【问题标题】:Create and Delete input type text if the selected input type checkbox如果选择了输入类型复选框,则创建和删除输入类型文本
【发布时间】:2015-06-02 07:54:19
【问题描述】:

我有一个问题,如果选择了输入类型复选框,我需要根据需要创建或删除输入类型文本。

目前我只能创建输入文本,但如果未选中复选框,我设法找到清除解决方案。

我的 HTML 代码:

<form role="form" action="" method="POST">
  <input type="checkbox" class="myCheckBox" name="category[]" value="1">
  <input type="checkbox" class="myCheckBox" name="category[]" value="2">
  <input type="checkbox" class="myCheckBox" name="category[]" value="3">
  <input type="checkbox" class="myCheckBox" name="category[]" value="4">
  <input type="checkbox" class="myCheckBox" name="category[]" value="5">
  <div class="inputCreate"></div>
  <input type="submit" name="" value="Send yours categories">
</form>

而jQuery代码如下

     var wrapper = $(".inputCreate");

$('.myCheckBox').click(function() {
    if ($(this).is(':checked')) {
         $(wrapper).append('<input type="text" name="mytext[]" placeholder="">');
    }
});

我可以通过取消选中复选框来做到这一点,同时删除输入文本字段?。

这个问题的解决方法:

var wrapper = $(".inputCreate");
$(".myCheckBox").change( function(){
    if($(this).is(':checked')){
         $(wrapper).append('<input type="text" name="mytext[]" placeholder="">');
    }
    else{
        $('.inputCreate :last-child').remove();
    }
});

来自智利的问候。

【问题讨论】:

    标签: javascript jquery checkbox input


    【解决方案1】:

    这应该正是您想要的: Working Fiddle

    var wrapper = $(".inputCreate");
    $(".myCheckBox").change( function(){
        if($(this).is(':checked')){
             $(wrapper).append('<input type="text" name="mytext[]" placeholder="'+$(this).val()+'">');
        }
        else{
            $('.inputCreate :last-child').remove();
        }
    });
    

    【讨论】:

    • 非常感谢朋友,这正是我们想要实现的。再次感谢。来自智利的问候。
    • 请投票和检查!! ;)
    • 我在几分钟前加入了该网站,我收到消息说我需要+15 声望嘿嘿。很抱歉无法回复您的宝贵帮助。
    • 大声笑,我只是说。 Stackoverflow 旨在提供帮助。玩得开心。
    【解决方案2】:

    试试这个。如果复选框未选中,我假设您想删除文本框。

    $('.myCheckBox').click(function() { 
         if ($(this).is(':checked')) { 
             $(wrapper).append('<input type="text" name="mytext[]" placeholder="">'); 
         }else{ 
             $(wrapper).find('input').remove();
         }
     });
    

    【讨论】:

    • 它可以工作,但是当重新选择任何复选框时,这不会创建文本字段。
    • 不工作,控制台返回以下错误:ReferenceError:输入未定义。谢谢你的帮助。
    • 抱歉遗漏了冒号。只需尝试编辑后的答案。
    • 它有效,但如果我有多个选中的复选框并且只取消选中一个,我会删除所有输入文本字段:(。再次感谢您的帮助。
    猜你喜欢
    • 2022-11-25
    • 2018-01-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-11-07
    • 2018-12-23
    相关资源
    最近更新 更多