Trigger action in form submit javascript html - javascript

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>

Related

Disable and enable button in js

i want to make a form with inputs and "submit" button. Idea is to disable button as long as inputs are empty or value of input not correctly (email validation).
I have my js code, but the problem is that, button starts at the beggining as disabled, but when i write something in first input it start to be not disabled, even if rest of inputs have not correct value.
My function:
document.getElementById("my-button").disabled = true
function inputValidator() {
var $element = $(this);
// for all input fields
if ($element.val()) {
$element.closest('.my-form__item').removeClass('error');
document.getElementById("my-button").disabled = false;
} else {
$element.closest('.my-form__item').addClass('error');
document.getElementById("my-button").disabled = true;
}
// for email field
if ($element.attr('id') === 'email' && $element.val()) {
if (!reg.test($element.val())) {
$element.closest('.my-form__item').addClass('error');
document.getElementById("my-button").disabled = true;
} else {
$element.closest('.my-form__item').removeClass('error');
document.getElementById("my-button").disabled = false;
}
}
Does anyone knows how to solve it?
Iterate over each element inside the form and check if one elements value length is zero. Note: Also the submit button needs a value in this implementation. A more native way would be to simply add the required tag to each input which also gives a good user experience.
JS approach
function validateForm() {
let inputs = document.forms["example"].elements;
let status = true;
[...inputs].forEach((input) => {
if(input.value.length == 0) status = false;
});
document.getElementById('submit').disabled = !status;
}
<form id="example">
<p>
<label>First name</label><br>
<input type="text" name="first_name" onKeyup="validateForm()">
</p>
<p>
<label>Last name</label><br>
<input type="text" name="last_name" onKeyup="validateForm()">
</p>
<p>
<label>Email</label><br>
<input type="email" name="email" onKeyup="validateForm()">
</p>
<p>
<button disabled=true id="submit" value="submit">Submit</button>
</p>
</form>
Pure HTML Approach
<form id="example">
<p>
<label>First name</label><br>
<input type="text" name="first_name" required>
</p>
<p>
<label>Last name</label><br>
<input type="text" name="last_name" required>
</p>
<p>
<label>Email</label><br>
<input type="email" name="email" required>
</p>
<p>
<input type="submit" value="Submit">
</p>
</form>

Alert if radios unchecked on form submit

I am attempting to check if a one of two radio buttons have been checked when submitting a form to validate before submitting.
<body onload="init();">
<form name="myForm" onsubmit="return validateForm();">
<label for="cName">Client Name*</label><br>
<div style="width:74.8%; display:inline-block;">
<input type="text" id="cName" name="cName" placeholder="Client Name..." required>
</div><div style="width:25.2%; display:inline-block;">
<select class="select1" id="cRecord" name="cRecord" required>
<option value="" disabled selected>Advised Recording...
</option>
<option value="Yes">Yes</option>
<option value="No">No</option>
</select>
</div>
Yes <input required type="radio" onclick="javascript:smeCheck();" value="Yes" name="TL/SME" id="yesCheck">
No <input type="radio" onclick="javascript:smeCheck();" value="No" name="TL/SME" id="noCheck"><br>
<div id="ifyes" style="display:none">
<div class="buttons">
<input type="button" id="formOut" onclick="this.form.submit();" value="Submit">
</div>
<script>
$('#formOut').click(function validateForm() {
var Name = document.forms["myForm"]["cName"].value;
var Record = document.forms["myForm"]["cRecord"].value;
var yesSME = $("#yesCheck").prop("checked");
var noSME = $("#noCheck").prop("checked");
if (Name == "") {
alert("//Alert Here");
return false;
}
if (Record == "") {
alert("//Alert Here");
return false;
}
if (yesSME == false || noSME == false) {
alert("//Alert Here");
return false;
} else if (cName != "" && cRecord != "" && ((yesSME == true) || (noSME == true))) {
// do things here
}
});
<script>
</form>
Currently I find with what I have above the user receives an alert upon form submission even when a radio option is selected.
Edit:
Desired behaviour - Upon the user clicking the "Submit" button if the fields cName, cRecord and one of the radios has been selected a Modal will open.
Current Behaviour - When the user clicks the "Submit" Button if the fields cName, cRecord and one of the radios have been selected an alert is given for the radio buttons.
If one or both of the fields cName or cRecord have no user input when clicking the "Submit" button an alert is given for the cName or cRecord field.
The function (opening the modal) works without any issues if I remove the check for the radio button being checked,
The only issue seems to be with the check for if a radio button is selected/unselected
Any assistance would be appreciated.
** Another answer (I'd like to keep first one for reference)
you can achieve what you want like :
HTML:
<!DOCTYPE html>
<html>
<body>
<form id="form1" action="javascript:void(0);">
<label for="cName">Client Name*</label><br>
<input type="text" id="cName" name="cName" placeholder="Client Name..."> <br><br>
<select class="select1" id="cRecord" name="cRecord">
<option value="" disabled selected>Advised Recording...
</option>
<option value="Yes">Yes</option>
<option value="No">No</option>
</select>
<br>
Yes <input type="radio" value="Yes" name="TLSME" id="yesCheck">
No <input type="radio" value="No" name="TLSME" id="noCheck"><br>
<input type="submit" id="formSubmit" value="Submit">
</form>
</body>
</html>
JS (JQuery):
$("#form1").submit(function(){
if (!$("input[name='TLSME']").is(':checked') || $("#cName").val() === '' || $("#cRecord").val() === '') {
alert('Please complete required fields!');
} else {
// your code here
}
});
if(!document.getElementById('yesCheck').checked || !document.getElementById('noCheck').checked) {
alert('Not checked');
}
Should do the trick
You can do that easily using JQuery:
HTML:
<html>
<body>
<form id="form1" action="javascript:void(0);">
<input type="radio" name="gender" value="male"> Male<br>
<input type="radio" name="gender" value="female"> Female<br>
<input type="radio" name="gender" value="other"> Other <br>
<input type="submit">
</form>
</body>
</html>
Javascript:
$("#form1").on("submit", function(){
//Code: Action (like ajax...)
if ($('input[name=gender]:checked').length <= 0) {
alert("No radio checked")
}
})
** Note:
action="javascript:void(0);"
was added to prevent form submission (do nothing), you can remove it when you have action to do.
Why not make the radio buttons required
It would seem that you're trying to do the job of the browser. You don't need to display an alert, which are generally bad UX, because you can use built-in form validation via the required attribute like so:
<form onsubmit="...">
<input type="radio" name="group" value="1" required />
<input type="radio" name="group" value="2" />
...
<button type="submit">Submit</button>
<form />
NOTE: you only need one required attribute and it will apply to all inputs in said group.

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>

Validating messages before submit

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">

Form alerts for multipe inputs

I have the following code, and need to get an alert that will specify which fields are empty or null, and return an alert for each empty or null field. I'm new to JavaScript and struggling a great deal with this. Can anyone give me some advice on this?
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<HTML>
<HEAD>
<TITLE></TITLE>
<SCRIPT LANGUAGE="JavaScript">
<!--
function checkForm(form){
var len = form.length;
//create for loop
for (var i=0; i<len; i++){
if (form.elements[i].type=="text" || form.elements[i].type==null){
if (form.fax number.value=="" || form.fax number.type==null){
alert("Please fill out the fax number field");
}
}
}
}
function emailTest(emailText){
var email = emailText.value;
var emailPattern = /^.+#.+\..{2,}$/;
if (!(emailPattern.test(email))) {
alert("Please enter a valid email address.");
document.myForm[1].focus();
}
}
// -->
</SCRIPT>
</HEAD>
<BODY>
<H3>Assignment 2 Form</H3>
<HR>
<FORM NAME="myForm" METHOD="post"
ACTION="mailto:joeschmoe#blahblah.ca">
Name:<BR>
<INPUT TYPE="text" size="30" NAME="name"><br>
Email address:<BR>
<INPUT TYPE="text" size="30" NAME="email address" onBlur="emailTest(this);"><br>
Phone number:<BR>
<INPUT TYPE="text" size="30" NAME="phone number"><br>
Fax number:<BR>
<INPUT TYPE="text" size="30" NAME="fax number"><p>
<INPUT TYPE="submit" VALUE="Submit Data" onClick="return checkForm(this.form);">
<INPUT TYPE="reset" VALUE="Reset Form">
</FORM>
</BODY>
</HTML>
Ok...wow. I spent way too much time on this.
Your form should look like the following:
<FORM NAME="myForm" id="myForm">
<label for="name">Name:</label><br />
<INPUT TYPE="text" size="30" NAME="name" /><br />
<label for="email_address">Email address:</label><BR />
<INPUT TYPE="text" size="30" NAME="email_address" /><br />
<label for="phone_number">Phone number:</label><BR />
<INPUT TYPE="text" size="30" NAME="phone_number" /><br />
<label for="fax_number">Fax number:</label><BR />
<INPUT TYPE="text" size="30" NAME="fax_number" /><br />
<INPUT TYPE="button" VALUE="Submit Data" onClick="return checkForm()" />
<INPUT TYPE="reset" VALUE="Reset Form" />
</FORM>
Form Summary:
You should utilize labels for form elements
Never use spaces for the name attribute or any identifying attribute for that matter (name, class, id)
inputs should end with /> as should any tag without an end tag (<br /> too)
I pulled out the onBlur event and just added it as a piece of the overall validation process. No need to make it too complicated
I used a button input type instead of a submit input type. See why in the JavaScript
And then your JavaScript:
function checkForm() {
var valid = false; //Set a boolean variable that will be changed on each block
//of validation
if (document.myForm.fax_number.value === "") {
alert("Please fill out the fax number field");
}
if (document.myForm.email_address.value === "") {
alert("Email address is required");
} else {
valid = emailTest(document.myForm.email_address.value);
}
//all other checks within if statements
if (valid) {
document.myForm.action = "mailto:soandso#so.com";
document.myForm.submit();
}
}
function emailTest(emailText) {
var emailPattern = /^.+#.+\..{2,}$/;
var ret = false;
if (!(emailPattern.test(emailText))) {
alert("Please enter a valid email address.");
} else {
ret = true;
}
return ret;
}
Javascript Summary
In JavaScript interacting with HTML forms, forms are called as such: document.formName where formName is the string in the name="" attribute of the form tag or document.forms[i] where i is the numerical instance of the form on the page, i.e. the first form on the page is i = 0, thus it would be called as document.forms[0]
Check each input by name for a value with document.myForm.(elementName).value where elementName is the string from your <input>s name attribute.
Instead of using a submit, I used a regular button. When the "Submit Data" button is clicked in the form, it runs checkForm() which makes sure everything is valid
If everything is valid, it assigns an action to the form with document.myForm.action=youraction and then submits it via JavaScript with document.myForm.submit()
Notes
Don't use W3Schools to learn about anything ever.
Read more about forms here

Categories

Resources