How to change default “please fill out this field” in two field

后端 未结 4 739
无人共我
无人共我 2021-02-13 18:30

I would like two different messages in two field, for example, the username and password field that contain messages like \"username cannot be blank\" and \"password cannot be b

4条回答
  •  谎友^
    谎友^ (楼主)
    2021-02-13 18:46

    you make a loop on all your input elements that's why you obtain the same result in each element. Give an id to your input for example username and password, then try :

    $(document).ready(function() {
    var msg="";
    var elements = document.getElementsByTagName("INPUT");
    for (var i = 0; i < elements.length; i++) {
        elements[i].oninvalid = function(e) {
            e.target.setCustomValidity("");
    
            switch(e.target.id){
                case "password" :
                msg="Bad password";
                case "username" :
                msg="Username cannot be blank";
            }
    
            if (!e.target.validity.valid) {
                e.target.setCustomValidity(msg);
            }
        };
        elements[i].oninput = function(e) {
            e.target.setCustomValidity("");
        };
    } })
    

提交回复
热议问题