How do I use javascript to prevent form submission because of empty fields?

后端 未结 4 1462
慢半拍i
慢半拍i 2021-01-24 01:44

How do I make a script in javascript to output an error and prevent form submission with empty fields in the form? Say the form name is \"form\" and the input name is \"name\".

4条回答
  •  难免孤独
    2021-01-24 02:05

    Attach an event handler to the submit event, check if a value is set (DEMO).

    var form = document.getElementById('test');
    
    if (!form.addEventListener) {
        form.attachEvent("onsubmit", checkForm); //IE8 and below
    }
    else {
        form.addEventListener("submit", checkForm, false);
    }
    
    function checkForm(e) { 
        if(form.elements['name'].value == "") {
            e.preventDefault();
            alert("Invalid name!");   
        }
    }
    

提交回复
热议问题