簡體   English   中英

jQuery獲取單選按鈕旁邊的文本框的值

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM