I have this form:
<input type="checkbox" value="First" />First
<input type="checkbox" value="Second" />Second
<input type="checkbox" value="Third" />Third
<select name="first-drop">
<option value="---">---</option>
<option value="Option1">Option1</option>
<option value="Option2">Option2</option>
</select>
Is there a way (using JS/jQuery) I can change the value of first-drop to --- whenever the First check box is unchecked?
$('input[type="checkbox"][value="First"]').change(function (){
$('select[name="first-drop"]').toggle();
});
LIVE DEMO
Note that I fixed you markup:
<input type="checkbox" value="First" checked="checked" >First
<input type="checkbox" value="Second" />Second
<input type="checkbox" value="Third" />Third
<select name="first-drop">
<option value="">---</option>
<option value="Option1">Option1</option>
<option value="Option2">Option2</option>
</select>
Update:
What you want now is:
$('input[type="checkbox"][value="First"]').change(function() {
if (!this.checked) {
$('select[name="first-drop"] option:first').prop('selected', 'selected');
}
});
LIVE DEMO
If you will give your DOM elements ids it can be simple as that:
$('#first').change(function() {
if (!this.checked)
$('#nothing').prop('selected', 'selected');
});
Updated DOM:
<input type="checkbox" value="First" id="first" >First
<input type="checkbox" value="Second">Second
<input type="checkbox" value="Third">Third
<select name="first-drop">
<option value="" id="nothing" >---</option>
<option value="Option1" >Option1</option>
<option value="Option2">Option2</option>
</select>
LIVE DEMO
I added an ID to the first checkbox
<input id="first" type="checkbox" value="First">First</input>
<input type="checkbox" value="Second">Second</input>
<input type="checkbox" value="Third">Third</input>
<select name="first-drop">
<option value="">---</option>
<option value="Option1">Option1</option>
<option value="Option2">$Option2</option>
</select>
<script type="text/javascript">
$(function () {
$("#first").click(function () {
if ($(this)[0].checked == true) {
$("[name='first-drop'] option:first").attr("selected", "selected");
}
});
});
</script>
Demo:
http://jsfiddle.net/8BtYc/2/
Edit: Fixed my code so that it doesn't toggle when you uncheck the first checkbox
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With