Reputation: 245
How can I convert this JavaScript into jQuery?
The purpose of this is to auto-select the value of a dropdown that matches.
JS code :
window.onload = function(){
document.getElementsByName("title")[0].value="the_title_value";
}
Upvotes: 0
Views: 15375
Reputation: 505
For programmatically selecting a select element (drop-down list), if you have an Id on your select element, then jQuery makes it as simple as assigning a value to the element.
let dynamicValue = 'xyz'; //just ensure this value is on the target list
$("#idOfSelect").val(dynamicValue);
Please note that the onChange event will not be triggered by this. Also, the DOM state should be Ready as already pointed out by others.
Upvotes: 0
Reputation: 67505
You could use :eq
and name
selector inside ready
function to achieve that , check the example bellow.
Hope this helps.
$(function(){
$("select[name='title']:eq(0)").val('second');
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select name="title">
<option value='first'>First 1</option>
<option value='second'>Second 2</option>
<option value='third'>Third 3</option>
</select>
Upvotes: 0
Reputation: 10782
window.onload = function() {
// document.getElementsByName("title")[0].value="the_title_value";
// get all items with name "title" and then reduce the result set to the first element and then set the value
$('[name="title"]').first().val("the_title_value");
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<select name="title">
<option value='the_title_value_1'>the_title_value_1</option>
<option value='the_title_value'>the_title_value</option>
<option value='the_title_value_3'>the_title_value_3</option>
</select>
Upvotes: 0
Reputation: 120
$(document).ready(function(){
$('[name="title"]').val("the_title_value");
})
you only need first() if you have many elements with name="title" on the page. The reason why you have to put [0] in vanila javascript is because
document.getElementsByName("title")
returns an array of elements, even if there is only one with this name.
Upvotes: 0
Reputation: 5004
$(document).ready(function(){
$('select[name="title"]').first().val("the_title_value");
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<select name="title">
<option value='the_title_value1'>1</option>
<option value='the_title_value'>2</option>
<option value='the_title_valu3'>3</option>
</select>
Upvotes: 0
Reputation: 337560
You can select the elements by their name
attribute, then get the :first
of them before setting the current val()
, like this:
$(window).on('load', function() {
$('select[name="title"]:first').val('the_title_value')
});
Upvotes: 1