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">
}
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");});
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!');
}
}
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!');
});
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
精彩评论