如何找到它们在同一级别上的输入元素的最近标签 [英] How to find the closest label to an input element where they are on the same level

查看:118
本文介绍了如何找到它们在同一级别上的输入元素的最近标签的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我动态地在我的表单中添加 input 元素。每个逻辑代码块如下所示:

 < input ../> 
< input .. />
< label>< / label>

以及标签的想法是显示错误信息,在这种情况下,如果两个输入之一是空的,我想显示消息,这两个输入都是必需的。



这是一个JSFiddle 示例。通过这一步一步走,我认为我成功地获得每个输入并执行检查,但然后我无法获得标签 code>所以我可以添加适当的文本。在输入后得到最接近的标签是很重要的,因为我想为这两个输入使用一个标签。

由于标签输入的兄弟,因此您需要使用 .next() 而不是 $ b

使用 / em>

  $(v).next('label')。text(Both fields are required!); 

而不是

  $(v).find('label')。text(Both fields are required!); 

DEMO

I'm dynamycally adding input elements to my form. Each logical code block looks like this:

<input .. />
<input .. />
<label></label>

and the idea of the label is to display error message, in this case, if on of the two inputs is empty I want to show message the both inputs are required.

Here is a JSFiddle example. walking through this step by step I think that I successfully get each input and perform the check but then I'm not able to get the label so I can add the appropriate text. And it's important that I get the closest label after the input, because I want to use one label for both inputs.

解决方案

As label is a sibling of input, You need to use .next() instead of .find()

Use

$(v).next('label').text("Both fields are required!"); 

instead of

$(v).find('label').text("Both fields are required!"); 

DEMO

这篇关于如何找到它们在同一级别上的输入元素的最近标签的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆