获取所选单选按钮的相应文本字段值

时间:2018-08-09 10:20:03

标签: html5 twitter-bootstrap radio-button bootstrap-4 textfield

我正在使用引导程序从选定的单选按钮的文本字段中获取相应的文本值。

输出将如下所示:

https://imgur.com/Z33pkKH

function selectedRadioButton()
{ 
  console.log($('input[name=radiobutton]:checked', '#myForm').val());
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="form-group" id="myForm">
    <div class="input-group col-sm-3">
            <div class="input-group-prepend">
              <div class="input-group-text">
              <input type="radio" name="radiobutton" aria-label="Radio button for following text input">
              </div>
            </div>
            <input type="text" name="txtbox" class="form-control" aria-label="Text input with radio button">
    </div>
    </br>
    <div class="input-group col-sm-3">
            <div class="input-group-prepend">
              <div class="input-group-text">
              <input type="radio" name="radiobutton" aria-label="Radio button for following text input">
              </div>
            </div>
            <input type="text" name="txtbox" class="form-control" aria-label="Text input with radio button">
    </div>

</div>

<button type="button" class="btn btn-primary" onclick="selectedRadioButton();">Download</button>

如何将单选按钮与文本字段值相连?

1 个答案:

答案 0 :(得分:1)

使用以下代码片段,使用jquery获取element的值。

function selectedRadioButton() {
  console.log($($('input[name=radiobutton]:checked').closest('.input-group').find("input[type=text]")).val());
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.2/css/bootstrap.min.css" rel="stylesheet" />

<div class="form-group" id="myForm">
  <div class="input-group col-sm-3">
    <div class="input-group-prepend">
      <div class="input-group-text">
        <input type="radio" name="radiobutton" aria-label="Radio button for following text input">
      </div>
    </div>
    <input type="text" name="txtbox" class="form-control" aria-label="Text input with radio button">
  </div>
  </br>
  <div class="input-group col-sm-3">
    <div class="input-group-prepend">
      <div class="input-group-text">
        <input type="radio" name="radiobutton" aria-label="Radio button for following text input">
      </div>
    </div>
    <input type="text" name="txtbox" class="form-control" aria-label="Text input with radio button">
  </div>

</div>

<button type="button" class="btn btn-primary" onclick="selectedRadioButton();">Download</button>