Reputation: 45
I have a form on a modal with the following HTML:
<div class="input-field col m2 s12">
<select id="user_id" name="user_id">
<option value="1">John</option>
<option value="2">Jane</option>
<option value="3">Joe</option>
</select>
<label for="user_id">User</label>
</div>
I want the right item to be selected when I click on an event with the following jQuery script:
$(document).ready(function () {
$('#calendar').fullCalendar({
themeSystem: 'jquery-ui',
slotLabelFormat: "HH:mm",
timeFormat: 'h:mm',
businessHours: {
start: '08:00', // a start time (10am in this example)
end: '19:00', // an end time (6pm in this example)
},
header: {
left: 'prev,next today',
center: 'title',
right: 'month,agendaWeek,agendaDay,listMonth'
},
buttonText: {
today: 'Vandaag',
month: 'Maand',
week: 'Week',
day: 'Dag',
list: 'Lijst'
},
defaultView: 'month',
weekNumbers: false,
weekends: false,
eventLimit: true, // allow "more" link when too many events
events: 'urltoEvents',
eventClick: function (calEvent, jsEvent, view) {
var eventId = calEvent.id;
var userId = calEvent.user_id;
var comment = calEvent.comment;
var startTime = calEvent.start_time;
var startDate = calEvent.start_date;
var endTime = calEvent.end_time;
var endDate = calEvent.end_date;
$("#updateEvent #start_time").val(startTime);
$("#updateEvent #start_date").val(startDate);
$("#updateEvent #end_time").val(endTime);
$("#updateEvent #end_date").val(endDate);
$("#updateEvent #user_id").val(userId).attr("selected", "selected");
$("#updateEvent #eventId").val(eventId);
$("#updateEvent #comment").val(comment);
$('#updateEvent').modal('open');
}
});
Unfortunately this is not working and it's showing the first option as the selected one. Can somebody help me with this please? Thanks.
Upvotes: 1
Views: 54
Reputation: 45
After trying a lot the answer was quiet simple. I am not sure if it's because I am using 'Materialize', but I had to add 'formSelect()' to the code, so this was working for me:
$("#user_id").val(userId).change();
$("#user_id").formSelect();
Upvotes: 0
Reputation: 1381
If you are just trying to set the user id for the selected box and assuming, for example, that the user id is #2 is in the value of the options list then all you need to do is this.
$("#user_id").val("2");
However, your title suggests that you are not trying to set the value of the selected option but rather to read the selected value.
$("#user_id").on("change", function() {
console.log("User ID: " + $("#user_id option:selected").val());
console.log("User Name: " + $("#user_id option:selected").text());
});
Upvotes: 1
Reputation: 17190
Try next solution, since i don't know what is "#updateElement" i will ignore it.
var userId = calEvent.user_id;
$("#user_id").val(userId).change();
Also, the variable userId should hold values of type string, for example: "1", "2" or "3".
Upvotes: 2