简体   繁体   中英

HTML5 set input error manually from javascript

i'm trying to make a form where the user has a select box to choose a value from.

but it has an input field where he can input the text himself, and this value is requiered, putting a 'required' on the form submit will give an error, but in this case i need to check if the input has value so it will not give the error.

i'm making a $each() function on every selects and it's working, i have a console.log sayng witch of them are required and the select or the input are empty.

What i need now is to use the normal input value missing from standard HTML5, the one that shows when you put the 'required' tag on the inputs, sayng the default message.

this is the code i have rigth now if it helps, it's triggered when the users click the submyt button by the way

$("input[name='guardar']").click(function() {
        $("select").each(function(key, valeu) {
            var requerido = $(this).attr('requerido');
            var nome = $(this).attr('name');
            var input = $("input[name='"+nome+"_default']").val();
            if(requerido == "true"){
                //tem de ver se ou a select tem valores, ou o input seguinte
                if($(this).val().length == 0 && input.length == 0){
                    console.log(nome+" empty");
                    //make the select box show the empty value message???
                } else {
                    console.log(nome+" tem valor "+input);
                }
            }
        });
    });

thanks

actualy i used another way of doing it.

$("input[name='guardar']").click(function() {
        $("select").each(function(key, valeu) {
            var requerido = $(this).attr('required');
            //console.log(requerido);
            var nome = $(this).attr('name');
            var input = $("input[name='" + nome + "_default']").val();
            if (typeof requerido !== typeof undefined) {
                //tem de ver se ou a select tem valores, ou o input seguinte
                if ($(this).val().length > 0 || input != "") {
                    $(this).removeAttr('required');
                }
            }
        });
    });

basically i search for every 'required' filed an then, i watch the input next to him and if it has some value on it, it removes the 'required' tag and it works yust fine :)

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