jQuery表单验证:模糊的单选按钮验证

时间:2011-06-22 18:27:36

标签: jquery

我正在尝试验证模糊的单选按钮,并编写了一个通用功能来验证所有单选按钮组。

HTML:

<html>
<body>
<table width="100%">
<tr>
    <td>Body Type</td>
    <td><div id="bodyType">
    <input type="radio" tabindex="10" name="bodyType" value="1"> Slim &nbsp;&nbsp;&nbsp;
    <input type="radio" tabindex="11" name="bodyType" value="2"> Average &nbsp;&nbsp;&nbsp;
    <input type="radio" tabindex="12" name="bodyType" value="3"> Athletic &nbsp;&nbsp;&nbsp;
    <input type="radio" tabindex="13" name="bodyType" value="4"> Heavy<span class="form-error"></span>
    </div>
    </td>
</tr>
<tr>
    <td>Complexion</td>
    <td><div id="complexion">
    <input type="radio" tabindex="14" name="complexion" value="1"> Very Fair &nbsp;&nbsp;&nbsp;
    <input type="radio" tabindex="15" name="complexion" value="2"> Fair &nbsp;&nbsp;&nbsp;
    <input type="radio" tabindex="16" name="complexion" value="3"> Wheatish &nbsp;&nbsp;&nbsp;
    <input type="radio" tabindex="17" name="complexion" value="4"> Wheatish Brown &nbsp;&nbsp;&nbsp;
    <input type="radio" tabindex="18" name="complexion" value="5"> Dark <span></span>
    </div>
    </td>
</tr>
</table>
</body>
</html>

jQuery:

$(document).ready(function(){

    var bodyType = $("#bodyType"),
        complexion = $("#complexion");
    bodyType.find('input').blur(validate(this));
    complexion.find('input').blur(validate(this));

    function validate(obj){
        var tagname = $("input:first", obj).attr("name");
        var arr = document.getElementsByName(tagname);
        var counter = 0;
        var check = 0;
            while(counter < arr.length)
            {
                if(arr[counter].checked == true)
                {
                    check++;
                }
                counter++;
            }
            if(check > 0)
            {
                $(obj).find('span').attr("class","form-ok").html('OK');
                return true
            }
            else
            {
                $(obj).find('span').attr("class","form-error").html('Choose');
                return false;
            }
    }
});

CSS:

.form-ok { color:green; padding-left:10px }
.form-error { color:red; padding-left:10px }

同样在线运行: http://jsfiddle.net/prajan55/V9RvD/

但是即使在模糊发生之前,该函数也会在加载时执行。请帮助解决这个问题。

1 个答案:

答案 0 :(得分:2)

在您的脚本中更改

bodyType.find('input').blur(validate(this));    
complexion.find('input').blur(validate(this)); 

bodyType.find('input').blur(validate);     
complexion.find('input').blur(validate); 

工作示例:http://jsfiddle.net/V9RvD/1/