ken
ken

Reputation: 75

iterate through textboxes

I have text boxes where id for these boxes are from 1 to 20. These boxes are created in PHP for loop. How can i check using javascript if these textboxes are empty. and throw an error on each box.

foreach(i = 0, i<20, i++)
{
<input type = "Text" id="q_i">
}

Upvotes: 0

Views: 2043

Answers (4)

titus
titus

Reputation: 5784

Here is a basic form validation that might be what you're looking for It uses an invisible error message that shows up when you leave an empty field after you push the button. It doesn't accept white spaces. You can validate it multiple times and it behaves as expected Here's the jquery part:

$(document).ready(function() {
                $("button").click(function()
                {   $('span[id^=q_]').addClass("hidden");
                    $('input[id^=q_]').each(function()
                    {if ($(this).val().replace(/ /g,'') == '') 
                        {   $("#"+$(this).attr('id')).removeClass("hidden");
                        }
                }); 
                });
 });

html part:

<style>.hidden{display:none;}
       .visible{display:block;}
</style>
<span id="q_1" class="hidden">Missing text</span>
<input type = "Text" id="q_1">

Not very pretty but it does the job

Upvotes: 0

Michael
Michael

Reputation: 4090

Use jQuery?

$('input[type=text]').each(function(){if ($(this).val() == '') alert("Your Message Here");});  

or, if there are other inputs you don't want to process:

$('[id^="q_"]').each(function(){if ($(this).val() == '') alert("Your Message Here");});

Upvotes: 1

Ben Mosher
Ben Mosher

Reputation: 13381

document.getElementsById('q_'+i)[0].value.length > 0

in a for loop ought to roughly do it.

(though dropping jQuery into your project would probably be a better plan)

Then you could iterate over a class. i.e.

foreach(i = 0, i<20, i++)
{
<input type = "Text" id="q_i" class="q">
}

and in your Javascript:

$("q").each(function(index,object){
  if(object.value().length <= 0) alert('empty!');
});

Upvotes: 0

Matt
Matt

Reputation: 1911

Without jQuery (and using jQuery would be easier):

foreach(i = 0, i<20, i++)
{
  if (document.getElementById('q_' + i).length == 0) {
    alert('box ' + i + 'is empty!');
  }
}

Upvotes: 0

Related Questions