Reputation: 3538
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-" ?
Upvotes: 2
Views: 2677
Reputation: 1074
$(':checkbox').click(function(){
var parent_class = '';
parent_class = $(this).parent('div').attr('class').match(/food-\d+/);
alert(parent_class);
});
Upvotes: 0
Reputation: 207501
Use a regular expression
...attr("class").match(/food-\d+/)
if you want just the number
.match(/food-(\d+)/)[0]
Upvotes: 2
Reputation: 388316
Try a simple regex like
parent = $(this).closest(".formitem").attr("class").match(/\b(food-\d+)\b/)[1];
Upvotes: 6