jQuery Selected
Im trying to see if a special option in a select-menu has a value equal to 1, and then hide another object. Ive been trying all day but cant figure it out (probably because im a total beginner at jquery)
I have a select-menu that i populated from a db. If the option with the id="1" have "selected=selected" then i want another div to hide when the page is loaded.
This is what i got so far:
<select>
<option id="3">test1</option>
<option id="1" selected="selected">test2</option>
<option id="2">test3</option>
</select>
<div id="hide">Hide me</div>
$("#1 option:selected").ready(function () {
$("#hide").hide();
});
开发者_开发百科
Any help would be greatly appreciated. Thanks.. /Andreas
There are a few things wrong with your code I'm afraid:
- You're using the event on the wrong object -
.ready()
should be applied to the document - IDs can't start with a number
- You should be using the value attribute instead of the id attribute.
- You're better off using
.val()
to get the value - You should give the select an id in case you add another one to the page.
Putting it all together:
<select id="foo">
<option value="3">test1</option>
<option value="1" selected="selected">test2</option>
<option value="2">test3</option>
</select>
<div id="hide">Hide me</div>
$(document).ready(function () {
if ($('#foo').val() != 1)
$("#hide").hide();
});
If you want to do this dynamically when the select is changed, you can do it like this:
$('#foo').change(function () {
if ($(this).val() != 1)
$("#hide").hide();
else
$("#hide").show();
});
First of all your id is not valid one. It should not start with a number. Provide an id to the select element and find the selected element and check its value to 1 and show/hide the appropriate div.
// assume your select has id="mySelect"
$(function() {
$('#mySelect').change(function() {
var value = $(this).val();
if (value == '1') {
$('#hide').hide();
} else {
$('#hide').show();
}
return false;
});
});
$(function() {
$('select').change(function(){
if ($("option:selected",this).attr('id') == 1 ){
$("#hide").hide();
}
});
});
Will work with what you have, but ditto the points raised by others -
- HTML spec states that you should not have ids starting with numbers
- Use the value attribute for options instead of an id
- You need to put the code in a function that will execute when the change event of the
<select>
is raised - Give the
<select>
an id to uniquely identify it.
精彩评论