0

我需要使用javascript,这样当一个单选按钮被选中时,什么都不会发生,但如果另一个是(例如,其他地址),它将验证以下字段;

街道郊区邮政编码

虽然我发布了这个,它可能是一个类似的方法,但是当我有一个复选框和一个文本框时,我怎么能做到这一点,以便只有当复选框被选中时,文本框才不能留空......

感谢大家!!!!如果需要,请询问更多详细信息,我在解释事情方面很糟糕!

4

3 回答 3

1

/* 在员工详细信息页面检查无线电验证 */

function editPage()
{
var select=document.frmEmployeeDetails.radSelect;
if (radioValidate(select,"Select an Employee"))
      {
window.open("EditEmployee`enter code here`.html","_self");
      }
return false;
}   

希望这个例子可以帮助你的朋友。

于 2012-05-09T09:24:29.197 回答
0

由于他们会在单击单选按钮时对其进行检查,因此您可以将 onClick 事件添加到其中一个单选按钮而不是另一个单选按钮。

<input type='radio' id='test' name='test-1' />
<input type='radio' id='test' name='test-2'onClick='Validate();'/>

对于复选框,当用户选中该框时,您应该将焦点设置到文本输入字段。这样,如果用户离开该字段(onBlur),您可以给他们一个错误/警报以填写文本。

<input type='checkbox' id='testChkbx' name='testChkbx' onClick=' /*Set the focus to the text box*/'/>

<input type='text' id='testText' name='testText' onBlur='/* Check to make sure the value of the checkbox is not empty. */'/>
于 2012-05-03T03:01:55.450 回答
0

我假设您可能正在使用 jQuery,因为您没有说。如果没有,那么您仍然可以采用这些概念并将它们移植到普通的旧 javascript 或您正在使用的任何东西。

示例标记

<form id="address-form">
 <input type="radio" name="validate" id="validate_address" value="yes"> Validate<br>
 <input type="radio" name="validate" value="no"> Don't Validate<br>
 Street <input name="street"><br>
 Suberb <input name="suberb"><br>
 Postcode <input name="postcode"><br>
 <input type="submit">
</form>​​​​​

条件验证

在您页面上的某个<script>标记或您包含的 javascript 文件中,创建一个提交事件,该事件将在进行验证之前检查无线电输入的值。

$('#address-form').submit(function(event) {
    if ($('input[name=validate]:checked').val() === 'yes') {
        if (!formValid()) {
            event.preventDefault(); // Don't submit the form
        }
    }
});

// Perform validations
function formValid() {
    if ($('input[name=street]').val().length == 0) {
        // tell them ...
        return false;
    }
    if ($('input[name=suberb]').val().length == 0) {
        // tell them ...
        return false;
    }
    if ($('input[name=postcode]').val().length == 0) {
        // tell them ...
        return false;
    }

    return true;
}

这应该够了吧!

我创建了一个 jsfiddle,如果你愿意,你可以进一步弄乱 - http://jsfiddle.net/nilbus/JNnuX/2/

改为使用复选框

使用复选框非常相似。而不是这个

    if ($('input[name=validate]:checked').val() === 'yes') {

只需检查您的复选框是否已选中。

    if ($('input[name=validate]').attr('checked')) {

http://jsfiddle.net/nilbus/JNnuX/3/

于 2012-05-03T04:12:48.780 回答