Eyal
Eyal

Reputation: 4763

Select previous element by it's class part string

I have the follwoing HTML:

<div id="divAreaId_1" class="SuppAreaParentDiv">
       <input type="hidden" value="3" class="hdnMaxSelection_1" id="hdnMaxSelection_1">

       <input type="checkbox" id="SuppItemId_2" class="chkSuppItem"> <br /> 
       <input type="checkbox" id="SuppItemId_3" class="chkSuppItem"> <br /> 
       <input type="checkbox" id="SuppItemId_4" class="chkSuppItem"> <br />
       <input type="checkbox" id="SuppItemId_5" class="chkSuppItem"> <br />

I am trying to get the 'input:hidden' value when any checkbox is checked! I need to do it by the 'input:hidden' partial class name:

$(".chkSuppItem").click(function () {
   var hdnMaxSelection = $(this).prev("[class*='hdnMaxSelection_']").val();
   alert(hdnMaxSelection); // I am getting here 'undefined'.

Upvotes: 1

Views: 40

Answers (2)

Felix
Felix

Reputation: 38102

You can use siblings():

var hdnMaxSelection = $(this).siblings("[class*='hdnMaxSelection_']").val();

Currently, your selector only correct for the first checkbox since the hidden input is the immediately preceding sibling element of your first checkbox.

With siblings(), as long as your hidden input is the sibling of your checkboxes, then it'll work.

Fiddle Demo

Upvotes: 1

Rajaprabhu Aravindasamy
Rajaprabhu Aravindasamy

Reputation: 67187

You have to use .siblings() in this context. Because .prev() will only look for the immediate previous sibling with the provided constraint.

Try,

$(".chkSuppItem").click(function () {
   var hdnMaxSelection = $(this).siblings("[class*='hdnMaxSelection_']").val();
   alert(hdnMaxSelection); 
});

Or you can try with .prevAll(selector),

$(".chkSuppItem").click(function () {
   var hdnMaxSelection = $(this).prevAll("[class*='hdnMaxSelection_']").first().val();
   alert(hdnMaxSelection); 
});

DEMO for .prevAall()

Upvotes: 1

Related Questions