[英]Jquery get value of text box next to a radio button
我正在创建带有多个单选按钮和文本框的表单。 每个文本框都位于单选按钮旁边,如下所示:
<div class="form-group"> <div class="radio"> <label> <input type="radio" name="correct_answer_id"> Correct </label> </div> <label for="answer" class="col-sm-2 control-label">Answer 2</label> <div class="col-sm-10"> <input type="text" class="form-control" name="answer[]" placeholder="Answer" required> </div> </div>
我正在尝试使用Jquery的next()函数,如下所示:
$('input[type="radio"]').click(function(){ if ($(this).is(':checked')) { console.log($(this).next('input[type="text"]').val()); } });
但是我的日志显示未定义。 我做错了什么?
尝试以下操作:找到radio的父div,然后执行next().next()
以获得输入框div
,然后找到输入框以获取值。
注意 -您无需检查if ($(this).is(':checked'))
因为当您单击单选按钮时,它将始终被选中。
$('input[type="radio"]').click(function(){
var value = $(this).closest('.radio').next().next('.col-sm-10').find('input[type=text]').val();
console.log(value );
});
使用parent()使用以下代码; 看到工作提琴
$('input[type="radio"]').click(function(){
if ($(this).is(':checked'))
{
console.log($(this).parents('div.radio').next().next('div.col-sm-10').find('input[type="text"]').val());
}
});
您应该将要提交的value
放在input
元素的value
属性中。
例如<input type="radio" name="correct_answer_id" value="correct">
您的点击处理程序将变为:
$('input[type="radio"]').click(function(){
if ($(this).is(':checked'))
{
console.log($(this).val());
}
});
如果您不想将某些值放在value属性中,那么最好还是在input元素中引用该值,而不要依赖于特定的文档布局。
尝试这个
$('input[type="radio"]').click(function(){
if ($(this).is(':checked'))
{
console.log($(this).parent().parent().siblings().find('input[type="text"]').val());
}
});
如果您可以稍微更改html,这是另一种方法http://jsfiddle.net/xa9cjLd9/1/
<div class="form-group">
<div class="radio">
<label data-for='answer[]'>
<input type="radio" name="correct_answer_id" />Correct</label>
</div>
<label for="answer" class="col-sm-2 control-label">Answer 2</label>
<div class="col-sm-10">
<input type="text" class="form-control" name="answer[]" placeholder="Answer" required />
</div>
</div>
$('input[type="radio"]').click(function () {
if ($(this).is(':checked')) {
var data = $(this).closest('label').attr('data-for');
console.log($('input[name=' + '"' + data + '"' + ']').val());
}
});
只需为label定义一个data属性,其中包含相关输入的名称。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.