Get & set drop down value using jQuery
If user select an option from dropdown it will shown it a textbox but if he select option having value "Other" then a row will appear to type value for other.
my code works fine except when option value is not equal to "Other"
<script type="text/javascript"><!--
function setAndReset(box) {
if(box.value 开发者_如何学C== 'Other'){
$("#ShowHide").hide();
}
document.FormName.hiddenInput.value = box.value;
}
//-->
</script>
<body bgcolor="#ffffff">
<form id="FormName" action="" method="get" name="FormName">
<select name="choice1" size="1" onchange="setAndReset(this);">
<option value="one">first</option>
<option value="two">second</option>
<option value="three">third</option>
<option value="other">Other</option>
</select>
<input type="text" name="hiddenInput" value="">
<tablt><tr id="ShowHide"><td>
<input type="text" name="otherInput">
</td></tr></table>
<input type="submit" name="submitButtonName">
</form>
</body>
but it does not show/hide & does not set value in textbox.
If it's solve using jquery then i will be thankful to you for you code.
Thanks.
Do it like this:
$(document).ready(function() {
$("select[name=choice1]").change(function() {
$(this).val() == 'other' ? $("#ShowHide").show() : $("#ShowHide").hide();
});
});
and lose the inline onchange function call. Try it here.
I like karim79's answer, but prefer it a bit more compact:
$(function() {
$("select[name=choice1]").change(function() {
$("#ShowHide").toggle($(this).val() === "other");
});
});
- Instead of
$(document).ready(f)
, do$(f)
, it's exactly the same - Instead of a loose
==
, use===
for a exact comparison (in this case it doesn't matter, but==
can behave strangely so you should avoid it everywhere) - Use
toggle(b)
instead ofshow()
/hide()
精彩评论