Validating a form to not submit on empty input boxes - javascript

// html
<label>Write Data:</label>
</br>
<input type=text id=data name="data"style="width: 14em;">
</br>
</br>
<button id="write" type="submit" formaction="/output4" formmethod="post" style="width: 5em;">Write</button>
<button id="More" type="submit">Add more Parameters</button>
// js
$('#write').click(function(){
$('#data').each(function() {
if ($(this).val() == "" || $(this).val() == null) {
alert("Write Data must be filled out or Remove empty parameter list!");
return false;
}
});
});
I have a program where if a user clicks on a button, more write data boxes are appended. I do not want the form to submit unless all the write data boxes are filled out. The snippet above shows the alert box if an input if incomplete but then when you press ok, the form still submits?

You can use the .submit() event handler. Then use either return false or e.preventDefault() to stop the submit. Also note that id's are unique so $('#data') will only be a single element, so the .each() isn't needed:
$('#formIDHere').submit(function(e){
if ($('#data').val() == "" || $('#data').val() == null) {
alert("Write Data must be filled out or Remove empty parameter list!");
e.preventDefault(); // or `return false`
}
});
For many inputs have your input items be a class with the value class="data". Just note you need to to use e.preventDefault() using the e from the submit event. In this case return false is for the .each() and not the submit. I use it here to stop the .each from going so we don't have many unneeded alerts and checks:
$('#myForm').submit(function(e){
$('.data').each(function(){
if ($(this).val() == "" || $(this).val() == null) {
alert("Write Data must be filled out or Remove empty parameter list!");
e.preventDefault(); // This is the preventDefault of submit
return false; // This stops the .each from continuing
}
});
});
Demo

$('#write').click(() => {
// if any one of the inputs is blank canSubmit will end up as false
// if all are not blank, it will end up as true
var canSubmit = [...document.querySelectorAll('input')]
.reduce((acc, input) => acc = input.value === '' ? false : acc , true)
});

<script type="text/javascript">
$(function () {
$("#data").bind("change keyup", function () {
if ($("#data").val() != "")
$(this).closest("form").find(":submit").removeAttr("disabled");
else
$(this).closest("form").find(":submit").attr("disabled", "disabled");
})
});
</script>
This would allow you to disable your submit button until there was data within the input field.

Related

Jquery min and max show new page

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.)

Disable form button unless all text input fields are filled in

I have a form that has multiple text inputs, I don't want to add id to each one as they are generated from server side code - number of fields may differ etc. I just want to be able to disable the submit button until there is text entered into each text input.
I have gotten this far, but only disables button until text entered in to one text input field - I want it to stay disabled until text entered in to all text inputs.
<script>
$(function () {
$('#button').attr('disabled', true);
$('input:text').keyup(function () {
$('#button').prop('disabled', this.value == "" ? true : false);
})
});
</script>
I have also tried $('input:text').each().keyup(function (){ - but does not make button clickable?
$('#button').attr('disabled', true);
$('input:text').keyup(function () {
var disable = false;
$('input:text').each(function(){
if($(this).val()==""){
disable = true;
}
});
$('#button').prop('disabled', disable);
});
Demo
The callback function for keyup now checks only that specific input field's value (this.value). Instead, this needs to loop through all input fields that need to be filled, and only when all have text do you change the the .prop value.
$('input:text').keyup(function () {
$('#button').prop('disabled', allFieldsAreFilled());
});
function allFieldsAreFilled() {
var allFilled = true;
// check all input text fields
$("#yourForm input:text"]).each(function () {
// if one of them is emptyish allFilled is no longer true
if ($(this).val() == "") {
allFilled = false;
}
});
return allFilled;
}
Try this:
$(function() {
var bool = true, flag = false;
$('#button').prop('disabled', bool); // use prop to disable the button
$(document).keyup(function() { // listen the keyup on the document or you can change to form in case if you have or you can try the closest div which contains the text inputs
$('input:text').each(function() { // loop through each text inputs
bool = $.trim(this.value) === "" ? true : false; // update the var bool with boolean values
if(bool)
return flag;
});
$('#button').prop('disabled', bool); // and apply the boolean here to enable
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type='text' />
<input type='text' />
<input type='text' />
<input type='text' />
<input type='text' />
<input type='button' id='button' value='button' />

I have to press submit button twice in IE using jquery framework to submit form

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();
});
});

Want to prevent a textbox from becoming empty with javascript

So i already have a textbox in which you can only enter numbers and they have to be within a certain range.The textbox defaults to 1,and i want to stop the user from being able to make it blank.Any ideas guys?Cheers
<SCRIPT language=Javascript>
window.addEventListener("load", function () {
document.getElementById("quantity").addEventListener("keyup", function (evt) {
var target = evt.target;
target.value = target.value.replace(/[^\d]/, "");
if (parseInt(target.value, 10) > <%=dvd5.getQuantityInStock()%>) {
target.value = target.value.slice(0, target.value.length - 1);
}
}, false);
});
<form action="RegServlet" method="post"><p>Enter quantity you would like to purchase :
<input name="quantity" id="quantity" size=15 type="text" value="1" />
You could use your onkeyup listener to check if the input's value is empty. Something along the lines of:
if(target.value == null || target.value === "")
target.value = 1;
}
You could add a function to validate the form when the text box loses focus. I ported the following code at http://forums.asp.net/t/1660697.aspx/1, but it hasn't been tested:
document.getELementById("quantity").onblur = function validate() {
if (document.getElementById("quantity").value == "") {
alert("Quantity can not be blank");
document.getElementById("quantity").focus();
return false;
}
return true;
}
save the text when keydown
check empty when keyup, if empty, restore the saved text, otherwise update the saved text.
And you could try the new type="number" to enforce only number input
See this jsfiddle

Javascript, alert if a value on $(reviewForm).serialize() is blank?

I'm submitting a form with JS and I want to cancel the submit if any field is blank.
I'm getting all values with: $(reviewForm).serialize()
which returns something like:
id=2&text=aaaa&rating=2&gender=
How can I show an alert if any value in the form is blank?
var serialized = $(reviewForm).serialize();
if(serialized.indexOf('=&') > -1 || serialized.substr(serialized.length - 1) == '='){
//you've got empty values
}
using jQuery, you can test it before serializing:
$(reviewForm).find('input').each(function(idx, elem){
if($(elem).val().length == 0){
//this field is empty
}
});
Before submitting the form you can do something like this.
if($(reviewForm).find('input, select, textarea').filter(function(){
return $(this).val() == '';
}).length > 0){
alert('Enter all the values');
}
else{
//Submit the form here
}
This will check for empty fields, return array of the field names, and alert how many fields are empty. check the fiddle for a demo: http://jsfiddle.net/brentmn/Pwngn/
$('form').submit(function(){
var s = $(this).serialize();
var empty = $.grep(s.split('&'), function(field){
//get empty fields
return field.split('=')[1] === '';
}).map(function(arr){
//return field name of empty field
return arr.split('=')[0];
});
alert(empty.length + ' empty fields');
return !empty.length;
});

Categories

Resources