jquery - 使用具有不同值的 jQuery 定位多个输入
问题描述
我有 20 多个不同的输入字段,都有唯一的 ID。在每个输入旁边,有一个按钮会弹出一个模式,允许用户选择一些预定义的值。模态总是相同的。
我想要以下功能:
我希望每个按钮都与特定的输入字段相关联。基本上来说,如果您点击 input#1 旁边的按钮并选择某个值,则该值需要进入 input#1 内部,而不是其他任何地方。与 input#2 相同 - 如果我点击 input#2 旁边的模态按钮并选择另一个值,则该值现在需要进入 input#2 并且不覆盖以前的输入或转到其他任何地方。
希望这是有道理的!我知道解决方案可能很简单,但是我被卡住了。
HTML 代码:
<!-- First input -->
<input type="text" class="form-control" id="inputOne" name="heatloss_floorUValue">
<!-- Second input -->
<input type="text" class="form-control" id="inputTwo" name="heatloss_externalWallsUValue">
<!-- Button that brings modal
ITS THE SAME code for each button,
might this be the problem? -->
<button type="button" class="calc-uv btn btn-dark mb-3 " data-toggle="modal" data-target="#calculateUValue"><i class="fas fa-chevron-right"></i> Calculate U-Value</button>
<!-- this is how modal HTML code looks -->
<table class="table table-responsive table-striped wall uvalue-table" id="solidWall">
<tbody>
<tr>
<td>Brick 102 mm</td>
<td>Dense Plaster</td>
<td>2.97</td>
<td><a href="#" class="text-warning">Select</a></td>
</tr>
<tr>
<td>Brick 228 mm</td>
<td>Dense Plaster</td>
<td>2.11</td>
<td><a href="#" class="text-warning">Select</a></td>
</tr>
<!-- ETC Plenty more choices to choose from --> >
jQuery:
// Choose a pre-defined value from the modal pop-up
$(".uvalue-table a").click(function(u){
u.preventDefault();
// Store this value in a variable
var uValueOne = $(this).parent().prev().text();
console.log("the new value is"+" "+ uValueOne);
// Hide modal, because we've chosen our value
$("#calculateUValue").modal('hide');
// Target inputOne and insert the variable inside
$("#inputOne").val(uValueOne);
});
// This part works well. However,
// If i try the same code targeting different input ID
// it doesn't work
$(".uvalue-table a").click(function(u){
u.preventDefault();
var uValueTwo = $(this).parent().prev().text();
console.log("the new value is"+" "+ uValueTwo);
$("#calculateUValue").modal('hide');
$("#inputTwo").val(uValueTwo);
});
//what happens is the 2nd input never gets uValueTwo (or any value at all) and console log prints the same string twice
解决方案
推荐阅读
- python - 是否有自定义方法来收集 pytest 结果?
- c - FILE 结构中未使用的变量
- ios - AFNetworking 3.2.0 ' 配置的安全策略只能应用于具有安全基本 URL(即 https)的管理器
- javascript - javascript 超时如何在执行堆栈中工作?
- reactjs - Material-UI:长文本包裹在网格中
- python - 如何仅操作属于 Pandas DataFrame 中对象列表的某些元素
- ruby-on-rails - 检查 RSpec 中仅在创建时运行的自定义验证
- excel - 识别模式并提取子字符串
- python - mpl_to_plotly 没有显示预期的图例
- magento - 如何在 Magento 中导出类别描述