Javascript - check if serialized form is empty - javascript

I'm trying to check if the form inputs are all empty. It works fine when any input has value (returns true) but doesn't return false when input gets empty again.
var data;
$('form :input').on('input', function() {
data = $('form').serialize();
console.log(data.indexOf('=&') > -1)
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
<input type="text" name="in-1" />
<input type="text" name="in-2" />
<input type="text" name="in-3" />
<input type="text" name="in-4" />
<input type="text" name="in-5" />
<input type="text" name="in-6" />
<input type="text" name="in-7" />
<input type="text" name="in-8" />
</form>

(data.indexOf('=&') > -1
will return true when at least one of the fields is blank - you're checking for the existence of the =&, and as soon as one field is blank, this string will exist. However, relying on the serialised version of the data is a bit of a hack anyway IMHO. Much better to check the inputs directly:
$('form :input').on('input', function() {
var allBlank = true; //assume they're all blank until we discover otherwise
//loop through each of the inputs matched
$('form :input').each(function(index, el)
{
if ($(el).val().length != 0) allBlank = false; //they're not all blank anymore
});
console.log(allBlank);
});

var serialized = $(form).serialize();
if(serialized.indexOf('=&') > -1 || serialized.substr(serialized.length - 1) == '='){
//you've got empty values
}
Using jQuery, you can test it before serializing:
$(form).find('input').each(function(index, elem){
if($(elem).val().length == 0){
//this field is empty
}
});

data.split('&').every(e => { return e.indexOf('=') === (e.length - 1); })

Related

Check if there are multiple input fields with the same value

What is the simplest way to check with jQuery if we have multiple input fields on the page with the same value?
Thank you all!
You can iterate all input elements, store their value in a hash table, and check if the value was already there:
var hash = Object.create(null),
result = [].some.call(document.getElementsByTagName('input'), function(inp) {
if(hash[inp.value]) return true;
hash[inp.value] = true;
});
Get all the input elements, sort and check if there are duplicates.
var elements = document.getElementsByTagName("input")
var values = [];
for (var i = 0; i < elements.length; i++) {
values.push(elements[i].value);
}
var sortedValues = values.sort();
for (var o = 0; o < values.length-1; o++) {
if (values[o] == values[o+1])
alert ('Duplicate!');
}
You can loop thru all inputs and generate a data structure like below.
var inputs = {};
$("input").each(function(i, elem) {
if (inputs.hasOwnProperty(elem.value)) {
inputs[elem.value] += 1;
} else {
inputs[elem.value] = 1;
}
});
alert (JSON.stringify(inputs, null, 4))
A Demo
The solution is to write a loop and iterate through each input field for a possible match. If you're using jQuery, then it's actually very simple.
Let's say we have a simple HTML page with 3 input fields.
HTML:
<input type="text" name="input1">
<input type="text" name="input2>
<input type="text" name="input3">
Then we use the jQuery each() method to iterate over the fields. Mainly saying, we iterate over all the input fields and get their values. Then we again iterate through all the input fields (so were actually creating a nested loop) and check if any of them match the currently iterating input value.
jQuery:
var currentInput;
$("input").each(function(index) {
currentInput = $(this);
$("input").each(function(index) {
if currentInput.val() === $(this).val() {
alert("Error: input fields match found");
}
});
});
I would like to provide a more efficient answer when it comes to checking for duplicate values in multiple input fields. When it comes to comparing values we need to,
Iterate and keep the current element somewhere temporarily
Re-iterate and check against the previously kept value whether its a duplicate
When performing the step 2, we need to make sure that we skip comparing the previously kept (step 1) value against itself.
If I am not wrong, I have seen step 1 and 2 in all above answers but not the step 3.
The following code will do all those 3 steps.
var eqArr = [];
var currentInput;
$("input").each(function(k1, v1) {
if($(v1).val() != ''){
currentInput = $(v1);
$("input").each(function(k2, v2) {
if(k1 !== k2 &&
currentInput.val() === $(v2).val() &&
$.inArray($(this).attr('id'), eqArr) === -1){
eqArr.push($(this).attr('id'));
}
});
}
});
In the above code I am collecting id's of those input fields of those duplicates (in array). After performing the above logic, doing following simple check will tell you whether you have duplicates or not.
if(eqArr.length > 0){
//It means we have duplicates
}
var eqArr = [];
var currentInput;
$("input").each(function(k1, v1) {
if ($(v1).val() != '') {
currentInput = $(v1);
$("input").each(function(k2, v2) {
if (k1 !== k2 &&
currentInput.val() === $(v2).val() &&
$.inArray($(this).attr('id'), eqArr) === -1) {
eqArr.push($(this).attr('id'));
}
});
}
});
console.log(eqArr);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>Input Field Duplicates</title>
</head>
<body>
<input type="text" name="input1" id="i1" value="bbb">
<input type="text" name="input2" id="i2" value="aaa">
<input type="text" name="input3" id="i3" value="aaa">
<input type="text" name="input3" id="i4" value="fff">
<input type="text" name="input3" id="i5" value="bbb">
<input type="text" name="input3" id="i6" value="ccc">
<input type="text" name="input3" id="i7" value="bbb">
<input type="text" name="input3" id="i8" value="bbb">
</body>
</html>

jquery each loop check if at least one field has been filled

Let's say that I have an HTML structure like this:
<input type="text" name="input_1" class="required" value="" />
<input type="text" name="input_2" class="required" value="" />
<input type="text" name="input_3" class="required one" value="" />
<input type="text" name="input_4" class="required one" value="" />
<input type="text" name="input_5" class="required" value="" />
As you can see each text field above has the class required but there are two of them that also have the class one. What I wanna do is to iterate over these text fields and check if they are not empty but for the ones that have the class one, at least one of them is required (not both at the same time). If I iterate over the input with class required, how do I check if at least one of the inputs with class one has been filled (within the same loop)? Thank you
You can do:
var oneIsFilled = false;
$(":text.required").each(function() {
if ($(this).hasClass("one") {
if (this.value.length > 0)
oneIsFilled = true;
}
});
These here will additionally cover the checking of the required fields:
Working example see my fiddle: http://jsfiddle.net/Florian_Loch/A3C5C/1/
function click() {
var bool = check();
if (bool) {
alert("OK!");
} else {
alert("NOOOO!");
}
}
function check() {
var one = false;
var res = true;
$(".required").each(function () {
if ($(this).hasClass("one") && this.value.length > 0) {
one = true;
}
if ($(this).hasClass("required") && $(this).hasClass("one") == false && this.value.length == 0) {
res = false;
return; //We can leave here already
}
});
if (!res) {
return false;
}
else {
return one;
}
}
Cheers,
Florian

How to validate if textbox value is empty in a series of textboxes?

There are a series of textboxes like:
<input type="text" class="jq-textBox" />
<input type="text" class="jq-textBox" />
<input type="text" class="jq-textBox" />
<input type="text" class="jq-textBox" />
<input type="text" class="jq-textBox" />
User can fill up the textbox values from top to bottom order. Only first textbox is required and all other textboxes are optional.
Allowed order to fill textbox values:
1st
1st & 2nd
1st, 2nd & 3rd
and likewise in sequence order
Dis-allowed order:
2nd
1st & 3rd
1st, 2nd & 4th
This means that user needs to fill up the first textbox only or can fill up the other textboxes in sequential order. User can NOT skip one textbox and then fillup the next one.
How to validate this in javascript/jQuery?
Any help is highly appreciated!
I would personaly use the disabled html attribute.
See this jsFiddle Demo
html
<form>
<input type="text" class="jq-textBox" required="required" />
<input type="text" class="jq-textBox" disabled="disabled" />
<input type="text" class="jq-textBox" disabled="disabled" />
<input type="text" class="jq-textBox" disabled="disabled" />
<input type="text" class="jq-textBox" disabled="disabled" />
<input type="submit" />
</form>
(Note the required attribute for HTML5)
jquery
$('input.jq-textBox').on('keyup', function(){
var next = $(this).next('input.jq-textBox');
if (next.length) {
if ($.trim($(this).val()) != '') next.removeAttr('disabled');
else {
var nextAll = $(this).nextAll('input.jq-textBox');
nextAll.attr('disabled', 'disbaled');
nextAll.val('');
}
}
})
Also see nextAll() jquery Method
Edit :
If you want to hide the disabled inputs in order to show them only when the previous input is filled, just add this css :
input[disabled] {
display: none;
}
Demo
You can iterate over the list backwards to quickly figure out whether there is a gap.
var last = false,
list = $(".jq-textBox").get().reverse();
$.each(list, function (idx) {
if ($(this).val() !== "") {
last = true;
}
else if (last) {
alert("you skipped one");
}
else if (list.length === idx + 1) {
alert("must enter 1");
}
});
http://jsfiddle.net/rnRPA/1/
Try
var flag = false, valid = true;
$('.jq-textBox').each(function(){
var value = $.trim(this.value);
if(flag && value.length !=0){
valid = false;
return false;
}
if(value.length == 0){
flag = true;
}
});
if(!valid){
console.log('invalid')
}
Demo: Fiddle
You can find all inputs that are invalid (filled in before the previous input) this way:
function invalidFields() {
return $('.jq-textBox')
.filter(function(){ return !$(this).val(); })
.next('.jq-textBox')
.filter(function(){ return $(this).val(); });
}
You can then test for validity:
if (invalidFields().length) {
// invalid
}
You can modify invalid fields:
invalidFields().addClass('invalid');
To make the first field required, just add the HTML attribute required to it.
I think a more elegant solution would be to only display the first textbox, and then reveal the second once there is some input in the first, and then so on (when they type in the second, reveal the third). You could combine this with other solutions for testing the textboxes.
To ensure the data is entered into the input elements in the correct order, you can set up a system which modifies the disabled and readonly states accordingly:
/* Disable all but the first textbox. */
$('input.jq-textBox').not(':first').prop('disabled', true);
/* Detect when the textbox content changes. */
$('body').on('blur', 'input.jq-textBox', function() {
var
$this = $(this)
;
/* If the content of the textbox has been cleared, disable this text
* box and enable the previous one. */
if (this.value === '') {
$this.prop('disabled', true);
$this.prev().prop('readonly', false);
return;
}
/* If this isn't the last text box, set it to readonly. */
if(!$this.is(':last'))
$this.prop('readonly', true);
/* Enable the next text box. */
$this.next().prop('disabled', false);
});
JSFiddle demo.
With this a user is forced to enter more than an empty string into an input field before the next input is essentially "unlocked". They can't then go back and clear the content of a previous input field as this will now be set to readonly, and can only be accessed if all following inputs are also cleared.
JS
var prevEmpty = false;
var validated = true;
$(".jq-textBox").each(function(){
if($(this).val() == ""){
prevEmpty = true;
}else if($(this).val() != "" && !prevEmpty){
console.log("nextOne");
}else{
validated = false;
return false;
}
});
if(validated)
alert("ok");
else
alert("ERROR");
FIDDLE
http://jsfiddle.net/Wdjzb/1/
Perhaps something like this:
var $all = $('.jq-textBox'),
$empty = $all.filter(function() { return 0 === $.trim(this.value).length; }),
valid = $empty.length === 0
|| $empty.length != $all.length
&& $all.index($empty.first()) + $empty.length === $all.length;
// do something depending on whether valid is true or false
Demo: http://jsfiddle.net/3UzHf/ (thanks to Arun P Johny for the starting fiddle).
That is, if the index of the first empty item plus the total number of empties adds up to the total number of items then all the empties must be at the end.
This is what you need :
http://jsfiddle.net/crew1251/jCMhx/
html:
<input type="text" class="jq-textBox" /><br />
<input type="text" class="jq-textBox" disabled/><br />
<input type="text" class="jq-textBox" disabled/><br />
<input type="text" class="jq-textBox" disabled/><br />
<input type="text" class="jq-textBox" disabled/>
js:
$(document).on('keyup', '.jq-textBox:first', function () {
$input = $(this);
if ($input.val()!='')
{
$('input').prop('disabled',false);
}
else {
$('input:not(:first)').prop('disabled',true);
}
});
var checkEmpty = function ()
{
var formInvalid = false;
$('#MyForm').each(function () {
if ($(this).val() === '') {
formInvalid = true;
}
});
if (formInvalid) {
alert('One or more fields are empty. Please fill up all fields');
return false;
}
else
return true;
}

How to check if the user has not entered the data to a form (befor sending)?

I have some input form on names: owner, number, city
<input id="id_owner" type="text" name="owner" maxlength="250" />
<input id="id_number" type="text" name="number" maxlength="250" />
<input id="id_city" type="text" name="city" maxlength="250" />
How to check if the user has not entered the data to a form (befor sending) that does not show this dialog from this code:
<a type="submit" name"save-continue-to-review" data-toggle="modal" data-target="#dialog" href=""
class="btn primary btn-primary" title="Order">Order
</a>
and it will show another
Here is full code: http://wklej.org/id/927806/
Eventually you'll be able to use HTML5 form validation. But until then, use some jQuery code like this. (only because you tagged the question with jQuery. You could potentially do it with vanilla JS.)
(un-tested code, but should work)
var fields = $('input')
$('form').submit(function(e){
e.preventDefault()
valid = true
fields.each(function(){
if ($(this).val() == null) {
valid = false
}
});
if (valid == true) {
$('form').submit()
} else {
alert("At least one field was not valid!")
}
});
1) Add this on your form
onsubmit="return validateForm(this);"
2)The validate function (checks if fields are empty)
function validateform(formObj)
{
inputs = formObj.GetElementsByTagName('input');
for(i=0; i < inputs.length; i++)
{
if($.trim(inputs[i].value) == '')
{
alert('Field: ' + inputs[i].name + ' is empty!');
return false;
}
}
return true;
}
if ( !$(this).val() ) {
valid = false
}
maybe this post is useful for you

comparing 50 pairs of input textboxes

If I have 50 pairs of input textboxes, i.e.
<input type="text" id="name_0" /><input type="text" id="name_1" />
<input type="text" id="dept_0" /><input type="text" id="dept_1" />
...
<input type="text" id="age_0" /><input type="text" id="age_1" />
<input type="text" id="weight_0" /><input type="text" id="weight_1" />
i.e 50 variables of these.
When the page loads, I populate each pair with identical data.
What is the best way to check if the _0 is different from the _1?
then returning a message showing which pair has changed.
The comparison should take place once the values have been changed and a button is clicked.
$("input[type=text]").each(function () {
var $this = $(this);
if ( /_0$/.test(this.id) ) {
if ( $this.val() != $this.next("input").val() ) {
$this.css("color", "red"); // or whatever
}
}
});
Tomalak's answer should work, but just in case your inputs are scattered or not necessarily beside each other, something like this should suffice.
$('input:text[id$="_0"]').each(function() {
var new_id = this.id.replace('_0','_1');
if ($(this).val() !== $('input#'+new_id).val()) {
// not the same
}
});
var changed = [];
$("[id$=_0]").each(function() {
var name = this.id.replace("_0", "");
if (this.value != $("#" + name + "_1").val()) {
changed.push(name);
}
});
console.log(changed);

Categories