Karna
Karna

Reputation: 148

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. However the issues arises when the user decides to select something from the dropdown and then changes their mind and uses the button. 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

$(".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

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

Upvotes: 1

Views: 1488

Answers (1)

Swati
Swati

Reputation: 28522

You don't need to use loop just to remove selected .Instead only write your selected true or false inside your button handler.

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>

Upvotes: 1

Related Questions