I would like to validate myForm, so the user can input a value between 1 and a max on 99. When I submit a number I get showed a blank page, which is the select.php. But I would like to stay on my indexpage, and get the message "You are below". Can anyone see what is wrong here?
index.html:
<div class="content">
<p id="number"></p>
<div class="form">
<form id="myForm" action="select.php" method="post">
<input type="number" name="numbervalue" id="numberinput">
<input type="submit" id="sub" Value="Submit">
<span id="result"></span>
<span id="testnumber"></span>
</form>
</div>
</div>
JS:
var minNumberValue = 1;
var maxNumberValue = 99;
$('#sub').click(function(e){
e.preventDefault();
var numberValue = $('input[name=numbervalue]').val();
if(isNaN(numberValue) || numberValue == ''){
$('#testnumber').text('Please enter a number.')
return false;
}
else if(numberValue < minNumberValue){
$('#testnumber').text('You are below.')
return false;
}
else if(numberValue > maxNumberValue){
$('#testnumber').text('You are above.')
return false;
}
return true;
});
// Insert function for number
function clearInput() {
$("#myForm :input").each( function() {
$(this).val('');
});
}
$(document).ready(function(){
$("#sub").click( function(e) {
e.preventDefault(); // remove default action(submitting the form)
$.post( $("#myForm").attr("action"),
$("#myForm :input").serializeArray(),
function(info){
$("#result").html(info);
});
clearInput();
});
});
// Recieve data from database
$(document).ready(function() {
setInterval(function () {
$('.latestnumbers').load('response.php')
}, 3000);
});
How about utilizing the 'min' and 'max' attributes of the input tag, it would handle all the validation itself:
<input type="number" name="numbervalue" min="1" max="99">
Cheers,
Here's a little function to validate the number:
var minNumberValue = 1;
var maxNumberValue = 99;
$('#sub').click(function(e){
e.preventDefault();
var numberValue = $('input[name=numbervalue]').val();
if(isNaN(numberValue) || numberValue == ''){
$('#result').text('Please enter a number.')
return false;
}
else if(numberValue < minNumberValue){
$('#result').text('You are below.')
return false;
}
else if(numberValue > maxNumberValue){
$('#result').text('You are above.')
return false;
}
return true;
});
You can define the minimum and maximum values by changing the two variables (be sure to check these server-side too if you are submitting to a server, as the user could manipulate the code via dev tools to change these boundaries or submit whatever they want).
The result message is displayed in your span#result, otherwise you could use alert() too.
The important things here are the e parameter in the click function (it's the JavaScript event), calling e.preventDefault() (if you don't do this, the form will submit before finishing validation, as the default action for an input[type=submit] is to submit a form [go figure...]), returning false whenever the conditions aren't met, and returning true if it satisfies the validation. The return true; allows the form to follow its action parameter.
And a fiddle with this: https://jsfiddle.net/3tkms7vn/ (edit: forgot to mention, I commented out return true; and replaced it with a call to add a message to span#result just to prevent submission on jsfiddle.)
Related
I have a form which contain elements (checkboxes) that will be produced using JavaScript and I want to check if at least one of them is checked. Also, I have a few inputs that I want to check if at least one of them has value. The initial problem was The code I wrote displayed the error message but immediately submits the form. I can't use server side validation here because these items are created through JS. and I'm not sure if I can use server side validation to check if at least one input field has value.
For this problem I tried using e.preventDefault(); , it stops the form from submitting if there is no value or checkbox not checked but if there was a value it will still not submit the form
This the code I tried
$(function () {
$("#SubmitForm-btn").click(function () {
$("#fupForm").submit(function (e) {
e.preventDefault();
var valid = true;
//here I'm checking if any of the input field has value.
$('#dataTable tbody tr td input[type=text]').each(function () {
var text_value = $(this).val();
if (!hasValue(text_value)) {
valid = false;
$("#tableEmpty").html("Please Choose a Service");
return false;
}
else {
$("#fupForm").unbind('submit');
valid = true;
return true;
}
})
//here I'm checking if any of the checkbox is checked.
$('.check').each(function () {
if (!$(this).is(':checked')) {
valid = false;
$("#Person_errorMSG").html("Please choose a person");
return false;
}
else {
$("#fupForm").unbind('submit');
valid = true;
return true;
}
});
//here I'm checking if any of the checkbox is checked.
$('.Fromcheck').each(function () {
if (!$(this).is(':checked')) {
valid = false;
$("#From_errorMSG").html("Please choose a City");
return false;
}
else {
$("#fupForm").unbind('submit');
valid = true;
return true;
}
});
//here I'm checking if any of the checkbox is checked.
$('.Tocheck').each(function () {
if (!$(this).is(':checked')) {
valid = false;
$("#To_errorMSG").html("Please choose a To city");
return false;
}
else {
$("#fupForm").unbind('submit');
valid = true;
return true;
}
});
});
});
});
You should prevent the button click event, instead of the form submit action.
Please refer the following sample code:
In the View page, we have a mainform.
<form id="mainform" asp-action="AddAttribute">
<div asp-validation-summary="ModelOnly" class="text-danger"></div>
<div class="form-group">
<label asp-for="AttributeId" class="control-label"></label>
<input asp-for="AttributeId" class="form-control" />
<span asp-validation-for="AttributeId" class="text-danger"></span>
</div>
...
<div class="form-group">
Is Submit <input type="checkbox" class="isSubmit" />
</div>
<div class="form-group">
<input type="submit" value="Create" class="btn btn-primary" id="SubmitForm-btn" />
</div>
</form>
At the end of the above page, add the following script:
#section Scripts {
#{await Html.RenderPartialAsync("_ValidationScriptsPartial");}
<script>
$(function () {
$("#SubmitForm-btn").click(function () {
event.preventDefault(); //prevent the default submit action.
//check if the checkbox is checked or not.
var ischecked = $(".isSubmit").last().is(":checked");
if (ischecked) {
//alert("Checked");
//if the cleckbox checked, submit the form.
$("#mainform").submit();
}
else {
//alert("Unchecked");
//show notification message. and the form will not submit.
}
});
});
</script>
}
The result as below:
I tried to delay for 10 sec before submit form like this but not work. It's will be still return true by not to delay.
<form class="form" method="post" action="" ENCTYPE = "multipart/form-data" onsubmit="return checkform(this);" >
<input type="submit" name="submit" value="OK">
</form>
<script language="JavaScript" type="text/javascript">
function checkform ( form )
{
var test = "1";
setTimeout(function(){
if(test != '0'){
return false;
}
else
{
return true;
}
}, 10000);
}
</script>
I want to know, how to delay on checkform using javascript ?
You must return to the checkForm function. A return inside a callback does not return to the outer function. Even if it did it must be immediate, not 10 seconds later
You could use a flag so you can call the function again inside the delay by submitting the form again
var allowSubmit = false;
function checkform(form) {
if (allowSubmit) {
return true;
} else {
var test = "1";
setTimeout(function() {
if (test === '1') {
// when validation passes resubmit with updated flag
allowSubmit = true;
form.submit();
}
}, 10000);
return false;
}
}
Here is a better way to do it if you have jQuery library included. In your case, the page gets submitted to itself and gets refreshed, so your 10 seconds get reset.
<form class="form" method="post" action="" enctype = "multipart/form-data" >
<input type="submit" name="submit" value="OK">
</form>
$(function(){
$("form").bind("submit", function(e){
e.preventDefault();
e.stopPropagation();
var test = "1";
setTimeout(function(){
if(test != '0'){
//return false;
alert("false");
}else{
alert("true")
//return true;
}
}, 10000);
});
});
So the problem here is that a submit request is has the same outcome as if you were to return something in a function.
For example if you had something like this:
function returnExplanation(){
return 0;
console.log("You will never see me");
}
You will never see the text in the console after the return.
A submit functions the same. although there are a few other ways to make this happen, I made a few adjustments to your code to achieve what you were looking for.
<form class="form" id="submitForm" method="post" action="" ENCTYPE = "multipart/form-data">
<input type="button" name="submit" value="OK">
</form>
<script language="JavaScript" type="text/javascript">
$(document).ready(function () {
$('#submitForm').on('click', function ()
{
var test = 1;
setTimeout(
function ()
{
if (test !== 0)
{
console.log("false");
return false;
} else
{
console.log("true");
return true;
}
}, 10000);
$('#submitForm').submit();
});
});
</script>
The first thing I did was give your form an "id". this allows jQuery (or javascript) to easily decipher exactly which element they should be communicating with.
Next, I removed your "onsubmit" attribute and added the appropriate jQuery to respond to the click event.
After that, I changed your button from a "submit" to a "button" type.
lastly, after the timeout, your form still submits with the line that reads:
$('#submitForm').submit();
I hope this helps you on your way to becoming a better HTML / jQuery programmer.
I am trying to validate some input fields. More specifically, the number always has to be positive.
EDIT: JS code
$(document).ready(function($) {
$('.error-message').hide();
function priceCheck() {
$('input[class="price"]').each(function() {
priceValue = $(this).val();
console.log(priceValue); //only runs until here and seems it exists the function then
if (priceValue <= 0) {
evt.preventDefault();
return false;
} else {
}
});
}
//POST FORM
$("#offerInquiry").on('valid.fndtn.abide', function(evt) {
//prevent the default behaviour for the submit event
// Serialize standard form fields:
var formData = $(this).serializeArray();
var checked = $("#terms").is(":checked");
priceCheck();
if (checked == false) {
$('.error-message-container').empty();
$('.error-message-container').append("<%= pdo.translate("
checkBox.isObligatory ") %>");
$('.error-message').show();
$('.bid-error').css("display", "block");
evt.preventDefault();
return false;
} else {
loading();
$.post("/inquiry.do?action=offer&ajax=1", formData,
function(data) {
window.top.location.href = data.redirectPage;
});
}
return false;
});
});
I have written a function that I separately call on form submit. But it only runs until the console log. Why is the if else statement not executed?
You are using evt.preventDefault() but you didn't capture the event in evt.
For example, you could try this instead: add the evt parameter to the priceCheck function, and then pass evt to that function when you call it, like this: priceCheck(evt)
HOWEVER, you do not need to use preventDefault here. You can simply return a boolean value from priceCheck and use that in your submit handler.
You also you had a couple errors with string concatentation. $('.error-message-container').append("<%= pdo.translate(" checkBox.isObligatory ") %>"); was missing the + to concat those strings together . You can view errors like this in the Console tab of your JavaScript debugger. (UPDATE This is JSP injection, but it may not work the way you are trying to use it here. The server function pdo.translate will only execute once, on the server side, and cannot be called via client script... but it can emit client script. Focus on solving other problems first, then come back to this one.)
Finally, you were reading string values and comparing them to numbers. I used parseFloat() to convert those values from the input fields into numbers.
Here is the fixed code.
$(document).ready(function($) {
$('.error-message').hide();
function priceCheck() {
var priceValid = true; // innocent until proven guilty
$('input[class="price"]').each(function() {
priceValue = parseFloat($(this).val()) || 0;
if (priceValue <= 0) {
priceValid = false;
return false;
}
});
return priceValid;
}
$("form").on("submit", function() {
$("#offerInquiry").trigger('valid.fndtn.abide');
});
//POST FORM
$("#offerInquiry").on('valid.fndtn.abide', function(evt) {
//prevent the default behaviour for the submit event
// Serialize standard form fields:
var formData = $(this).serializeArray();
var checked = $("#terms").is(":checked");
var priceValid = priceCheck();
if (priceValid) {
$('.error-message').hide();
if (checked == false) {
$('.error-message-container').empty();
$('.error-message-container').append("<%= pdo.translate(" + checkBox.isObligatory + ") %>");
$('.error-message').show();
$('.bid-error').css("display", "block");
return false;
} else {
loading();
$.post("/inquiry.do?action=offer&ajax=1", formData,
function(data) {
window.top.location.href = data.redirectPage;
});
}
}
else
{
$('.error-message').show().text("PRICE IS NOT VALID");
}
return false;
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="offerInquiry">
Price 1
<input type="text" class="price" id="price1" value="0.00" />
<br/>Price 2
<input type="text" class="price" id="price1" value="0.00" />
<br/>
<input type='submit' />
<div class="error-message">ERROR!</div>
</form>
I have a form and I am trying to run some validation on it to catch required fields on older browsers and Safari(!). The solution I have so far seems to almost work... When I submit the form with empty fields on Safari the error pops up, and then the form is submitted anyway. What am I doing wrong?
My form looks like this:
<form id="primaryPostForm" method="POST" >
<input type="text" name="iName" id="iID" maxlength="25" required="required" value="" />
<textarea class="tipContent requiredAttr" name="taName" id="taID" maxlength="150" required="required" ></textarea>
<input type="hidden" name="submitted" id="submitted" value="true" />
<input id="submitBtn" type="submit" value="Submit">
My validation looks like this:
function validate(){
$('#primaryPostForm').submit(function(){
$("#primaryPostForm .requiredAttr").each(function(){
if($(this).val().length < 1){
alert("Please make sure the fields are filled in - thanks");
return false;}
})//end each
})//end submit
}
The return false only exits from the each loop. You need to store a result that you can return from the function:
function validate(){
$('#primaryPostForm').submit(function(){
var result = true;
$("#primaryPostForm .requiredAttr").each(function(){
if($(this).val().length < 1){
alert("Please make sure the fields are filled in - thanks");
result = false;
return false; // exit loop
}
})//end each
return result;
})//end submit
}
First off, use e.preventDefault(); instead of return false.
To answer your question:
return false must be in the scope of the submit event callback:
function validate(){
$('#primaryPostForm').submit(function(e){
var ret = true;
$("#primaryPostForm .requiredAttr").each(function(){
if($(this).val().length < 1){
alert("Please make sure the fields are filled in - thanks");
ret = false;
}
});
if(!ret){
e.preventDefault();
}
});
}
A more concise and direct way to do this would be:
$('#primaryPostForm').submit(function(e){
var required = $(".requiredAttr", this).filter(function(){
return !this.value;
});
if(required.length){
alert("Please make sure the fields are filled in - thanks");
e.preventDefault();
}
});
Try this, refer to MDN
function validate(){
$('#primaryPostForm').submit(function(){
var result = [];
$("#primaryPostForm .requiredAttr").each(function(){
if($(this).val().length < 1){
result.push(false);
}
})//end each
result.some(function(element){return (element!=false)})
alert("Please make sure the fields are filled in - thanks");
})//end submit
}
I have a strange behaviour in IE browser.
I have simple form:
<form name="test" id="test" action="some_url_here" method="post">
<input type="text" name="url" id="url" class="required" />
<input type="text" name="page" id="page" class="required" />
...
<input type="submit" name="submit" value="Submit" />
</form>
and in JS:
var result = true;
$("#test").on("submit", function(){
$(".required").removeClass("error");
$.each($("input.required"), function(k, v) {
if($(this).val() === '') {
$(this).addClass("error");
result = false;
return false;
}
});
if(result) {
if(!IsValidUrl($("input[name='url']").val()){
$("input[name='url']").addClass("error");
return false;
}
} else {
return false;
}
});
Let's assume that I filled all fields correctly.
In Chrome & Firefox, when I press on submit button then works fine, just once time.
In IE (all versions) I have to press two times on the submit form to execute/sumbit the form.
Why ?
I tried also to put after IsValidUrl condition:
$(this).submit();
But no success.
You have two options here. On both you need to stop the submit event and validate the form.
One is to go through all the fields in the form, add the class error to the invalid ones (if there's any), set the variable result and return (or submit if everything is alright).
The other is to stop the test at the first invalid field found, not using the variable result, and return (or submit if everything is alright).
JS
$(function () {
$("#test").on("submit", function (e) {
// Stop the submit, because you need to validate the form before proceeding.
e.preventDefault();
// Check the comments below to decide for the use of the variable.
var result = true;
$(".required").removeClass("error");
$.each($("input.required"), function (k, v) {
// Test for empty fields or, if it's the URL, check whether is valid.
if ($(this).val() === "" || ($(this).attr("name") == "url" && !IsValidUrl($(this).val())) {
// Add class error to the invalid fields.
$(this).addClass("error");
// At this point, you could just return false stopping the loop,
// or keep going to make sure all the invalid fields will get the
// class error. In this case, you can still use the variable result.
result = false;
// Keep going, so, no return.
// return false;
}
});
// If you decided to carry on through all the fields, and don't return
// false at the first error, test for the result value.
// As this is the case...
if (!result) return false;
else $(this).submit();
// If you didn't return previously...
// $(this).submit();
});
});