簡體   English   中英

jQuery沒有在下拉列表中選擇正確的選項

[英]jQuery not selecting right option at form with dropdown

我在模式上有一個表單,其中包含以下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>

當我點擊具有以下jQuery腳本的事件時,我希望選擇正確的項目:

$(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');
  }
});

不幸的是,這不起作用,它顯示第一個選項作為選定的選項。 有人可以幫幫我嗎? 謝謝。

嘗試下一個解決方案,因為我不知道什么是“#updateElement”我會忽略它。

var userId = calEvent.user_id;
$("#user_id").val(userId).change();

此外,變量userId應保存string類型的值,例如:“1”,“2”或“3”。

如果您只是嘗試為所選框設置用戶ID,並假設,例如,用戶ID為#2在選項列表的值中,那么您需要做的就是這個。

  $("#user_id").val("2");

但是,您的標題表明您不是要設置所選選項的值,而是要讀取所選值。

$("#user_id").on("change", function() {
   console.log("User ID: " +  $("#user_id option:selected").val());
   console.log("User Name: " +  $("#user_id option:selected").text());
});

經過多次嘗試后,答案很簡單。 我不確定是不是因為我使用的是'Materialize',但是我必須在代碼中添加'formSelect()',所以這對我有用:

$("#user_id").val(userId).change();
$("#user_id").formSelect();

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM