Javascript 遍历文本框

Javascript 遍历文本框,javascript,Javascript,我有文本框,其中这些框的id为1到20。这些框是在PHP for循环中创建的。 如果这些文本框为空,如何使用javascript进行检查。并在每个框上抛出一个错误 foreach(i = 0, i<20, i++) { <input type = "Text" id="q_i"> } foreach(i=0,i使用jQuery $('input[type=text]').each(function(){if ($(this).val() == '') alert("Your

我有文本框,其中这些框的id为1到20。这些框是在PHP for循环中创建的。 如果这些文本框为空,如何使用javascript进行检查。并在每个框上抛出一个错误

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

$('input[type=text]').each(function(){if ($(this).val() == '') alert("Your Message Here");});  
或者,如果您不想处理其他输入:

$('[id^="q_"]').each(function(){if ($(this).val() == '') alert("Your Message Here");});
没有jQuery(使用jQuery会更容易):

foreach(i=0,i
在for循环中,应该大致这样做

(尽管加入你的项目可能是一个更好的计划)

然后你可以迭代一个类

foreach(i = 0, i<20, i++)
{
<input type = "Text" id="q_i" class="q">
}
foreach(i=0,i是一种基本的表单验证,您可能正在寻找它
它使用一条不可见的错误消息,当您按下按钮后离开一个空字段时会显示该消息。它不接受空格。您可以多次验证它,并且它的行为符合预期
以下是jquery部分:

$(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部分:

<style>.hidden{display:none;}
       .visible{display:block;}
</style>
<span id="q_1" class="hidden">Missing text</span>
<input type = "Text" id="q_1">
.hidden{display:none;}
.visible{显示:块;}
缺失文本

虽然不是很漂亮,但它确实起到了作用

如果你在每个文本框上都添加一个class属性,那么对于所有要迭代的文本框来说都是相同的,这会容易得多。我已经更新了我的回复,看看,在添加多条消息之前,不是说选择器缺少一个“.”这是伪代码吗?你认为
length
属性代表什么?谢谢伙计…我把你的和titus的代码合在一起:$(这个)。在(“缺少文本”)之前,它就像一个符咒。谢谢大家。
$("q").each(function(index,object){
  if(object.value().length <= 0) alert('empty!');
});
$(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");
                        }
                }); 
                });
 });
<style>.hidden{display:none;}
       .visible{display:block;}
</style>
<span id="q_1" class="hidden">Missing text</span>
<input type = "Text" id="q_1">