I have many divs in a page, like so:
<div class="formitem food-6 group-7">
//content of div
<input type="checkbox"> //child of div
</div>
<div class="formitem food-7 group-7">
//content of div
<input type="checkbox"> //child of div
</div>
When a checkbox is checked, I want to store the value of it's parent's unique class e.g "food-6" or "food-7" in a variable. I can get all the classes of the parent, like this:
parent = $(this).closest(".formitem").attr("class");
Which gives me formitem food-7 group-7
.
How can I get "the one that starts with food-" ?
I have many divs in a page, like so:
<div class="formitem food-6 group-7">
//content of div
<input type="checkbox"> //child of div
</div>
<div class="formitem food-7 group-7">
//content of div
<input type="checkbox"> //child of div
</div>
When a checkbox is checked, I want to store the value of it's parent's unique class e.g "food-6" or "food-7" in a variable. I can get all the classes of the parent, like this:
parent = $(this).closest(".formitem").attr("class");
Which gives me formitem food-7 group-7
.
How can I get "the one that starts with food-" ?
Share Improve this question asked Oct 28, 2013 at 16:12 IlaIla 3,5488 gold badges50 silver badges78 bronze badges 1-
4
Since it looks like you're using this
food-7
class for putation instead of CSS, have you considered usingdata-
attributes instead? – Joe Enos Commented Oct 28, 2013 at 16:14
3 Answers
Reset to default 6Try a simple regex like
parent = $(this).closest(".formitem").attr("class").match(/\b(food-\d+)\b/)[1];
Use a regular expression
...attr("class").match(/food-\d+/)
if you want just the number
.match(/food-(\d+)/)[0]
$(':checkbox').click(function(){
var parent_class = '';
parent_class = $(this).parent('div').attr('class').match(/food-\d+/);
alert(parent_class);
});