读取动态添加的复选框值

如何解决读取动态添加的复选框值

<head>
    <title>jQuery Add & Remove Dynamically Input Fields in PHP</title>
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
</head>

<body>
    <h1>jQuery Add & Remove Dynamically Input Fields in PHP</h1>
    <form method="post" action="">
        <div class="form-group fieldGroup">
            <div class="input-group">
                <input type="text" name="phno[]" class="form-control" placeholder="Enter No" />
                <input type="checkbox" name="cdr[]" class="checkbox-inline cdr" />
                <input type="checkbox" name="caf[]" class="checkbox-inline caf" />
                <div class="input-group-addon">
                    <a href="javascript:void(0)" class="btn btn-success addMore"><span class="glyphicon glyphicon glyphicon-plus" aria-hidden="true"></span> Add</a>
                </div>
            </div>
        </div>
        <input type="submit" name="submit" class="btn btn-primary" value="SUBMIT" />
    </form>
    <!-- copy of input fields group -->
    <div class="form-group fieldGroupCopy" style="display: none;">
        <div class="input-group">
            <input type="text" name="phno[]" class="form-control" placeholder="Enter No" />
            <input type="checkbox" name="cdr[]" class="checkbox-inline cdr" />
            <input type="checkbox" name="caf[]" class="checkbox-inline caf" />
            <div class="input-group-addon">
                <a href="javascript:void(0)" class="btn btn-danger remove"><span class="glyphicon glyphicon glyphicon-remove" aria-hidden="true"></span> Remove</a>
            </div>
        </div>
    </div>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.0.0-rc1/jquery.min.js"></script>
    <script>
    $(document).ready(function() {
        //group add limit
        var maxGroup = 10;

        //add more fields group
        $(".addMore").click(function() {
            if ($('body').find('.fieldGroup').length < maxGroup) {
                var fieldHTML = '<div class="form-group fieldGroup">' + $(".fieldGroupCopy").html() + '</div>';
                $('body').find('.fieldGroup:last').after(fieldHTML);
            } else {
                alert('Maximum ' + maxGroup + ' groups are allowed.');
            }
        });

        //remove fields group
        $("body").on("click",".remove",function() {
            $(this).parents(".fieldGroup").remove();
        });

    });
    </script>
</body>

在上面的代码中,我得到了复选框的值,但不对应于文本字段的值

请帮助

我需要把它作为例如数据 如果我输入 abcd ,然后选中与其关联的一个复选框,则我需要的是单击复选框的abcd值 这将重复输入组的数量

解决方法

我假设“ cdrtxt”与“ .cdr”位于同一节点吗?

在.cdr上使用.parent()

$(document).on('click','.cdr',function() {
     alert(1);
     $(this).parent().find('.cdrtxt').val("1");
});
,

这一行代码有几个问题:

$("this").find('.cdrtxt').val("1");
  1. 没有$("this")这样的东西。至少如果您的HTML中没有非标准的<this>标记。当您要引用接收事件的节点并将其包装在jQuery对象中时,应使用$(this)
  2. HTML代码中没有cdrtxt类。

您所遇到的解决方案是搜索单击复选框的文本输入同级。像这样:

$(this).siblings('input[type=text]').val('something');
,
<input type="text" name="phno[]" class="form-control" placeholder="Enter No" />
<input type="checkbox" name="cdr[]" class="checkbox-inline cdr" />

不能使用此命名方案正确关联文本输入字段值和复选框值。

文本字段总是会在表单提交数据集中产生一个条目,即使它们为空-复选框也不会,只有在实际选中的地方才创建一个。

如果您具有以上字段的四次组合,但是只选中了第一个和第三个复选框,那么您将获得$_POST['phno']作为四个文本值的数组,它们的索引从0到3,而{{ 1}}将仅包含两个 复选框值(您在此处未明确指定一个,因此这些复选框将提交值$_POST['cdr']),索引值为0和1。

基于这些索引,现在无法知道选中哪个复选框的哪个。如果您选择了第三和第四,则仍然在索引on0下获得这些值。

您需要在此处预先指定索引:

1

,并且下一组<input type="text" name="phno[0]" class="form-control" placeholder="Enter No" /> <input type="checkbox" name="cdr[0]" class="checkbox-inline cdr" /> 必须成为0,依此类推。

然后选中的复选框将获得与文本字段相对应的索引。

1的索引中仍然存在“空洞”-如果选中第一个(索引0)和第四个(索引3),则$_POST['cdr']$_POST['cdr'][0]会之后再设置。
但是,如果循环遍历包含从0到3的所有索引的$_POST['cdr'][3],则可以使用该索引值来检查$_POST['phno']中的相应索引是否已设置。

因此,您将必须修改JavaScript部分,即简单地“克隆”现有行,以便它设置适当的字段名称,包括索引。

,

复选框的问题在于,如果未选中该复选框,则不会与表单一起发布。如果选中复选框并发布表单,则将在$ _POST变量中获取复选框的值,如果未选中,则不会为$ _POST变量赋值。为了知道选中了哪个复选框,请为其分配一个不同的值。这段代码可以解决您的问题

<?php

if(isset($_POST['submit'])){

if(isset($_POST['checkbox'])){
echo 'Checkbox: ';
print_r($_POST['checkbox']);
}



if(isset($_POST['text'])){
$text=$_POST['text'];
echo 'Textbox: ';
print_r($text);

}
}
  ?>

<!DOCTYPE html>
<html>
<head>
    <title></title>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
</head>
<body>
<form method="POST" action="tests.php">
<input type="checkbox" name="checkbox[]" class="check"  value="1">
<br>
<input type="checkbox" name="checkbox[]" class="check"  value="2">
<br>
<input type="checkbox" name="checkbox[]" class="check"  value="3">
<br>
<input type="text" name="text[]" class="text">
<br>

<br>
<input type="submit" name="submit">
</form>
<button id="add">ADD</button>
</body>
<script>
$(document).ready(function()
{
$('#add').on('click',function()
{
var breaks="<br>"
var checkbox="<br>";
var textbox="<br><input type='text' name='text[]' class='text'>";
var check_length=$('.check').length;

console.log(check_length);
for(var i=check_length+1;i<check_length+4;i++)
{   
    checkbox=checkbox+"<input type='checkbox' name='checkbox[]' class='check' value='" + i + "'><br>";
    

}
$('input[type="text"]').last().after(checkbox,textbox);
});
    });
</script>

</html>

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


依赖报错 idea导入项目后依赖报错,解决方案:https://blog.csdn.net/weixin_42420249/article/details/81191861 依赖版本报错:更换其他版本 无法下载依赖可参考:https://blog.csdn.net/weixin_42628809/a
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下 2021-12-03 13:33:33.927 ERROR 7228 [ main] o.s.b.d.LoggingFailureAnalysisReporter : *************************** APPL
错误1:gradle项目控制台输出为乱码 # 解决方案:https://blog.csdn.net/weixin_43501566/article/details/112482302 # 在gradle-wrapper.properties 添加以下内容 org.gradle.jvmargs=-Df
错误还原:在查询的过程中,传入的workType为0时,该条件不起作用 &lt;select id=&quot;xxx&quot;&gt; SELECT di.id, di.name, di.work_type, di.updated... &lt;where&gt; &lt;if test=&qu
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct redisServer’没有名为‘server_cpulist’的成员 redisSetCpuAffinity(server.server_cpulist); ^ server.c: 在函数‘hasActiveC
解决方案1 1、改项目中.idea/workspace.xml配置文件,增加dynamic.classpath参数 2、搜索PropertiesComponent,添加如下 &lt;property name=&quot;dynamic.classpath&quot; value=&quot;tru
删除根组件app.vue中的默认代码后报错:Module Error (from ./node_modules/eslint-loader/index.js): 解决方案:关闭ESlint代码检测,在项目根目录创建vue.config.js,在文件中添加 module.exports = { lin
查看spark默认的python版本 [root@master day27]# pyspark /home/software/spark-2.3.4-bin-hadoop2.7/conf/spark-env.sh: line 2: /usr/local/hadoop/bin/hadoop: No s
使用本地python环境可以成功执行 import pandas as pd import matplotlib.pyplot as plt # 设置字体 plt.rcParams[&#39;font.sans-serif&#39;] = [&#39;SimHei&#39;] # 能正确显示负号 p
错误1:Request method ‘DELETE‘ not supported 错误还原:controller层有一个接口,访问该接口时报错:Request method ‘DELETE‘ not supported 错误原因:没有接收到前端传入的参数,修改为如下 参考 错误2:cannot r
错误1:启动docker镜像时报错:Error response from daemon: driver failed programming external connectivity on endpoint quirky_allen 解决方法:重启docker -&gt; systemctl r
错误1:private field ‘xxx‘ is never assigned 按Altʾnter快捷键,选择第2项 参考:https://blog.csdn.net/shi_hong_fei_hei/article/details/88814070 错误2:启动时报错,不能找到主启动类 #
报错如下,通过源不能下载,最后警告pip需升级版本 Requirement already satisfied: pip in c:\users\ychen\appdata\local\programs\python\python310\lib\site-packages (22.0.4) Coll
错误1:maven打包报错 错误还原:使用maven打包项目时报错如下 [ERROR] Failed to execute goal org.apache.maven.plugins:maven-resources-plugin:3.2.0:resources (default-resources)
错误1:服务调用时报错 服务消费者模块assess通过openFeign调用服务提供者模块hires 如下为服务提供者模块hires的控制层接口 @RestController @RequestMapping(&quot;/hires&quot;) public class FeignControl
错误1:运行项目后报如下错误 解决方案 报错2:Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.8.1:compile (default-compile) on project sb 解决方案:在pom.
参考 错误原因 过滤器或拦截器在生效时,redisTemplate还没有注入 解决方案:在注入容器时就生效 @Component //项目运行时就注入Spring容器 public class RedisBean { @Resource private RedisTemplate&lt;String
使用vite构建项目报错 C:\Users\ychen\work&gt;npm init @vitejs/app @vitejs/create-app is deprecated, use npm init vite instead C:\Users\ychen\AppData\Local\npm-