Validating messages before submit - javascript

I'm making a html5 application which require all fields to be filled in before the submit button can be clicked.
What I want to do now is give an alert if a textbox is not filled in, the problem is that my submit button is disabled until all fields are filled in, so I can't really add an alert to that button.
Any idea's on how to solve this?
I want it so that after filling in the final textbox the submit button becomes available without first having to click on it.
Note that the 'required' does not work.
I have the following code:
HTML:
<form id="winForm">
<p>
<input type="text" id="name" name="name" required />
</p>
<p>
<input type="text" id="vorname" name="vorname" required />
</p>
<p>
<input type="text" id="email1" name="email1" required />
<label id="atteken" >#</label>
<input type="text" id="email2" name="email2 " required />
<textarea id="fullemail" name="fullemail"></textarea>
</p>
<p>
<input type="text" id="telefon" name="telefon" onclick="generateFullAdress()" required />
</p>
<p>
<input type="text" id="firma" name="firma" required />
</p>
<p>
<input type="submit" id="submitBtn" onclick="sendTheMail()" value=" ">
</button><div id="loading"><img src="images/loadingBar.gif" id="load"></img></div>
</p>
</form>
Jquery/JS
<script type="text/javascript">
function generateFullAdress() {
document.getElementById('fullemail').value =
document.getElementById('email1').value + '#' +
document.getElementById('email2').value;
}
</script>
<script>
var $input = $('input:text'),
$register = $('#submitBtn');
$register.attr('disabled', true);
$input.keyup(function() {
var trigger = false;
$input.each(function() {
if (!$(this).val()) {
trigger = true;
}
});
if(trigger) {
$register.attr('disabled',true);
}else {
$register.removeAttr('disabled');
}
});
</script>
Help would greatly be appreciated.
Thanks!

If you have a form as such:
<form id="form">
...
</form>
You can use the following jQuery code to do something before the form is submitted:
$(function() {
$('#form').submit(function() {
// DO STUFF
return true; // return false to cancel form action
});
});
OR
perform the samething with the onsubmit event like
<form action="youraction" onsubmit="validatefunction" method="post">

Related

Trigger action in form submit javascript html

I am trying to validate the fields in the form and pull up a different html file when the user clicks the submit button if there's no error in field validation.
However, the validators don't seem to work. I want the Event Name and Location fields to alphanumeric characters and spaces, but it seems to take other values as well.
Putting onClick="self.location='successPage.html'" inside the submit button does not seem to validate the fields either. I want it to move to the successPage.html file if all fields in the form are successfully validated.
I don't want to use jQuery.
Here is my code:
<form action="" >
<p>
<label>
Day of the week:<br>
<select name="days">
<option value="mon">Monday</option>
<option value="tue">Tuesday</option>
<option value="wed">Wednesday</option>
<option value="thu">Thursday</option>
<option value="fri">Friday</option>
</select><br>
</label>
<label>
Start Time:<br>
<input id="appt1" type="time" name="appt1" min="9:00" max="18:00" required /><br>
</label>
<label>
End Time:<br>
<input id="appt2" type="time" name="appt2" min="9:00" max="18:00" required /><br>
</label>
<label>
Event Name:<br>
<input id="ename" type="text" name="ename" required /><br>
</label>
<label>
Location:<br>
<input id="loc" type="text" name="location" required /><br><!--pattern="[A-Za-z0-9\s]"-->
</label>
<label>
Enter URL for the pictture:<br>
<input id="urlpic" type="text" name="urlname" />
</label>
<br><br>
<input type="reset" id="reset" value="Reset" />
<input type="submit" id="submit" value="Submit" /><!--onClick="self.location='successPage.html'"-->
<!-- <input type=button value="Submit" onClick="self.location='successPage.html'"> -->
</p>
</form>
<script>
function chkName() {
var myName = documnet.getElementById("ename");
var pos = myName.value.search( /^[A-Za-z0-9\s]/);
if (pos != 0) {
alert("Please check your input (" + myName + ") again");
return false;
} else
return true;
}
function chkLoc() {
var myLoc = documnet.getElementById("loc");
var pos = myLoc.value.search( /^[A-Za-z0-9\s]/);
if (pos != 0) {
alert("Please check your input (" + myLoc + ") again");
return false;
} else
return true;
}
document.getElementById("ename").onchange = chkName;
document.getElementById("loc").onchange = chkLoc;
</script>
<form action="." method="POST" onsubmit="return validate(this)">
<input type="submit" value="Submit">
</form>
the form element will be passed into the validate function when the user submits, return false to not submit the form, and true to submit it.
<script>
function validate(form) {
console.log(form); // log element to console on submit
return false; // replace with true if input is good to be submitted
}
</script>

JQuery form validation on clicking Submit, check all input fields are empty and show innerHTML error not working?

I am trying to create a form validation using HTML and JQuery to check that all the input fields are not empty when a "Submit" button is clicked. If any of them are empty, the Submit button will not process the form, and will change the color of the empty input fields to Yellow and display a message at the bottom of the form (using innerHTML in a .
This are the relevant HTML codes:
<body>
<div id="div_main">
<form action="process.html" method="POST">
<div id="div_left">
<p>Name:</p>
<p>Age:</p>
<p>Gender:</p>
</div>
<div id="div_right">
<p><input type="text" id="name" name="name"></p>
<p><input type="text" id="age" name="age"></p>
<p><input type="text" id="gender" name="gender"></p>
</div>
<input type="submit" id="chksubmit" value="submit"/>
<div id="divmessage"></div>
</form>
</div>
</body>
And these are my relevant JQuery codes to perform the validation:
<script src="jquery-3.3.1.min.js"></script>
<script>
$(document).ready(function(){
$('#chksubmit').click(function(){
if($('#name').val()==''){
$('#name').css('background-color','yellow');
$('#divmessage').append("Please enter Name.")
success = false;
}
});
$('#chksubmit').click(function(){
if($('#age').val()==''){
$('#age').css('background-color','yellow');
$('#divmessage').append("<br>Please enter Age.")
success = false;
}
});
$('#chksubmit').click(function(){
if($('#gender').val()==''){
$('#gender').css('background-color','yellow');
$('#divmessage').append("<br>Please enter Gender.")
success = false;
}
});
});
</script>
When I click the Submit with empty input boxes, the form still goes through instead of stopping. I can't figure out why.
Check the below example
$(document).ready(function() {
$('#chksubmit').on("click", function(e) {
//clean divmessage
$('#divmessage').html("");
//or use $("#div_main form input") to check all inputs
$("#name, #age, #gender").each(function() {
$(this).css('background-color', '');;
if ($(this).val().replace(/\s+/g, " ").trim() == '') {
$(this).css('background-color', 'yellow');
success = false;
$('#divmessage').append("<br>Please enter " + $(this).data("for"))
}
});
e.preventDefault();
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="div_main">
<form action="process.html" method="POST">
<div id="div_left">
<p>Name:</p>
<p>Age:</p>
<p>Gender:</p>
</div>
<div id="div_right">
<p><input type="text" data-for="Name" id="name" name="name"></p>
<p><input type="text" data-for="Age" id="age" name="age"></p>
<p><input type="text" data-for="Gender" id="gender" name="gender"></p>
</div>
<input type="submit" id="chksubmit" value="submit" />
<div id="divmessage"></div>
</form>
</div>

Jquery not getting form data from forms with that same class name

I'm not getting form values on submit of two forms with the same class.
When I submit one of the forms,
a) Jquery submit event is called but values are empty
b) the submit event is skipped and I'm taken right to the php file where I enter the info into a database
My Jquery
$(document).ready(function(){
$('body').on('submit', '.newStaff', function(event) {
event.preventDefault();
var firstName= this.firstName.value;
// do other stuff
//complete AJAX call
});
});
My forms
<form class="newStaff" method="post" action="insertStaff.php">
<input type="text" name="firstName" />
// use other inputs.....
<input type="submit" value="submit" />
</form>
<form class="newStaff" method="post" action="insertStaff.php">
<input type="text" name="firstName" />
// use other inputs.....
<input type="submit" value="submit" />
</form>
Am I not binding correctly? Haven't had issues like this before. I've always been able to get unique input values based on the form that was submitted.
my be you can use function eq jquery for this
$(function() {
$('body').on('submit', '.newStaff', function(event) {
event.preventDefault();
var firstName = $('.newStaff input[name="firstName"]').eq(0).val();
alert(firstName);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form class="newStaff" method="post" action="insertStaff.php">
<input type="text" name="firstName" value="1 2 3"/>
<input type="submit" value="submit" />
</form>
<br/>
<form class="newStaff" method="post" action="insertStaff.php">
<input type="text" name="firstName" value="a b c"/>
<input type="submit" value="submit" />
</form>

How to know which form I clicked with button class

How can I know which form I clicked? Is it possible with a button class instead of buttons with id?
$(document).ready(function () {
$(".form-buttons").click(function () {
//I only want the form which corresponds to the button I clicked
var formDates = $(form).serialize()
alert ("You clicked "+formDates)
})
})
<form id="form1">
<input type="text" value="date1" name="name1"/>
<input type="text" value="date2" name="name2"/>
<input type="text" value="date3" name="name3"/>
<button type="button" class="form-button"></button>
</form>
<form id="form2">
<input type="text" value="date4" name="name1"/>
<input type="text" value="date5" name="name2"/>
<input type="text" value="date6" name="name3"/>
<button type="button" class="form-button"></button>
</form>
Yes use class instead of id for similar elements. Please try this.
Note: form-button is the class name in your HTML and not form-buttons
$(document).ready(function () {
$(".form-button").click(function () {
var formDates = $(this).closest('form').serialize();
alert ("You clicked "+formDates)
})
})
I think you be looking for
$('.form-button').on('click', function () {
alert($(this).parents('form').attr('id')); // Check the ID of the form clicked
});
something Maybe Like mentioned above.
You can get the name of the element by using the this keyword which refer, in a DOM event, to the cibled element :
$(document).ready(function () {
$(".form-buttons").click(function () {
alert('You clicked the form' + this.parentElement.getAttribute('id'));
})
})
You can do this in a few different ways. You can traverse up the DOM and see which form is used or -and this is my favorite- you can submit the form!
Solution 1: Traversing up the DOM
<script>
$(document).ready(function () {
$(".form-button").click(function () {
var clicked_form = $(this).parent();
var formDates = clicked_form.serialize();
alert ("You clicked "+formDates);
})
})
</script>
</head>
<body>
<form id="form1">
<input type="text" value="date1" name="name1"/>
<input type="text" value="date2" name="name2"/>
<input type="text" value="date3" name="name3"/>
<button type="button" class="form-button"></button>
</form>
<form id="form2">
<input type="text" value="date4" name="name1"/>
<input type="text" value="date5" name="name2"/>
<input type="text" value="date6" name="name3"/>
<button type="button" class="form-button"></button>
</form>
</body>
Solution 2: Submit the form
You already are using the form, so why not submit it? Change the buttons to input elements with type submit and intercept the submit event, like this. This is how I think it should be done. It is also better for user experience because the user can just submit the form by pressing enter.
<script>
$(document).ready(function () {
$("form").on('submit', function (e) {
e.preventDefault();
var formDates = $(this).serialize()
alert ("You clicked "+formDates)
})
})
</script>
</head>
<body>
<form id="form1">
<input type="text" value="date1" name="name1"/>
<input type="text" value="date2" name="name2"/>
<input type="text" value="date3" name="name3"/>
<input type="submit" class="form-button"></input>
</form>
<form id="form2">
<input type="text" value="date4" name="name1"/>
<input type="text" value="date5" name="name2"/>
<input type="text" value="date6" name="name3"/>
<input type="submit" class="form-button"></input>
</form>
</body>
Check this fiddle on how I would do it.
https://jsfiddle.net/xtfeugav/
Simple use
$("form").submit(function(e) {
to listen for every submit on all the forms you have. To get the ID of the form you use
var formid = $(this).attr('id');
I used e.preventDefault(); to prevent the form don't update the page.
Remember to use <input type="submit" value="Submit"> on your forms to make this work.
Its a simple code, hope it helps.

How to genetrate input field and their value based on user input on the other input field in jquery

I have an input field where user will enter isbn number based on the input number i need to populate two input field i.e book title and book author name i am calling a javscript function on onblur of input and i am getting the correct value but my problem is that if user will not move their cursor from the input field and click on submit button then how i will populate these two input field in these scenario onblur is not working
<form name="post" id="post" method="post" action="#">
<input type="text" name="price" id="price">
<input type="text" name="isbn_number" id="isbn_number" onblur="getdetail()">
</form>
Pick your preferred solution and adapt it to your website:
1) If your browser supports it, the easiest is make all your fields required and use onchange instead of onblur. This will force the user to enter an isbn, which will trigger the onchange containing more inputs with required.
<form name="post" id="post" method="post" action="#">
<input type="text" name="price" id="price" required>
<input type="text" name="isbn_number" id="isbn_number" onchange="getdetail()" required>
</form>
2) Do manual submitting after checking fields.
<form name="post" id="post" method="post" action="#">
<input type="text" name="price" id="price">
<input type="text" name="isbn_number" id="isbn_number" onblur="getdetail()">
<input type="submit">
</form>
<script>
document.querySelector('input[type="submit"]').addEventListener('click', function ( event ) {
var valid = false;
event.preventDefault();
// ...
// add validation code here.
// ...
if (valid) document.querySelector('#post').submit();
});
</script>
3) Only activate the submit if everything is valid.
<form name="post" id="post" method="post" action="#">
<input type="text" name="price" id="price">
<input type="text" name="isbn_number" id="isbn_number">
<input type="submit" disabled="disabled">
</form>
<script>
var valid = false;
document.querySelector('#post').addEventListener('change', function ( event ) {
if (event.target.name === 'isbn_number') getdetail();
// ...
// add validation code
// if (stuff && stuff && stuff) valid = true;
if (valid) document.querySelector('input[type="submit"]').removeAttribute('disabled');
});
</script>

Categories

Resources