2010-05-20 93 views
8

嗨,我有以下的html:的jQuery寻找元素旁边另一

<p> 
    <input type="text" name="field1"/> <input type="hidden" name="fieldh1"/> 
    <button type="button" class="sendInfo">Send</button> 
</p> 
<p> 
    <input type="text" name="field2" /> <input type="hidden" name="fieldh2"/> 
    <button type="button" class="sendInfo">Send</button> 
</p> 

我要的是,当用户点击该按钮,我需要使用Ajax场字段的内容发送。

这就是我想要做的没有成功。

$(function() { 
     $('button.sendInfo').live('click', function() { 
      var id = $(this).parent().next('[type=text]').val(); 
      alert(id); 
     }); 
    }); 

我打算设置从AJAX调用到正常的文本框收到什么文本框的用户类型的隐藏字段和值。但问题是,我甚至无法获得与用户点击的按钮位于同一行的文本框的值。 任何人都可以帮助我吗? 非常感谢。

回答

18

尝试:

$(this).siblings('input:text').val(); 

或更改nextfind

$(this).parent().find('[type=text]').val(); 

next只搜索立即以下同级

+1

是的! This works fine: $(this).parent()。find('[type = text]')。val(); 感谢您的帮助 – thiagoleite 2010-05-20 19:44:04

+0

找到只有在两者之间没有任何作品.. – stuartdotnet 2013-08-23 04:51:51

0

你可以使用ID选择你的文本框?

$(function() { 
    $('button.sendInfo').live('click', function() { 
     //what about this: 
     var id = $('#textBoxID').val(); 
     alert(id); 
     //or this 
     var id2 = $('+ input', this).val(); 
     alert(id2); 
    }); 
}); 
+1

不,因为我有很多文本框,我不想为它们单独设置处理程序。我需要确定在按下按钮 – thiagoleite 2010-05-20 19:41:52

+0

好之前的文本框,所以,也许,看起来像第二个选项应该工作... – Rbacarin 2010-05-20 20:10:51

1

你的问题是,“下一个()”将父的下一个兄弟 - 和家长是<p>标签,所以兄弟姐妹,如果存在的话,是以下<p>标签。

你想要$(this).parent().children('[type=text]').val()$(this).parent().find('[type=text]')