首页 > 解决方案 > 使用具有不同值的 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

标签: jqueryinputjquery-selectors

解决方案


推荐阅读