jQuery检查复选框是否被选中,并使用复选框's值,如果它's是空的

jQuery check if checkbox is checked and update the value of the texbox with the checkbox's value and uncheck if it's empty

本文关键字:复选框 如果 是否 检查 jQuery      更新时间:2023-09-26

这里我要做的是,如果我选中复选框,则应使用","作为值之间的分隔符将相应复选框的值附加到文本框中。如果选中的相应复选框的值为空,则应提醒电子邮件ID无效,并取消选中值为空的复选框。

工作原理:
 nbsp -如果我选中复选框,该值将附加到文本框中。
 nbsp -如果我选中值为空的复选框,我会收到警报。
 nbsp -如果取消选中,这些值将自动从文本框中删除。

什么不起作用:
 nbsp -电子邮件ID验证无效。函数已编写,但不起作用。(控制台中没有错误)
 nbsp -如果我通过选中有值的复选框选择了几个选项,然后如果我选择了值为空的复选框,我不会收到无效的电子邮件ID警报。

这是下面的代码。

HTML:

   <label>Recipients : </label>
<input style="width:450px;" type="text" id="toaddress" name="toaddress"></input>
<br>
<div class="plist" style="padding:20px;">
    <input type="checkbox" value="abcp@gmail.com">Pradeep</input><br>
    <input type="checkbox" value="cd@gmail.com">Karthik</input><br>
    <input type="checkbox" value="abcn@p.com">akfkl</input><br>
    <input type="checkbox" value="ksake@po.com">afljs</input><br>
    <input type="checkbox" value="">abc</input><br>
    <input type="checkbox" value="">xyzop</input><br>
    <input type="checkbox" value="abc@cto.com">jay</input><br>
    <input type="checkbox" value="">raj</input><br>
</div>

JavaScript:

    function updateTextArea() {
    var allVals = [];
    $('.plist :checked').each(function (i) {
        if ($.trim($('.plist :checked').val()) === '' && validateEmail($('.plist :checked').val())) {
            $(this)
            alert("Email ID is invalid for the selected patient ! 'n Example: abc@xyz.com");
        } else {
            allVals.push((i !== 0 ? "'r'n" : "") + $(this).val());
        }
        $('#toaddress').val(allVals).attr('rows', allVals.length);
    });

}
$(function () {
    $('.plist input').click(updateTextArea);
    updateTextArea();
});
function validateEmail($email) {
    var emailReg = /^(['w-'.]+@(['w-]+'.)+['w-]{2,4})?$/;
    if (!emailReg.test($email)) {
        return false;
    } else {
        return true;
    }
}

JSFiddle链接在这里http://jsfiddle.net/RhjjA/

检查http://jsfiddle.net/RhjjA/3/

  1. 我更改了validateEmail
  2. 将循环时选中的更改为$(this)
  3. 我正在考虑检查该值是否为空或无效,因为这两个条件都不允许通过检查。如此添加!validateEmail的infron
  4. 我添加了一个$(this).attr('checked', false);

这应该有助于你上路。

if ($.trim($(this).val()) === '' && validateEmail($(this).val())) {
            $(this).attr('checked',false);
            alert("Email ID is invalid for the selected patient ! 'n Example: abc@xyz.com");

除了一个微小的细节外,您的代码运行良好,在if条件之后,您添加了$(this)。这不是以分号结束的,也不是必需的。请对此行进行注释并尝试。

http://jsfiddle.net/RhjjA/5/

我从你的第一个问题开始就这么做了:jsfiddle.net/hBGD6/4/

两个主要问题是

  • if("字符串为空"answers"validateEmail")无法工作(所以所有字符串都可以)。应为if("字符串为空"或"NOT validateEmail")
  • validateEmail()使用的参数是一个null(或未定义的东西)函数的返回,该函数对emailReg.test()无效