开发者

jQuery Form validation: Radio buttons validation on blur

开发者 https://www.devze.com 2023-03-14 22:24 出处:网络
I am trying to validate radio button开发者_运维知识库s on blur and have written a common function to validate all sets of radio buttons.

I am trying to validate radio button开发者_运维知识库s on blur and have written a common function to validate all sets of radio buttons.

The 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>

The 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;
            }
    }
});

The CSS:

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

The same is running online at: http://jsfiddle.net/prajan55/V9RvD/

But the function executes on load itself even before blur happens. Kindly help to fix this issue.


In your script change

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

to

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

Working example: http://jsfiddle.net/V9RvD/1/

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号