如果复选框未选中且文本字段不为空,则显示警报

Display Alert if Checkbox is unchecked and text field is not empty

本文关键字:显示 字段 复选框 文本 如果      更新时间:2023-09-26

当信息被存储到DB中时,我有这个表单。我有一个复选框和一个文本字段。其中任一项都是必需的,但如果文本字段不为空,则很有可能会选中该复选框。因此,如果文本字段中有值,并且复选框未选中,我希望显示警报。我希望在点击"提交"按钮时显示此警报。这是我的表格:

<form id="form" name="form" action=?post=yes" method "post">
   <input type="checkbox" name="close" id="close" value="Yes"><label for="close" title="Close this RMA">Close this RMA</label>
   <label><input type="text" name="dateshipped" id="dateshipped"/></label>
   <button type="submit">Save and Continue</button>
</form>

因此,如果复选框"关闭"未选中且"发货日期"不为空,则在单击提交时显示警报。

谢谢。

您可以在提交按钮中的onclick事件上调用一个javascript函数,比如这个

<button type="submit" onclick="callAfunction();">Save and Continue</button>

并定义功能

callAfunction()
{
 //do the checks with:  document.getElementById('close').value 
  // display an alert("a message"); 
}

这样的东西行吗?

onsubmit="return validate();" // add to your form tag
function validate() {
    checkbox = document.getElementById('myCheckbox').value;
    if (!checkbox) {
        alert('checkbox is empty');
        return false;
    } else {
        return true;
    }
}

可能是这样的吗?

用于提交的按钮。它运行validateSubmit。只有当函数为true时,它才会提交。

<input type="button" value="submit" onsubmit="return validateSubmit();" />

这是验证函数。它获取复选框和文本的值。如果它们都是伪造的,那么它将有效设置为确认框。确认框允许用户选择ok或cancel,并在此基础上返回true或false。

function validate() {
    var valid = true;
    var checkbox = document.getElementById('checkboxID').value;
    var text = document.getElementById('textBox').value;
    if(!(checkbox || text))
        valid = confirm("Checkbox and text are empty. 'n Continue?");
    return valid;
}

条件可以写成(!checkbox&&!text),但是我发现只使用一个更容易阅读!如果可以的话。如果你感兴趣的话,这个规则叫做德摩根定律。

如果您使用jQuery,事情会变得更容易。

var checkbox = $('#checkboxID').prop( "checked" );
var text =$('#textBox').val();

此外,你甚至可以附加这样的处理程序:

$(document).ready(function() {
    $('#btnSubmit').on('click', validate);
});

如果你有任何问题,请告诉我。

**以下代码对我有效,首先你需要添加一个onclick="functionName()"然后执行以下代码**

function myCkFunction() { 

var checkBox=document.getElementById("关闭");

if(checkBox.checked==true){

alert('checked');

}其他{

alert("未选中");

}}