user2338652
user2338652

Reputation: 467

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!

Upvotes: 7

Views: 3248

Answers (10)

CodingSolutions
CodingSolutions

Reputation: 81

    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;

    }

Upvotes: 0

Brewal
Brewal

Reputation: 8189

I would personaly use the disabled html attribute.
See this jsFiddle Demo

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

$('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 :

input[disabled] {
    display: none;
}

Demo

Upvotes: 2

user1956570
user1956570

Reputation: 142

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

});

Upvotes: 0

nnnnnn
nnnnnn

Reputation: 150030

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.

Upvotes: 0

BeNdErR
BeNdErR

Reputation: 17927

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/

Upvotes: 0

James Donnelly
James Donnelly

Reputation: 128791

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.

Upvotes: 1

Erik Christianson
Erik Christianson

Reputation: 507

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.

Upvotes: 1

Explosion Pills
Explosion Pills

Reputation: 191749

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/

Upvotes: 1

Denis
Denis

Reputation: 5271

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.

Upvotes: 1

Arun P Johny
Arun P Johny

Reputation: 388316

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

Upvotes: 1

Related Questions