【问题标题】:How to Link checkbox to textfield in html/PHP如何将复选框链接到 html/PHP 中的文本字段
【发布时间】:2017-04-11 08:56:43
【问题描述】:

有什么方法可以将复选框链接到文本框。例如

<form>
<table>
    <tr>
       <td><input name="databaseIDs[]" type="checkbox" value="49"/></td>
       <td><input type="text" name="first" value="First Input"/></td>
    </tr>
   <tr>
     <td><input name="databaseIDs[]" type="checkbox" value="50"/></td>
     <td><input type="text" name="first" value="Second Input"/></td>
  </tr>

<tr>
   <td><input name="databaseIDs[]" type="checkbox" value="60"/></td>
   <td><input type="text" name="first" value="Third Input"/></td>
</tr>
<tr>
  <td><input name="databaseIDs[]" type="checkbox" value="38"/></td>
  <td><input type="text" name="first" value="Fourth Input"/></td>
</tr>
</table>

</form>

如您所见,复选框是一个数组,每个复选框的值都是数据库 id。我想要实现的是更新数据库值,其中 id 等于用户勾选的复选框的 id。例如,如果用户勾选第一个复选框(值为49),并提交表单,数据库将更新id为49的数据库中的值。

【问题讨论】:

    标签: php jquery checkbox


    【解决方案1】:

    此解决方案适用于您的情况,无需对您的 html 标记进行任何修改。

    如果您得到id of 复选框,那么您可以获得与该复选框相关的输入字段的值,如下所示:

    <script>
    var id = 49;//you will get this id after form submission, i assumed it 49 for example
    $('input[type="checkbox"]').each(function(){
        if($(this).attr('id')===id){
            var desired_value = $(this).parent().find('input[type="text"]').val();
        }
    });
    console.log(desired_value);//First Input// use desired value as you like
    </script>
    

    希望对你有帮助

    【讨论】:

    • 感谢您的贡献。我很感激
    【解决方案2】:

    这个问题不需要任何 jQuery(或者 javascript)。由于您使用的是复选框而不是单选按钮,因此我假设您希望一次能够更新多个实体。

    实现此目的的最简单方法是按如下方式设置表单:

    <table>
        <tr>
          <td><input name="selected_ids[]" type="checkbox" value="49"/></td>
          <td><input type="text" name="data[49][name]" value="First Input"/></td>
        </tr>
      <tr>
        <td><input name="selected_ids[]" type="checkbox" value="50"/></td>
        <td><input type="text" name="data[50][name]" value="Second Input"/></td>
      </tr>
    
    <tr>
      <td><input name="selected_ids[]" type="checkbox" value="60"/></td>
      <td><input type="text" name="data[60][name]" value="Third Input"/></td>
    </tr>
    <tr>
      <td><input name="selected_ids[]" type="checkbox" value="38"/></td>
      <td><input type="text" name="data[38][name]" value="Fourth Input"/></td>
    </tr>
    </table>
    

    如您所见,复选框将代表您要更新的实体。当表单提交时,您最终会得到一个包含 0 个或多个 ID 的数组,每个 ID 对应一个选中的复选框。然后,您可以遍历这个 ID 数组,在 data 关联数组中获取与 name 匹配的值。这个循环看起来像这样:

    foreach($_POST['selected_ids'] as $id){
      $name = $_POST['data'][$id]['name'];
      //TODO: update the database
    }
    

    此设置允许您通过按照约定 &lt;input name="data[&lt;entity id&gt;][&lt;database field&gt;]"&gt; 创建 &lt;input&gt;s 来非常轻松地为每个实体添加更多数据

    【讨论】:

    • 非常感谢您的回答。这正是我一直在努力实现的目标。你的回答100%解决了这个问题。我很感激。
    猜你喜欢
    • 2014-11-05
    • 1970-01-01
    • 1970-01-01
    • 2019-10-03
    • 2021-07-04
    • 1970-01-01
    • 2016-03-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多