Rojj
Rojj

Reputation: 1210

Change selected option in jQuery

My html is

<select name="one_day_per_month" id="one_day_per_month" style="width: 200px">
  <option value="false" selected>No</option>
  <option value="true">Yes</option>
</select>

The page is wrapped with

$( document ).ready(function() {...}

I can change the value by using

$("#one_day_per_month").val("true")

The value is updated, but the dropdown list does not change in the browser does not change. What am I doing wrong?

Upvotes: 0

Views: 1004

Answers (2)

Suchit kumar
Suchit kumar

Reputation: 11859

Try this call trigger with change to achieve your requirement.

$( document ).ready(function() {
$("#one_day_per_month").val("true").trigger("change");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select name="one_day_per_month" id="one_day_per_month" style="width: 200px">
  <option value="false" selected>No</option>
  <option value="true">Yes</option>
</select>

Upvotes: 1

AlexStack
AlexStack

Reputation: 17381

Your code is probably running before the HTML tags for your select element is loaded. You have two ways to fix it:

  1. Put your script at the end of your HTML right before the tag
  2. Embed all your code in $(function () { /* your code here */}); This makes sure that your code runs after the HTML is entirely loaded and parsed in the browser.

Upvotes: 0

Related Questions