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

后端 未结 4 1416
慢半拍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:28

    Claudio's answer is great. Here's a plain js option for you. Just says to do nothing if field is empty - and to submit if not.

    If you need to validate more than one, just add an && operator in the if statement and add the same syntax for OtherFieldName

    function checkForm(form1)
    {
        if (form1.elements['FieldName'].value == "")
        {
            alert("You didn't fill out FieldName - please do so before submitting");
            return false;
        }
        else
        {
            form1.submit();
            return false;
        }
    }
    

提交回复
热议问题