Arka
Arka

Reputation: 591

jquery chaining not working in my html with each function

Here is my html

<div  class="productcheck">

    <div class="expenserow1">
        <select name="product[]" class='product_name'>
            <option value="A">A</option>
            <option value="B">B</option>
            <option value="C">C</option>
        </select>
    </div>
    <div class="expenserow2">
        <input type="text" name="productpercent[]" size=3 maxlength=3 value="100">
    </div>
</div>
<div  class="productcheck">
    <div class="expenserow1">
        <select name="product[]" class='product_name'>
            <option value="A">A</option>
            <option value="B">B</option>
            <option value="C">C</option>
        </select>
    </div>
    <div class="expenserow2">
        <input type="text" name="productpercent[]" size=3 maxlength=3 value="100">
    </div>
</div>
<div  class="productcheck">
    <div class="expenserow1">
        <select name="product[]" class='product_name'>
            <option value="A">A</option>
            <option value="B">B</option>
            <option value="C">C</option>
        </select>
    </div>
    <div class="expenserow2">
        <input type="text" name="productpercent[]" size=3 maxlength=3 value="100">
    </div>

</div>

JS:

<script>
$(document).ready(function(){
  $(".productcheck .expenserow2 input[type='text']").each(function() {
            var product_percentage=$(this).val();
            var product_name=$(this).closest('.product_name:selected').val();
            console.log(product_percentage);
  });
});
</script>

Im getting product_percentage value correctly, but not able to get product_name value.

Upvotes: 1

Views: 439

Answers (2)

Milind Anantwar
Milind Anantwar

Reputation: 82241

You need to use correct selector to target the select element. use:

$(this).parent().prev().find('.product_name').val();

Working Demo

Upvotes: 2

Satpal
Satpal

Reputation: 133433

Problem is with your selector. product_name is not a parent of textbox so your code is not working.

Use

var product_name = $(this)
    .closest('.productcheck') //traverse to parent productcheck
    .find('.product_name').val(); //Use .find() to search product_name You don't need selected here

DEMO

Upvotes: 2

Related Questions