首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >验证div中的文本框

验证div中的文本框
EN

Stack Overflow用户
提问于 2014-02-04 01:46:27
回答 2查看 721关注 0票数 0

我在Div中有5个textbox,div和textbox是使用jquery动态创建的,如果textbox有值或空,则需要验证textbox,如果div中的一个textbox为null,则错误消息将在span中显示,SPAN标记也位于div中。文本框在为空时也会变红,该部分可以工作,但是消息错误有问题。有什么想法吗?

这是HTML

代码语言:javascript
运行
复制
 <div id="QuestionTBDiv1" >
    <label>Question</label><br/>
    <input type="text" name="quiztxtBox[]" size="57" id="quiztxtBox[]" placeholder="Question #1"><br/>
    <label>Answer</label><br/>
    <input type="text" name="quiztxtBox[]" size="24" id="answer[]" placeholder="Choice A">&nbsp;<input type="radio" class = "choiceA" name="correct_answer1" value="A">&nbsp;<input type="text" name="quiztxtBox[]" size="24" id="answer[]" placeholder="Choice B">&nbsp;<input type="radio" class = "choiceB" name="correct_answer1" value="B"><br/><input type="text" name="quiztxtBox[]" size="24" id="answer[]" placeholder="Choice C">&nbsp;<input type="radio" class = "choiceC" name="correct_answer1" value="C">&nbsp;<input type="text" name="quiztxtBox[]" size="24" id="answer[]" placeholder="Choice D">&nbsp;<input type="radio" class = "choiceD" name="correct_answer1" value="D"><br><span name="errMchoice" class="errorMsg"></span>
        </div>  

这是JQUERY

代码语言:javascript
运行
复制
 $("[name='quiztxtBox[]']").each(function(){
          if ($(this).empty()) {

            $(this).css({"background-color":"#f6d9d4"});
            $( "div span:last-child" ).html("This is error message.");
          }
        });
EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2014-02-04 01:49:18

.empty()方法移除所选元素的子元素(ChildNodes),它不检查value属性的长度。由于它返回的是一个jQuery对象而不是一个布尔值,在JavaScript中,一个对象是一个真实的值,您的条件总是true,所以您应该检查该值的长度。

还请注意,$( "div span:last-child" )选择文档中的所有div span:last-child元素。可以使用.siblings()方法选择目标元素。

代码语言:javascript
运行
复制
if ( !this.value.length )
   // selecting the sibling `span` for showing the message 
   $(this).css(...).siblings('span.errorMsg').text('Read the docs!');
票数 0
EN

Stack Overflow用户

发布于 2014-02-04 01:59:43

$( "div :末后子“).html(”这是错误消息。“);

我想这应该是

$( "div span" ).text("This is error message.");

$( "div:last-child" ).text("This is error message.");

因为span是div的最后一个子元素,也是div旁边唯一的span元素。而且,.text,因为您设置的值不是HTML,而是文本内容。希望这能有所帮助!

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/21541511

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档