Monday, June 3, 2024
 Popular · Latest · Hot · Upcoming
3
rated 0 times [  8] [ 5]  / answers: 1 / hits: 37080  / 14 Years ago, sat, december 4, 2010, 12:00:00

I need select's option to be actually selected on document ready depending on an input's value.



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!


More From » jquery

 Answers
10

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.


[#94728] Thursday, December 2, 2010, 14 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
micheleb

Total Points: 275
Total Questions: 103
Total Answers: 103

Location: Macau
Member since Sat, Jul 11, 2020
4 Years ago
;