Reputation: 1434
I have this form:
<form name="test">
<input type="radio" required="required" name="a" value="1">1
<input type="radio" required="required" name="a" value="X">X
<input type="radio" required="required" name="a" value="2">2
<br />
<input type="radio" required="required" name="b" value="1">1
<input type="radio" required="required" name="b" value="2">2
</form>
I want to achieve this:
If a=1 then b=1
If a=X then unset b
If a=2 then b=2
I tried this, but it doesn't do anything:
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$('#test').on('change', function() {
if ($("input[name='a']:checked").val()=="1") {
$( "#b" ).prop( "checked", true );
}
});
});
</script>
What's missing here?
Upvotes: 1
Views: 46
Reputation: 2650
You should bind the change
event to the radiobutton, not to the form.
Something like this:
HTML
<form name="test">
<input type="radio" required="required" name="a" value="1">1
<input type="radio" required="required" name="a" value="X">X
<input type="radio" required="required" name="a" value="2">2
<br />
<input type="radio" required="required" name="b" value="1">1
<input type="radio" required="required" name="b" value="2">2
</form>
Javascript
$(document).ready(function() {
$("input[name='a']").on("change", function() {
$("input[name='b']").prop("checked", false);
$("input[name='b'][value='" + $(this).val() + "']").prop("checked", true);
});
});
Upvotes: 2
Reputation: 29683
Bind change event on radio
button with name a
, get its value, find the same in radio button
with name b
set, and check its property, as below:
$('input[name="a"]').on('change', function() {
var selected = $('input[name="a"]:checked').val();
if (selected == "X") {
$('input[name="b"]:checked').prop("checked", false);
return false;
}
$('input[name="b"][value="' + selected + '"]').prop("checked", true);
});
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<form name="test">
<input type="radio" required="required" name="a" value="1">1
<input type="radio" required="required" name="a" value="X">X
<input type="radio" required="required" name="a" value="2">2
<br />
<input type="radio" required="required" name="b" value="1">1
<input type="radio" required="required" name="b" value="2">2
</form>
PS: If you wish you can add
disabled
property toradio button
set with nameb
so that user is not allowed to change them
Upvotes: 2