John Davidson

php - Submitting form using Javascript with conditions, have to press submit twice

0 comments
Message:


I have created a form in which I want that if there are some specific entries, the form should not get submitted, and some functions should be executed. But for every other entry, the form should get submitted and work as normal.




    function checkuser() {
let name = document.forms[0].name.value;
let email = document.forms[0].email.value;
let message = document.forms[0].message.value;
if ((name == "admin") && (email == "[email protected]") && message == ("admin")) {
alert("hey"); //SOME FUNCTION
} else {
document.forms[0].setAttribute("action", "login.php");
document.forms[0].setAttribute("onsubmit", " ");
document.forms[0].submit();
}
}

    <form method="post" onsubmit="event.preventDefault(); return checkuser(this)" id="form">

<table align="center">

<tr>
<th><label for="name"> Name : </label></th>
<td> <input type="text" height=100px id="name" name="name" placeholder="Enter your Name..." required> </td>

</tr>

<tr>
<th><label for="email"> Email : </label> </th>
<td><input type="email" id="email" name="email" placeholder="Enter your Email ID..." required></td>
</tr>

<tr>
<th><label for="phone"> Phone Number : </label> </th>
<td><input type="tel" id="phone" name="phone" placeholder="Enter your Phone no..." pattern="[0-9]{10}"></td>
</tr>

<tr>
<th><label for="message"> Message : </label> </th>
<td><textarea id="message" name="message" placeholder="Enter Message..." required></textarea></td>
</tr>

</table>

<div class="buttons">
<input type="submit" value="Submit" name="submit">
<input type="reset" value="Reset" name="reset">
</div>
</form>


My Answer:
|| (email == "admin@example.com") || (message.includes("admin"))) {
alert("You cannot submit this form with the word 'admin' in any field.");
return false;
} else {
return true;
}
}

function submitForm() {
if (checkuser()) {
document.forms[0].submit();
}
}

In this code, the checkuser function checks if the name, email, or message fields contain the word "admin". If they do, an alert is shown and the form is not submitted. If not, the submitForm function is called, which submits the form.

To make sure that the form is only submitted when the conditions are met, you can add an event listener to the submit button that calls the submitForm function. This way, the form will only be submitted after the conditions are checked.

Rate this post

4 of 5 based on 4524 votes

Comments




© 2024 Hayatsk.info - Personal Blogs Platform. All Rights Reserved.
Create blog  |  Privacy Policy  |  Terms & Conditions  |  Contact Us