Reputation: 657
I have a set of checkboxes. When I check the checkbox with the value 4, I want the checkbox with the value 2 to automatically get checked and also show a div with a message in it. When the checkbox with the value 4 is unchecked, I want the message to disappear. Message toggles with checkbox value 4.
I have been able to get the message to disappear after unchecking the checkbox value 4, but when I check it again, the message doesn't appear again and the checkbox with the value 2 doesn't auto checked again either.
HTML:
<input type="checkbox" value="2" id="user_role_ids_"><br>
<input type="checkbox" value="4" id="user_role_ids_"><br>
JS:
var chk1 = $("input#user_role_ids_[type='checkbox'][value='4']");
var chk2 = $("input#user_role_ids_[type='checkbox'][value='2']");
var checkmsg = $('<div/>', {'class': 'checkbox-message'}).html('If you are a Copywriter
Manager, you are also a Copywriter')
chk1.on('change', function(){
$(checkmsg).insertAfter("input#user_role_ids_[type='checkbox'][value='4']");
chk2.prop('checked',this.checked);
});
I am aware that you are not suppose to have two elements with the same id. Please do not comment on that.
Upvotes: 0
Views: 699
Reputation: 207557
With a CSS solution and adding the "dynamic" HTML directly into the layout, there is no need to have JavaScript involved
HTML:
<input type="checkbox" /><span>My Message!</span><br>
CSS:
[type="checkbox"] + span {
display:none;
}
[type="checkbox"]:checked + span {
display: inline;
}
DEMO:
If you want to do it in JavaScript with the same HTML it is just
$("#formId").on("change", '[type="checkbox"]', function() {
$(this).next("span").toggle(this.checked);
});
Add classes to make it more specific if you have additional checkboxes on the page.
Upvotes: 0
Reputation: 39
I suggest you target the checkboxes by simply their id and make sure they are unique
Demo
http://jsfiddle.net/q5Rr8/7/
var chk1 = $("#user_role_ids1");
var chk2 = $("#user_role_ids2");
chk1.on('change', function(){
$(checkmsg).insertAfter("#user_role_ids1");
chk2.prop('checked',this.checked);
});
Be careful of using css only solution as ':checked' is not supported in internet explorer before version 9, use feature detection or simply let javascript take care of it all
http://quirksmode.org/css/selectors/
Upvotes: 0
Reputation: 38262
You can toggle()
the message like this Demo.
First Hide the element:
var checkmsg = $('<div/>', .... Copywriter').hide();
Then toggle with the on(change)
chk1.on('change', function(){
$(checkmsg).insertAfter("input#... [value='4']").toggle();
chk2.prop('checked',this.checked);
});
Upvotes: 1