[英]Getting a value from a dropdown data attribute and passing it to a input field
I'm trying to pass values that i have stored in a multiple dropdown list to relevant input fields on select. 我正在尝试将存储在多个下拉列表中的值传递给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.
我已经使其在一定程度上起作用,但是当输入字段和选择下拉列表不在父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? 如何获得在
material-pricex
上选择的数据价格值,以将其传递到“总计”输入字段?
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. 您的植入问题是使用
.parent()
,它只会插入所选元素的直接父元素,因此您的代码无法正常工作。
You can use .closest()
/ .parents()
to traverse up-to common ancestor then use .find()
to target the desired element. 您可以使用
.closest()
/ .parents()
遍历至共同祖先,然后使用.find()
定位所需的元素。
$(this).closest('.row').find('.material-total').val(materialValue);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.