最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to validate if textbox value is empty in a series of textboxes? - Stack Overflow

programmeradmin6浏览0评论

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!

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!

Share Improve this question edited Oct 4, 2013 at 20:02 Sparky 98.7k26 gold badges202 silver badges290 bronze badges asked Oct 4, 2013 at 13:25 user2338652user2338652 4672 gold badges6 silver badges13 bronze badges
Add a ment  | 

10 Answers 10

Reset to default 2

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/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 bine 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/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/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/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;

    }
发布评论

评论列表(0)

  1. 暂无评论