0

I'm trying to pass values that i have stored in a multiple dropdown list to relevant input fields on select. I have gotten it to work to a certain extent but i can't get it to work when the input field and the select drop down is not under the parent div.

Current working code

$(document).ready(function() {
  $('.select2').select2();
});

$(document).ready(function() {
  $('select.material-price').change(function() {
    var materialValue = $(this).select2().find(":selected").data("price");
    $(this).parent('.row').find('.material-total').val(materialValue);
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container">
  <div class="row">
    <select class="material-price select2">
        <option value="100" value="10">Material A</option>
        <option data-price="400" value="20>">Material B</option>
        <option data-price="500" value="30">Material C</option>
    </select>
    <input type="text" class="material-total" readonly />
  </div>
</div>

Code i'm trying to fix

<div class="row">
  <div class='col-md-2 nopadding'>
    <div class='form-group nomarg'>
      <select class="material-pricex select2">
        <option data-price="100" value="10">Material A</option>
        <option data-price="400" value="20>">Material B</option>
        <option data-price="500" value="30">Material C</option>
      </select>
    </div>
  </div>

  <div class='col-md-1 nopadding'>
    <div class='form-group nomarg'>
       <input type='number' id="total" name="total" min='0' class='form-control'>
    </div>
  </div>     
</div>

How can I get data-price value selected on material-pricex to pass it to the "total" input field?

2
  • $('#total').val(materialValue); keep it simple use ID selector to set value Commented Oct 30, 2017 at 13:30
  • @Satpal Yea i can do with single a row. But in my case i have multiple rows. What's the best way to target and get the value? I have duplicate rows in my scenario with the same ID and class names. Commented Oct 30, 2017 at 13:34

1 Answer 1

1

Problem with your implantation was usage of .parent() which only tragets the direct parent element of the selected element, thus your code didn't worked.

You can use .closest()/.parents() to traverse up-to common ancestor then use .find() to target the desired element.

$(this).closest('.row').find('.material-total').val(materialValue);
Sign up to request clarification or add additional context in comments.

1 Comment

Understood. Thank you very much. :) I'm kinda new to all of this so i'm tampering around. Thanks again!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.