How to autoselect option depending on input's value
I need select's option to be actually selected on document ready depending on an input's valu开发者_开发技巧e.
Example:
<select id="mySelect">
<option value="1">myVal1</option>
<option value="2">myVal2</option>
</select>
<input type="text" id="myId" value="2">
For example, we've got a predefined value '2' of the input on page load. I need select-box to be auto-selected with it's option having the same value as input 'myId'. I mean 'mayVal1' must be selected.
When input has no value select must behave as default.
Thanks!
Your mention of "on document ready" sort of suggests that you might be using jQuery, with that assumption made (albeit perhaps erroneously), I offer you this:
$(document).ready(
function(){
var theValue = $('#myId').val();
$('option[value=' + theValue + ']')
.attr('selected',true);
});
With a demo at JS Fiddle.
Edited in response to OP's question:
How do I compare option's value to very first word in the input's value? I mean if I have option value 'hello' and input value 'hello world' script have to select option containing 'hello' in its value.
Right, given the disparity between your posted example and your question, I'm going to try to address both of the possibilities.
First, to select an option
based on its text component (in your above code, the 'myVal1','myVal2' bits):
$(document).ready(
function() {
$('form:eq(0)').submit(
function() {
var theValue = $('#myId').val().split(" ",1);
$('option:contains(' + theValue + ')').attr('selected', true);
return false;
});
});
JS Fiddle demo: note that the text component of the option
element does not represent the value of the option
element.
Secondly, if you want to link the first part of the value entered into the myId
input element to the value of the select
/option
element(s):
$(document).ready(
function() {
$('form:eq(0)').submit(
function() {
var theValue = $('#myId').val().split(" ",1);
$('option[value=' + theValue + ']').attr('selected', true);
return false;
});
});
JS Fiddle demo.
These demos could work with keyup()
, or equivalent actions/events, but submit()
seemed the better choice.
something like below should work///
<select>
<option value="0">One</option>
<option value="1">Two</option>
</select>
$(document).ready(
var inputValue = $('#id').val();
$('select').val('1'); // selects "Two"
$('select').val(inputValue); // also selects "Two"
});
in vanilla JS:
var listener = function(ev){
var input = document.getElementById('myId');
for(var i = 0, elems = document.getElementById('mySelect'), l = elems.length; i < l; i++)
elems[i].selected = elems[i].value == input.value;
}
listener();
document.getElementById('myId').addEventListener('change', listener, false);
with jQuery:
$(function(){
$('#myId').change(function(){
$('#mySelect option').removeAttr('selected').filter('[value=' + $(this).val() + ']').attr('selected', true);
}).change()
})
$('#mySelect').val('2').change();
精彩评论