简体   繁体   中英

jquery css validation inside input no message red text issue

i really need your help of jquery and css. Here it goes:

say I have three types of fields

<input id="customer_name" name="customer_name" type="text" value="jo"/>
<select id="address_province" name="address_province" style="width:95%;" >
    <option value="">a</option>
    <option value="b">b</option>
</select>
<input type="checkbox" value="" id="purchase_selected" name="purchase_selected" /> 
<label for="purchase_selected">hi</label> 

Every text has a default value and if user doesn't enter anything, the input shows the default value (using js). If the fields are not valid to some rules there should be no error messages but the text should be red. (default values should be red if "required" is the rule). Maybe a little confusing. For example if text input is null, select value is '' and checkbox not checked in the above example, value jo, a, hi shoule be red. So far I could achieve this through following code:

$('#registerForm').validate({

    errorPlacement: function () {
        return false;
    },

    submitHandler: function (form) { 
        var errors=0;
        var name = $("input[name='customer_name']").val(); 
        var td = $("#purchase_selected").is(":checked");

        if(name==""){ 
            $("input[name='customer_name']").css("color","red"); 
            errors++;
        }else{ 
            $("input[name='customer_name']").css("color","white");  
        }
        //code for purchase_selected omitted
        if(errors==0)
            submit();

    }

});

But it drives me crazy about the select fields. I can't make the text red when "a" is selected. The best solution came out is that I set .error and .valid css style and use the keyword "required" in the select tag. But it doesn't make the text red but only the border. Further more, it seems the "required" validates first and if it's through, then comes to the submitHandler which makes it poor user experience.

Any advice would be appreciated.

And I am wondering if I could use something like:

rules: {
   customer_name:{
        required: true
    },
    address_province:{
        required: true
    },
    purchase_selected:{
        required: true
    }
} 

I tried it out, but nothing happened. And even so, I don't really know how to make the text red when they are invalid.

The browser support for styling selects are bad and uneven to say the least...

Since your using jQuery I would recommend to take a look at some jQuery select box plugins . Then you are free to style them as you like.

Try out this code:

if($("#address_province :selected").text() == "a"){
    $("#address_province :selected").css("color", red);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM