简体   繁体   中英

How can I show input fields only when previous input has a valid value?

I have a form that requires between 3 and 10 text input items. When the form first loads it will show 3 inputs (minimum).

I'd like to efficiently show input rows as the previous row has a valid value (let's assume greater than 3 characters for example). So if you fill out the first 3, you will automatically see a 4th optional input row.

Can you help me loop through this quick list efficiently in jQuery?

HTML:

<input type="text" class="item_1" name="item_1">
<input type="text" class="item_2" name="item_2">
<input type="text" class="item_3" name="item_3">
<input type="text" class="item_4" name="item_4">
<input type="text" class="item_5" name="item_5">
<input type="text" class="item_6" name="item_6">
<input type="text" class="item_7" name="item_7">
<input type="text" class="item_8" name="item_8">
<input type="text" class="item_9" name="item_9">
<input type="text" class="item_10" name="item_10">

CSS:

.item_4,.item_5,.item_6,.item_7,.item_8,.item_9,.item_10 { display:none }

This is pretty simple - you shouldn't even need a loop if you let jQuery's chaining do the work. I'd do something like:

$("#myform input").change(function(){ //If an input in your form is changed,
    if ($(this).val() == 42){ //replace with your validation logic :)
         $(this).next('input').show(); //This shows the next sibling element to the triggering element
    } else { //but if it fails validation...
         $(this).nextAll('input').hide().val(""); //hide them and delete the contents to stop the form from uploading invalidated data!
    }
});

This does what you asked, and for bonus points it hides and empties later boxes if their predecessors are later changed to be invalid.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM