简体   繁体   English

Javascript select 更改后的选项在按下按钮时不会更新

[英]Javascript select option after change won't update when button is pressed

I've come up against some weird behaviour that I can't seem to get working correctly.我遇到了一些我似乎无法正常工作的奇怪行为。 I have a book button where it would select the value from the dropdown which works fine.我有一个书本按钮,它将 select 下拉菜单中的值工作正常。 However the issues arises when the user decides to select something from the dropdown and then changes their mind and uses the button.但是,当用户决定从下拉列表中选择 select 然后改变主意并使用按钮时,就会出现问题。 The button then won't update the changed value within the dropdown.然后,该按钮将不会更新下拉列表中的更改值。 I figured this had to do something with the selected behaviour being turned to true, I tried to loop through the options and set them to false but it didn't fix the issue.我认为这必须将所选行为变为真,我试图循环通过选项并将它们设置为假,但它没有解决问题。 Any advice?有什么建议吗?

JS JS

$(".book-btn").click(function (e) {
  e.stopPropagation();
  $('#id_CourseName :selected').attr('selected',false);
  var courseTitle = $(this).parent().parent().children(".course-title-ref")[0].innerText;
  $(`#id_CourseName option:contains(${courseTitle})`).attr('selected', true);
});

$(document).ready(function(e){
  $("#id_CourseName").change(function(e){
    for(let i=0 ; i<$('#id_CourseName').length; i++){
      $('#id_CourseName').eq(i).attr('selected',false);
      }

  })
})

Edit编辑

For the HTML I'm using Django to render out the options of the dropdown对于 HTML 我使用 Django 呈现下拉选项

 <label for="">Service/Course</label>
 {{ form.CourseName }}

You don't need to use loop just to remove selected .Instead only write your selected true or false inside your button handler.您不需要使用循环来删除selected的 . 而只需在按钮处理程序中写入您选择的 true 或 false 。

Demo Code :演示代码

 $(".book-btn").click(function(e) { e.stopPropagation(); $('#id_CourseName option:selected').prop('selected', false); var courseTitle = "1"; //just for demo... $(`#id_CourseName option:contains(${courseTitle})`).prop('selected', true); });
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <select id="id_CourseName"> <option>1</option> <option>2</option> <option>3</option> </select> <button class="book-btn">Book</button>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM