javascript - passing a variable to .html() function -
javascript - passing a variable to .html() function -
<!-- select drop downwards menu (works fine) --> <select id="select-event-type"> <?php foreach ($this->events $event) { echo "<option value='" .$event->event_id. "'>" .$event->event_title."</option>"; }?> </select> <!-- javascript, supposed output according chosen alternative in select drop downwards --> <script> (function ($) { var events = <?php echo (count($this->events) > 0) ? json_encode($this->events) : "null"; ?>; $(document).ready(function() { $('#select-event-type').change(function() { if (events) { var event = events[this.selectedindex]; $('#event-details').html(event); } }); }); })($); </script> <!-- in div output displayed --> <div id="event-details"></div>
the event variable undefined. if illustration this: var event = 'hello'
output 'hello' supposed to. problem seems part: events[this.selectedindex];
. did wrong? new this. give thanks much help!! update: console output (in chrome):
<script> (function ($) { var events = json.parse({"1":{"event_id":"1","event_title":"event1","event_desc":"event1","event_location":"eventlocation","event_requirements":"event1","event_date":"2022-07-20 15:00:00"},"2":{"event_id":"2","event_title":"event2","event_desc":"event2","event_location":"eventlocation","event_requirements":"event2","event_date":"2015-04-20 15:00:00"},"3":{"event_id":"3","event_title":"event3","event_desc":"event3","event_location":"eventlocation","event_requirements":"event3","event_date":"2019-11-20 16:00:00"}}); $(document).ready(function() { $('#select-event-type').change(function() { if (events) { var event = events[$(this).selectedindex]; $('#event-details').html(event); } }); }); </script>
json:
{ "1": { "event_id": "1", "event_title": "event1", "event_desc": "event1", "event_location": "eventlocation", "event_requirements": "event1", "event_date": "2022-07-20 15:00:00" }, "2": { "event_id": "2", "event_title": "event2", "event_desc": "event2", "event_location": "eventlocation", "event_requirements": "event2", "event_date": "2015-04-20 15:00:00" }, "3": { "event_id": "3", "event_title": "event3", "event_desc": "event3", "event_location": "eventlocation", "event_requirements": "event3", "event_date": "2019-11-20 16:00:00" } }
to value of select
element utilize this.value
. change:
var event = events[this.selectedindex];
to:
var event = events[this.value];
however, if json array indices 0,1,2,3,4
rather object alternative values keys
utilize of this.selectedindex
correct.
update:
in lite of sample json posted right code should be:
var event = events[this.selectedindex + 1].event_title;
special note
you can event info using either:
var event = json.stringify( events[this.selectedindex + 1] ); //gives string of
or build how want so:
var event = $('<div/>'); $.each( events[this.selectedindex + 1], function(k,v) { event.append( $('<div/>',{text:k + ': ' + v}) ); });
javascript jquery
Comments
Post a Comment