Its not validating on my submit button click using javascript - javascript

I have this code in my view
function Validate() {
if (document.getElementById('MandateName').value == "") {
var err = document.getElementById('MandateNameErr');
err.innerHTML = "Please enter a value for the Mandate Name";
err.style.display = "block";
return false;
}
else {
document.getElementById('MandateNameErr').style.display = "none";
}
if (document.getElementById('MandateDescription').value == "") {
var err = document.getElementById('MandateDescriptionErr');
err.innerHTML = "Please enter a value for the Mandate Description";
err.style.display = "block";
return false;
}
else {
document.getElementById('MandateDescriptionErr').style.display = "none";
}
return true;
}
and I have on submit button I am validating before submiting?
<button name="Submit" onclick="Validate()" >Add Variables to Mandate</button>
I called Validate function but its showing me if I am not entering anything on the text box if I click Button its showing me my validation message but same time its going to my view and throwing me the message?
even I put the return false; its not working is that something I am doing wrong?

You need to put return in the onclick, like this:
<button name="Submit" onclick="return Validate()" >Add Variables to Mandate</button>
Otherwise you're executing the validation...but not really caring about the result.

Related

Javascript form validation only working once

Script: NewsletterScript.js
function formValidation() {
var fname = document.getElementById('firstName').value;
var lname = document.getElementById('lastName').value;
var pnumber = document.getElementById('phoneNumber').value;
var email = document.getElementById('e-mail').value;
if (FirstName(fname)) {
}
if (LastName(lname)) {
}
if (Country(country)) {
}
if (Email(email)) {
}
return false;
}
/*first name input validation*/
function FirstName(fname) {
var message = document.getElementsByClassName("error-message");
var letters = /^[A-Za-z]+$/;
if ( fname =="" || fname.match(letters)) {
text="";
message[0].innerHTML = text;
return true;
}
else {
text="First name should contain only letters";
message[0].innerHTML = text;
return false;
}
}
/*last name input validation*/
function LastName(lname) {
var message = document.getElementsByClassName("error-message");
var letters = /^[A-Za-z]+$/;
if ( lname =="" || lname.match(letters)) {
text="";
message[1].innerHTML = text;
return true;
}
else {
text="Last name should contain only letters";
message[1].innerHTML = text;
return false;
}
}
I'm trying to get this validation to loop until the criteria is fulfilled, currently this is only working once and if the button is clicked again it submits regardless. Button below.
Due to the script being so long its not letting me upload all of it, however its just got other validation such as phone number etc, Any help will be appreciated, cheers!
If what you want is that formValidation() returns true only when the four validation functions return true you sould write that instead of putting empty if statements :
return FirstName(fname) && LastName(lname) && Country(country) && Email(email);
This manner formValidation() will return false if one of them return false
You should consider using form onsubmit instead on the onclick on the submit button.
Instead of:
<input class="button" type="submit" value="Submit" name="submit" onClick="formValidation()" />
consider using the form submit and do not forget the return keyword:
<form onsubmit="return formValidation();" > /* ... */ </form>
Related Question: HTML form action and onsubmit issues

Why is nothing happening when I click on onclick button?

*I want to display two input fields for lower and higher number and display the necessary error messages if the inputs are wrong.
Any idea why nothing happens when I click on my button? Any way I can shorten my if-else statement cus it does feel quite wordy thank you would appreciate the comments*
<html> Enter lowest number<br>
<input type="text" id="input" size="20">
<span id="wrongInput"><br><br>
Enter highest number<br>
<input type="text" id="input2" size="20">
<span id="wrongInput2"></span><br><br>
<button type="button" onclick="testNum()">Play button</button><br><br>
</html>
<script>
function testNum()
{
//if is not a number or blank input
if (/^\d$/.test(input) == '')
{
var blank = document.getElementById("wrongInput").innerHTML;
blank.innerHTML = "Please fill in a number";
blank.style.color ="red";
return false;
} else {
blank.innerHTML = "";
}
if (/^\d$/.test(input) == false)
{
var wrong = document.getElementById("wrongInput").innerHTML;
wrong.innerHTML = "Only key in number";
wrong.style.color ="red";
return false;
} else {
wrong.innerHTML = "";
}
if (/^\d$/.test(input2) == '')
{
var blank = document.getElementById("wrongInput2").innerHTML;
blank.innerHTML = "Please fill in a number";
blank.style.color ="red";
return false;
} else {
blank.innerHTML = "";
}
if (/^\d$/.test(input2) == false)
{
var wrong = document.getElementById("wrongInput2").innerHTML;
wrong.innerHTML = "Only key in number";
wrong.style.color ="red";
return false;
} else {
wrong.innerHTML = "";
}
if (input2 < input)
{
var wrong = document.getElementById("wronginput2").innerHTML;
wrong.innerHTML = "The number must be higher";
wrong.style.color ="red";
return false;
} else {
return true;
}
}
</script>
The function is called in your example, there are just a few things listed below, that I think you should consider.
First of all you are trying to call an undefined variable in all of the else-blocks.
Second, you are calling innerHTML twice in all of the if statements.
Finally you need to take a look on your conditions in the if statements.

Change button type to submit

I'm trying do something like this:
Initially, the user has button "Edit booking", but after clicking on it something activates and button becomes a submit button. When the user enters his info and clicks submit, this data goes to servlet.
It works partially, but the problem is that when the button changes, I don't have a moment when the user can enter their data.
Here is my current code:
<c:if test="${booking.status == 'Checking'}">
<form name="myForm" id="myForm">
<input type="button" value="Edit booking" id="editButton"
onclick="activate(); changeButton();">
</form>
<script>
function activate() {
var editButton = document.getElementById("editButton");
if (editButton.value == "Edit booking") {
document.getElementById("bookingDate").disabled = false;
document.getElementById("returnDate").disabled = false;
editButton.setAttribute('type','submit');
}
else {
document.getElementById(editButton).action = "/BookingUpdate";
document.getElementById("bookingDate").disabled = true;
document.getElementById("returnDate").disabled = true;
}
}
</script>
<script>
function changeButton() {
var editButton = document.getElementById("editButton");
if (editButton.value == "Edit booking") {
editButton.value = "Submit";
}
else {
editButton.value = "Edit booking";
editButton.setAttribute('type', 'button');
}
}
</script>
</c:if>
Actually, you can submit a form data by either using a submit button or calling a submit function document.getElementById("myForm").submit()directly in javascript code.
thus, you can try something like below:
<form name="myForm" id="myForm">
<input type="button" value="Edit booking" id="smartButton" onclick="doSomethingSmart();">
</form>
<script>
var smartButton = document.getElementById("smartButton");
var myForm = document.getElementById("myForm");
function doSomethingSmart() {
if(smartButton.value == "Edit booking") { // we gonna edit booking
document.getElementById("bookingDate").disabled = false;
document.getElementById("returnDate").disabled = false;
smartButton.value = "submit"; // let it in disguise as submit button
}
else { // we gonna submit
if( isUserInputValied() ) {
myForm.submit(); // submiiiiiiiiiiiiiiiiiit !
// restore everything as if nothing happened
document.getElementById("bookingDate").disabled = true;
document.getElementById("returnDate").disabled = true;
smartButton.value="Edit Booking";
}
else {
alert("please fill your form correctly!");
}
}
}
function isUserInputValid() {
// check whether the user input is valid
}
</script>
You need to prevent the default event if it's in edit mode so that it won't submit the form. You can always have your button type as submit no need to change it to button.
This should work:
var button = document.getElementById('editButton');
button.addEventListener('click', toggleButton);
function toggleButton(e){
var isEdit = button.value === 'Edit booking';
if(isEdit){
document.getElementById("bookingDate").disabled = false;
document.getElementById("returnDate").disabled = false;
button.value = 'Submit';
e.preventDefault();
}
}

Multiple onClicks in Submit Button

I have a submit button that redirects to another page if all the required fields are filled out.
<input type="submit" onclick="validateForm();redirect();" class="someClass" value="Submit" />
Right now when the button is clicked, it calls both functions. How do I get it to where it does not call redirect if validateForm returns false?
Here is the validateForm function if it helps:
function validateForm(){
var email = document.forms["form"]["Email"].value;
if(email == null || email == ""){
alert("Email must be filled out");
return false;
}
}
<input type="submit" onclick="validateForm(); return false;" class="someClass" value="Submit" />
Change the input to the code above. Also change your function to reflect the code below.
function validateForm(){
var email = document.forms["form"]["Email"].value;
if(email == null || email == ""){
alert("Email must be filled out");
return false;
}else {
redirect();
}
}
Add a onclick handler, say validateAndRedirect:
function validateAndRedirect()
{
if(validateForm())
{
redirect();
}
else
{
return false;
}
}
Add this to the button:
<input...onclick="validateAndRedirect()" ... >
This function will call validate(). If validation fails, will return false. This false will prevent the submit action of the button. If validation passes, it will call redirect.
Make the first function call the next one and add this to your HTML :
<input> type=button onclick="validateForm(); return false;" </input>
Putting 'return false' will prevent redirection and will give time for your function to execute.
function validateForm(){
var email = document.forms["form"]["Email"].value;
if(email == null || email == ""){
alert("Email must be filled out");
return false;
} else
redirect();
}
Additionally, I'd recommend to abstain from putting any code in your HTML. It is considered a "bad practice". However, if you still want to put your code, it'll be more appropriate to put it in the form as an "onsubmit" action:
<form onsubmit="validateForm()">
If you want the function to execute when the submit button is clicked, you can just add an event listener in your script and an id to your button, like this:
var button = document.getElementById("submit");
button.onclick = function validateForm() { /*same code as above..*/ };
Hope it helps!

Submit button using jQuery not working in IE9 and FF9

This submit button works in both Safari and Chrome but not IE9 or FF9.
Submit button -
<img type="submit" src="lib/send_feedback.jpg" border="0" class="feedback-submit-img" onClick="javascript: validate(); return false;"/>
Related jQuery -
// Submit form to next page
function submitForm() {
// document.forms["feedbackform"].submit();
document.feedbackform.submit();
}
// Submit form and validate email using RFC 2822 standard
function validateEmail(email) {
// Modified version original from: http://stackoverflow.com/a/46181/11236
var re = /^(([^<>()[\]\\.,;:\s#\"]+(\.[^<>()[\]\\.,;:\s#\"]+)*)|(\".+\"))#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
return re.test(email);
}
// Return true if email field is left unchanged
function originalText(email){
var defaultMsg;
defaultMsg = "Enter your email address (optional)";
if(defaultMsg == email){
return true;
}
return false;
}
// Verify or decline with error message
function validate(){
$("#result").text("");
var email = $("#email").val();
if ((validateEmail(email)) || originalText(email)) {
w.value = screen.width;
h.value = screen.height;
submitForm();
} else {
$("#result").text(email + " is not a valid email.");
$("#result").css("color", "red");
}
return false;
}
$("form").bind("submit", validate);
Also for what it's worth when I alter the submit button to be more basic to ensure it submits the hidden field that w and h are suppose to update are not filled in.
Here is the entire code and the CSS
type isn't a valid attribute of the img tag: https://developer.mozilla.org/En/HTML/Element/Img
Instead I think you want a <input type="image" /> tag: https://developer.mozilla.org/en/HTML/Element/Input.
The <img type="submit" /> didn't work for me either but using a <input type="image" /> did: http://jsfiddle.net/HXrNb/1/
You can then just bind the validate() function to the submit event for the form:
$('form').on('submit', function () {
...
if ((validateEmail(email)) || originalText(email)) {
...
return true;
} else {
...
return false;
}
});

Categories

Resources