简体   繁体   中英

Submit Only if a specific button is clicked

I have a form like:

<form id='Contact' action="<?php echo $_SERVER['PHP_SELF']; ?>" method='post' enctype="multipart/form-data" accept-charset='UTF-8' style='background-color:#7FFF00; width: 781px'>

In that form, I have 15 fields. The first three "FirstName", "Title", "LastName" are the only three required for the form to submit.

The form has three buttons. One for deleting, creating, and modifying.

When Create is clicked, it has to validate the three fields and then submit the form. When Delete is clicked, it only has to validate one specific field and then submit.

Javascript:

<script type="text/javascript">
<!--
function validateForm(Form, FieldName)
{
    var Form = document.getElementById(Form);
    var Elements = Form.elements;
    var Field = Elements[FieldName].value;

    if (Field == null || Field == "")
    {
        alert(FieldName + " must be filled out!");
        return false;
    }
    return true;
}

function SubmitForm(Form, DoSubmit)
{
    if (DoSubmit)
    {
        document.getElementById(Form).submit();
    }
}
-->
</script>

My CreateButton:

<input type='button' name='ContactInfo' value='Create' onClick="SubmitForm('Contact', validateForm('Contact', 'Title') && validateForm('Contact', 'FirstName') && validateForm('Contact', 'LastName'));" />

My Delete Button:

<input type='submit' name='ContactInfo' value='Delete' />

Why does the Create Button not work? It validates the required fields but does NOT submit/Post :S

try the following.


<input type='submit' name='ContactInfo' value='Create' onClick="SubmitForm('Contact', validateForm('Contact', 'Title') && validateForm('Contact', 'FirstName') && validateForm('Contact', 'LastName'));return false;" />

change the type to submit and put a return false at the end.

or add this to your form element:

onsubmit="return validateForm(this);"

and do tests for Delete etc.. if this.value === "Delete" etc...

You have document.getElementById(Form) when the ID of your form is "Contact". So change that to document.getElementById("Contact") .

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