I have a list of states in an option menu. I'd like to run a bit of jquery only when either CA or NV are selected. Here is what I have:
$('#state').change(function(){ var text=$('#state :selected').val();
$('.st').val(text);
});
Which I tried (unsuccessfully) to adapt to another bit of jquery like this:
<script type="text/javascript">
$(document).ready(function() {
$("#state").change(function() {
if ($("#state opti开发者_如何学Goon[value='CA']").attr('selected')) {
$('#state').change(function(){ var text=$('#state :selected').val();
$('.st').val(text);
});
}
});
});
</script>
Any idea what needs to be changed for this to work?
Use
if ($("#state").val() == "CA")
jQuery val()
will return the selected value from a select
element.
Here's a working example: jsfiddle
EDIT: And here's one that clears the value too: jsfiddle
$(function() {
$("#state").change(function() {
var state = $(this).val();
$(".st").val((state == "CA") ? state : "");
})
});
You could try:
if ($("#state option[value='CA']:checked").length > 0) { ... }
Try this -
<script type="text/javascript">
$(document).ready(function() {
$("#state").change(function() {
if ($("#state").val()=='CA') {
//do something
}
});
});
</script>
I ended up doing this, slight edit of Town's code (to account for t states and have a non blank default value:
<script type="text/javascript"> $(function() { $("#state").change(function() { var state = $(this).val(); $(".st").val((state == "CA" || state == "NV") ? state : "auto"); }) }); </script>
精彩评论