Reputation: 25
First up, sorry about the title, I know it's not very specific, but I'm really stumped on what else to say.
So before I try and ramble on at what my problem is, you might as well check out this jsfiddle I made: http://jsfiddle.net/ax1ncdmu/2
How it works in this fiddle is exactly how I want it to work, but as you can see the jQuery is like this:
$(document).ready(function () {
$("input[name=guest0]").click(function () {
$('#guest0').toggle();
});
$("input[name=guest1]").click(function () {
$('#guest1').toggle();
});
$("input[name=guest2]").click(function () {
$('#guest2').toggle();
});
});
But it seems pretty sloppy to write out the code like that, just repeating the same thing over again. I feel like it should be obvious but I haven't worked with jQuery before, so I'm having a hard time figuring it out.
Is there a way to figure out the 'name' of the checkbox being clicked and then use that string to plug into the code? Or is that going the wrong way about it?
Upvotes: 2
Views: 132
Reputation: 22158
You can use jQueries attribute-starts-with-selector:
$(document).ready(function () {
// all inputs that its name starts with "guest"
$("input[name^=guest]").click(function () {
// read the name and apply to id
$('#'+$(this).attr('name')).toggle();
});
});
See it working:
http://jsfiddle.net/ax1ncdmu/7/
Upvotes: 8