简体   繁体   中英

javascript form validation, before submitting help?

I have the following form:

<select name="size">
    <option value="">Please Select</option>
    <option value="1">Medium</option>
    <option value="2">Large</option>
</select>
<select name="material">
    <option value="">Please Select</option>
    <option value="9">Wood</option>
    <option value="8">Metal</option>
</select>   
<input type="submit" value="submit">

I would like some help creating some javascript, when the above form is submitted the form is verified that values have been selected, and successfully gets submitted. If values have not been selected an alert popups saying either of the following:

  1. "Size needs to be selected and material needs to be selected",
  2. "Size needs to be selected", or
  3. "Material needs to be selected"

Thanks

If you're already using jQuery, try the Validation Plugin ( http://bassistance.de/jquery-plugins/jquery-plugin-validation/ ). Lots of flexibility and it'll do exactly what you want, with minimal code.

With HTML 5 you won't need any validation. Check out the HTML and JavaScript: http://jsfiddle.net/christopherpl/AkJQn/1/

$("form").submit(function(){
    if ($("#size").val() == "" && $("#material").val() == "") { alert("Size and material  needs to be selected"); return false; }
    elseif ($("#size").val() == "") { alert("Size needs to be selected"); return false; }
    elseif ($("#material").val() == "") { alert("Material needs to be selected"); return false;}
    $(this).submit();
});

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