Jquery when click on submit button, if the form is validated - javascript

I made a form, and when clicked on submit, it takes you to another webpage but i couldn't transfer the variables(values of form) from one webpage to another webpage through Javascript.
So, i figured to hide the data, when submit button clicked.
How can i check if the form is validated, and only then initiate Jquery. With the current logic, it initiates the Jquery even if the form is not initiated.
Ultimately, animate or hide the heading and the whole form and change it to the result.
<head>
<title>Food Web App</title>
<link rel="stylesheet" type="text/css" href="appStyleQues.less">
<link href='http://fonts.googleapis.com/css?family=Orbitron:500' rel='stylesheet' type='text/css'>
<link href='http://fonts.googleapis.com/css?family=Roboto+Mono:300' rel='stylesheet' type='text/css'>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script src="N:\Desktop\Javascript\App.js" type="text/javascript"></script>
</head>
<body>
<div id="main">
<header>
<h1>I need some data</h1>
</header>
<div id="ques">
<ul>
<form name="myForm" method="get">
<li>What cuisine?(You can leave it empty)
<br>
<input list="Cuisines" class="normal" type="text" name="Cuisine" placeholder="Like Chinese" pattern="Chinese|Italian|American">
<datalist id="Cuisines" autocomplete="off">
<option value="Chinese"></option>
<option value="Italian"></option>
<option value="American"></option>
</datalist>
</li>
<li>On a scale of 1 to 10, how much hungry are you?
<br>
<input class="normal" type="number" name="hunger" min="1" max="10" required>
</li>
<li>
<input class="special" type="checkbox" name="Personality" value="Vegetarian" checked> Vegetarian
<input class="special" type="checkbox" name="Personality" value="Non-Vegetarian"> Non-Vegetarian
</li>
<li>On a scale of 1 to 10, how much healthy do you want the food to be?
<br>
<input class="normal" type="number" name="Calories" min="1" max="10" required>
</li>
<li>What will be the max cost of the food, per person?
<br>(Quality of the food will be affected)
<br>
<input class="normal" type="number" name="quality" placeholder=" Like 400" step="50" autocomplete="off" required>
</li>
<li>How many people?
<br>
<input class="normal" type="number" name="Amount of people" required>
</li>
<li>
<input class="normal" type="submit" onclick="return a();">
</li>
</form>
</ul>
</div>
</div>
</body>
</html>

The following is a VERY basic function but will point you in the right direction:
$("form").submit(function(e){
e.preventDefault();
var url = "test2.html";
var appendix = "?";
var validated = false;
// Validation
$("form input").each(function() {
// Validation stuff here.
// A basic example:
if ($(this).val() == "") {
alert("Please add all fields.");
return false;
}
else validated = true;
})
if (validated == true) {
$("form [name]").each(function() {
appendix += this.name + "=" + this.value + "&";
})
window.location.href = url + appendix;
}
})
You will need to add a value to your submit button.

you could assign ids to all input tags and then access the values using $('#idofinputfield').val().
you should also use a link or button and register an onclick event handler in javascript
$( "#idofbuttonorlink" ).click(function() {
alert( "Handler for .click() called." );
//validation and further action
});
.if you want to keep using the submit button you can use the submit event handler which allows you to cancel the submission when the validation fails:
$( "#idofsubmitbutton" ).submit(function( event ) {
alert( "Handler for .submit() called." );
//validation and further action
event.preventDefault(); //use this function to cancel submission
});

Related

jQuery: enable element on radio check

jQuery function isnt enabling my disabled submit button?
$(document).ready(function() {
if ($("#lawfulBasis").prop("checked")) {
$("#submitBtn").prop('disabled', false);
alert('Button Clicked');
};
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<html>
<head>
</head>
<body>
<input id="lawfulBasis" type="radio" value="3" /> I give consent for you to store my data for the purposes of marketing, to contact me about products and services via email and telephone*
<p>
<input id="submitBtn" type="submit" value="Submit" disabled/>
</p>
</body>
</html>
The issue is because you only read the state of the radio control in the document.ready handler, ie. when the page loads not when the user changes its state.
To fix this attach a change event handler to the radio and set the disabled state of the button based on that.
Finally, note that you should be using a checkbox for this, not a radio. The reason is that the radio cannot be deselected once selected for the first time.
jQuery($ => {
$("#lawfulBasis").on('change', e => {
$("#submitBtn").prop('disabled', !e.target.checked);
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<label>
<input id="lawfulBasis" type="checkbox" value="3" />
I give consent for you to store my data for the purposes of marketing, to contact me about products and services via email and telephone*
</label>
<p>
<input id="submitBtn" type="submit" value="Submit" disabled/>
</p>
I did think about writing this up in jQuery but really it's just as easy to use vanilla js. Your problem was that you're checking all this when the docuemnt loads, and not when the button is pressed.
document.getElementById("lawfulBasis").addEventListener("change", () => {
const radio = document.getElementById("lawfulBasis");
if (radio.checked) {
document.getElementById("submitBtn").disabled = false;
}
});
<input id="lawfulBasis" type="radio" value="3" /> I give consent for you to store my data for the purposes of marketing, to contact me about products and services via email and telephone*
<p>
<input id="submitBtn" type="submit" value="Submit" disabled/>
</p>
You need an eventlistner: $('#lawfulBasis').change()
$(document).ready(function() {
$('#lawfulBasis').change(function() {
if ($(this).prop("checked")) {
$("#submitBtn").prop('disabled', false);
alert('Button Clicked');
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<html>
<head>
</head>
<body>
<input id="lawfulBasis" type="radio" value="3" /> I give consent for you to store my data for the purposes of marketing, to contact me about products and services via email and telephone*
<p>
<input id="submitBtn" type="submit" value="Submit" disabled/>
</p>
</body>
</html>

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>

Show Hide div on load page if, if statement is true

You will quickly see that I'm new to this and don't have a clue. I'm going mental trying to help a friend out with this project. He wants to have a simple quote form that generates a quote to html then he will copy/paste to a private wordpress page for his client.
The form starts with if radio button is selected, div is shown
index.html:
<html>
<body>
<head>
<title>Demo Quote Creator</title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script type="text/javascript">
$(function () {
$("input[name='animalvillas']").click(function () {
if ($("#chkYes1").is(":checked")) {
$("#dvanimalvillas").show();
} else {
$("#dvanimalvillas").hide();
}
});
});
</script>
<script type="text/javascript">
$(function () {
$("input[name='animalkidani']").click(function () {
if ($("#chkYes2").is(":checked")) {
$("#dvanimalkidani").show();
} else {
$("#dvanimalkidani").hide();
}
});
});
</script>
</head>
<h2>Client Name</h2>
<form name="create" action="welcome.php" method="post" onsubmit="return validateForm();">
<strong>Last</strong>: <input type="text" name="last" required />, <strong>First</strong>: <input type="text" name="first" required />
<BR />
<h2><strong>Resorts to Include in Quote</strong></h2>
<span><strong>Animal Kingdom Villas</strong></span><BR />
<label for="chkYes1">
<input type="radio" id="chkYes1" name="animalvillas" />
Include
</label>
<label for="chkNo1">
<input type="radio" id="chkNo1" name="animalvillas" />
Exclude
</label>
<hr />
<div id="dvanimalvillas" style="display: none">
$<input type="text" name="ages" size="7" /> - Value Studio - Standard View (Parking View) | Studio Description: 316sf - One (1) queen bed and one (1) double-size sleeper sofa (Sleeps 4) <br>
</div>
<span><strong>Animal Kingdom Kidani</strong></span><BR />
<label for="chkYes2">
<input type="radio" id="chkYes2" name="animalkidani" />
Include
</label>
<label for="chkNo2">
<input type="radio" id="chkNo2" name="animalkidani" checked />
Exclude
</label>
<hr />
<div id="dvanimalkidani" style="display: none">
$<input type="text" name="ages" size="7" /> - Value Studio - Standard View (Parking View) | Studio Description: 316sf - One (1) queen bed and one (1) double-size sleeper sofa (Sleeps 4) <br>
</div>
<BR />
<input type="submit" />
</form>
</body>
</html>
Now, on the welcome.php, he only wants the relevent that was selected on the index.html. Obviously, this is not working, but hopefully you can see what we are trying to accomplish.
welcome.php
<head>
<meta charset="utf-8" />
</head>
<body>
<div id="dvanimalvillas" <?php
if ($("#chkNo1").is(":checked")) { echo 'style="display:none;"'; } ?>>
The quote for Animal Kingdom Villas will show here when yes is selected
</div>
<div id="dvanimalkidani" <?php
if ($("#chkNo2").is(":checked")) { echo 'style="display:none;"'; } ?>>
The quote for Animal Kingdom Kidani will show here when yes is selected
</div>
</body>
Thank you for any direction you may have!
In your index.html make following changes. You have to give some value to your radio buttons to fetch in other file
<label for="chkYes2">
<input type="radio" id="chkYes2" name="animalkidani" value="Y" />
Include
</label>
<label for="chkNo2">
<input type="radio" id="chkNo2" name="animalkidani" value="N" checked />
Exclude
</label>
In your welcome.php make following changes. We will use radio button value to hide and display div content.
<div id="dvanimalvillas" <?php echo ($_POST['animalkidani'] == "Y") ? 'style="display:none;"' : '' ; } ?>>
The quote for Animal Kingdom Villas will show here when yes is selected
</div>
<div id="dvanimalkidani" <?php echo ($_POST['animalkidani'] == "N") ? 'style="display:none;"' : '' ; } ?>>
The quote for Animal Kingdom Kidani will show here when yes is selected
</div>
There are multiple things going on here:
You're not using radio buttons properly. Each radio selection needs a different value within each radio group having the same name. This value is what is sent with the form when it is submitted. See this link: http://www.echoecho.com/htmlforms10.htm
In welcome.php, you need to look at the form data that is sent from index.html, not at the actual checkboxes from the form. See this link: http://www.tutorialspoint.com/php/php_get_post.htm

Two Submit button on one form. Detect by text field using jquery

I have a form on my page with two submit buttons. Is there a way to associate a text field to a submit button and when pressed entered on the keyboard to execute correct button. Example - If I fill in the search text field and press enter on the keyboard it executes the search submit button. If I leave search blank and try to log in it would detect the login password field and execute the login submit button when I press enter on my keyboard.
Note: The search button works with the script written for it but if I add the script for login (if nothing is filled in with the search text field), it doesn't work. :(
Please help.
This is what I have so far:
HTML
<!DOCTYPE>
<html>
<head>
<script type="text/javascript" src="/jquery.js"></script>
<script type="text/javascript">
//<![CDATA[
$(window).load(function(){
(function() {
$('#s').keyup(function(){
var empty1 = false;
$('#s').each(function() {
if($(this).val() == ''){
empty1 = true;
}
});
if(empty1) {
$('#s_btn').attr('disabled','disabled');
//this is where i add login script if password has values
if($('#pass').val() == '') {
$('#login').removeAttr('disabled');
function lkey(event) {
var l = event.keyCode;
if(l == 13) {
$('#login').click();
}
} //function lkey
});
//end of login script
}else{
$('#s_btn').removeAttr('disabled');
function skey(event) {
var s = event.keyCode;
if(s == 13) {
$('#s_btn').click();
}
}
}
}); //keyup
})() //function
}); //load
//]]>
</script>
</head>
<body>
<div>
<form method="post" action="">
<div class="top menu">
<input type="text" name="search" id="s" />
<input type="submit" name="searchBtn" val="Search" id="s_btn" disabled="disabled" />
</div><!--end top menu-->
<div class="content">
<div class="left-col">
<table>
<tr>
<td><label for="user">Username: </label></td>
<td><input type="text" name="username" id="user" /></td>
</tr>
<tr>
<td><label for="pass">Password: </label></td>
<td><input type="password" name="password" id="pass" /></td>
</tr>
<tr>
<td colspan="2"><input type="button" name="loginBtn" id="login" disabled="disabled"/></td>
</tr>
</table>
</div><!--end left-col-->
<div class="right-col">
<ul>
<li>Stuff</li>
<li>Stuff</li>
</ul>
</div><!--end right-col-->
</div><!--end content-->
</form>
</div>
</body>
</html>

Unable to Submit form with multiple div id ...? please help me

Unable to submit form with multiple div id, when i have only one div id form is submitting correctly when i use more than one div id form is not submitting. I want to show the new fields when a radio button is pressed, for the purpose of hiding and visbility i used div id(four div id with different id names) please help
<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8">
<title>Report Generation</title>
<link rel="stylesheet" media="screen" href="../css/formstyle.css">
<script language="javascript" type="text/javascript">
function setVisible(id, visible) {
var o = document.getElementById(id);
if (typeof(o) != 'undefined') o.style.visibility = visible ? 'visible' : 'hidden';
if (typeof(o) == 'undefined') alert("Element with id '" + id + "' not found.");
}
function setDisplay(id, visible) {
var o = document.getElementById(id);
if (typeof(o) != 'undefined') o.style.display = visible ? 'block' : 'none';
if (typeof(o) == 'undefined') alert("Element with id '" + id + "' not found.");
}
</script>
</head>
<body onLoad="setVisible('Div4', false); setVisible('Div1', false);setVisible('Div3', false);setVisible('Div2', false);">
<form class="reg_form" action="pr.php" method="post" name="reg_form">
<ul>
<li>
<p>What type of Report you want to Create ?</p><br/>
</li>
<li>
<input type='radio' name='myradio' value='1' onclick="setVisible('Div1', true); setVisible('Div2', false);setVisible('Div3', false);setVisible('Div4', false);" />Based on Date<br/>
<input type='radio' name='myradio' value='2' onclick="setVisible('Div2', true); setVisible('Div1', false);setVisible('Div3', false);setVisible('Div4', false);" />Based on Income<br/>
<input type='radio' name='myradio' value='3' onclick="setVisible('Div3', true); setVisible('Div1', false);setVisible('Div2', false);setVisible('Div4', false);" />Based on District<br/>
<input type='radio' name='myradio' value='4' onclick="setVisible('Div4', true); setVisible('Div1', false);setVisible('Div3', false);setVisible('Div2', false);" />Based on Age<br/>
</li>
<li>
<div id='Div1'>
<p>From Date:</p> <input type="date" name= "from" required><br/>
<p>To Date:</p> <input type="date" name= "to" required><br/>
</div>
</li>
<li>
<div id='Div2'>
<p>Select Slab:</p>
<input type="radio" name="slab" value="s1">Slab-1<br/>
<input type="radio" name="slab" value="s2">Slab-2<br/>
<input type="radio" name="slab" value="s3">Slab-3<br/>
</div>
</li>
<li>
<div id='Div3'>
<p>Enter District:</p><br/>
<input type="text" name= "dist" required>
</div>
</li>
<li>
<div id='Div4'>
<p>Select Age From:</p><br/>
<input type="number" name= "afrom" required>
<p>To:</p>
<input type="number" name= "ato" required>
</div>
</li>
<li>
<button class="submit" type="submit">Submit Form</button>
</li>
</ul>
</div>
</form>
</body>
</html>
The problem is that you have required attributes on hidden input fields. When the form is submitted with these fields hidden (and them having no value), you're getting the errors:
An invalid form control with name='from' is not focusable.
An invalid form control with name='to' is not focusable.
An invalid form control with name='dist' is not focusable.
An invalid form control with name='afrom' is not focusable.
An invalid form control with name='ato' is not focusable.
By showing all the fields, or removing the required attributes, the form submits fine. A solution to this is to add the required attribute when shown and remove it when hidden.
To achieve this, firstly, define the following function:
function setRequired()
{
var r = document.getElementsByClassName('required')
for (var i in r)
{
if (r[i].parentNode && r[i].parentNode.style.visibility == 'visible')
{
r[i].required = true
}
else
{
r[i].required = false
}
}
}
Secondly, replace all required attributes with class="required". And thirdly, add ;setRequired() to the onclick events of the four radio buttons (at the end, after the setVisibles).
change:
<button class="submit" type="submit">Submit Form</button>
to:
<input type="submit">Submit Form</input>

Categories

Resources