多行“基于文本字段中的输入更改下拉值”

时间:2016-04-26 22:18:12

标签: javascript jquery drop-down-menu

首先,非常感谢你支持我:Change Dropdown values based on input in textfield

现在我需要扩展此功能。

以下是根据文本字段值更改下拉菜单的代码(非常感谢Rion Williams): https://jsfiddle.net/q5s24th2/

现在我想添加更多人,我也可以输入文本字段值,以便下拉菜单更改其内容。在这里,我创造了一些东西来增加更多人: https://jsfiddle.net/xsnLc48o/

 <p id="maintable">1:
  <input name="Year1" type="text" value="" />
  <select name="Results1">
    <option selected="selected" value="">please choose:</option>
    <option value="300" data-under-18="100" data-over-18="300">300.-</option>
    <option value="500" data-under-18="200" data-over-18="500">500.-</option>
    <option value="1000" data-under-18="300" data-over-18="1000">1000.-</option>
    <option value="1500" data-under-18="400" data-over-18="1500">1500.-</option>
    <option value="2000" data-under-18="500" data-over-18="2000">2000.-</option>
    <option value="2500" data-under-18="600" data-over-18="2500">2500.-</option>
  </select>

  <input name="Additional1" type="checkbox" title="Option" value="1" />Option
  </p>
  <p>
    <input type="button" value="+ Add Person" id="addRows" />
  </p>

不幸的是,对于添加的人来说,下拉功能不起作用(我尝试过几件事)。

如果有人知道怎么做,我会非常高兴。 也许比使用addRows / append功能有更好的可能性。

提前谢谢你。

祝你好运, 安迪

1 个答案:

答案 0 :(得分:0)

您可以通过创建一个克隆现有行并将其附加到内容的函数来实现此目的。最好考虑使用表格来更轻松地整理您的内容:

<table id="maintable">
    <tr class='person-row'>
       <td class='person-number'>...</td>
       <td>...</td>
       <td>...</td>
       <td>...</td>
    </tr>
 </table>

然后调整你的&#34;添加行&#34;函数克隆第一行,然后存储当前用户数的计数器,以便您可以按预期将其附加到name属性:

// When you add a new user
$("#addRows").click(function(){
        // Determine the next users number
        var nextUser = $('.person-row').length + 1;
        // Clone the first row
        var nextUserRow  = $('#maintable tr:first').clone();
        // Update your attributes
        $(nextUserRow).find('.person-number').text(nextUser + ':');
        $(nextUserRow).find('.person-year').attr('name','Year' + nextUser).val('');
        $(nextUserRow).find('.person-value').attr('name','Results' + nextUser);
        $(nextUserRow).find('.person-additional').attr('name','Additional' + nextUser);
        // Set the defaults for the row
        $(nextUserRow).find('select option:not(:first)').each(function() {
            var valueToUse = $(this).attr('data-over-18');
            $(this).val(valueToUse).text(valueToUse + '.-');
        });
        // Append the row
        $("#maintable").append(nextUserRow);
});

你可以see a working example of this in action here并在下面演示:

enter image description here