简体   繁体   中英

HTML5 Form required field with normal button (not Submit)

I have some form fields and a Save button (not Submit type). I want to implement the HTML5 required validation using

However it seems to work only with Submit button and not with normal button.

I cannot use Submit button, since I have custom code on my Save button

$("#saveForm").click(function(){
        saveFormData();
        showView('detailsView','editView');
        setFormFieldValues();
    })

How can I achieve the same with normal button ?

I think you can use submit button. just add return false at the end like this :

$("#saveForm").click(function(){
    saveFormData();
    showView('detailsView','editView');
    setFormFieldValues();
    return false;     //stops the form being submitted
})

It's better to add your custom code to the submit event of the form:

$("form").on("submit",function(event){

    saveFormData();
    showView('detailsView','editView');
    setFormFieldValues();




});

How is this?

$("#saveForm").click(function(event){

    var emptyFields = $('input').filter('[required][value=""]');
    if (emptyFields.length === 0) {
       /* valid code here */
    } else {
       /* invalid code here */
       event.preventDefault(); // this stops the click event;
    }
}

You can loop through the empty fields using emptyFields.each()

You could use form submit event and prevent the default behavior (posting to server) using e.preventDefault();

$("form").on("submit",function(e){
    e.preventDefault();
    saveFormData();
    showView('detailsView','editView');
    setFormFieldValues();
});

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