如果使用jquery选择了无线电,则填充输入

时间:2014-10-16 13:39:44

标签: javascript jquery

我有一个输入和两个单选按钮。

输入接受一个人居住在住所的时间段内的数字。

单选按钮是几个月和几个月。年份。

我想使用第一个输入值(居住长度的数值)填写第二个输入,并根据所选的收音机输入数月或数年的值。

我已经把它吐出来了,但它吐出了两个单选按钮的值,因为我没有要检查的if语句。我已经在我的表单中有jquery并且它有效。我只需要将我的表格中的这一小部分用于工作。

我的问题是,如何设置条件语句以检查检查哪个无线电?

HTML

<input type="number" value="" required maxlength="5" class="form-control" name="homeLength" id="homeLength">
<input type="radio" id="years" value="Years" name="length" required> Years
<input type="radio" id="months" value="Months" name="length"> Months

的jQuery

$('#months').click(function () {
  if ($(this).attr("checked") == "checked") {
    $('#homeLength, #months').bind('keypress blur', function () {
      $('#homeTime').val($('#homeLength').val() + ' ' + ' ' + $('#months').val() + ' ' + ' ');
    });
  }
});

$('#years').click(function () {
  if ($(this).attr("checked") == "checked") {
    $('#homeLength, #years').bind('keypress blur', function () {
      $('#homeTime').val($('#homeLength').val() + ' ' + ' ' + $('#years').val() + ' ');
    });
  }
});

3 个答案:

答案 0 :(得分:2)

您需要仅检查已检查的无线电的值,并在keyup / blur上执行此操作并单击任何无线电

$(function() {
  $('#homeLength').on('keyup, blur', function() {
    var lgt = $("input:radio[name=length]:checked").val();
    $('#homeTime').val($(this).val() + ' '+lgt);
  });
  $("input:radio[name=length]").on("click",function() { 
    $('#homeLength').blur(); // trigger the blur event of the field to update
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input type="number" value="" required maxlength="5" class="form-control" name="homeLength" id="homeLength">
<input type="radio" id="years" value="Years" name="length" required> Years
<input type="radio" id="months" value="Months" name="length"> Months
<hr/>
<input type="text" value="" class="form-control" name="homeTime" id="homeTime">

答案 1 :(得分:1)

此类检查最有用的条件声明是:

if ($(this).is(':checked'))

因此您可以看到响应是布尔值。

答案 2 :(得分:0)

用此

替换您的javascript代码
  $('#months').click(function() {
      console.log($(this).prop('id'));
      $('#homeLength, #months').bind('keypress blur', function() {
        $('#homeTime').val($('#homeLength').val() + ' ' + ' '+$('#months').val()+ ' ' + ' ');
      }); 
  });
  $('#years').click(function() {
      console.log($(this).prop('id'));
      $('#homeLength, #years').bind('keypress blur', function() {
        $('#homeTime').val($('#homeLength').val() + ' ' + ' ' + $('#years').val()+ ' ');
      }); 
  });

每当用户选择任何单选按钮时,您都可以通过

获取其ID
$(this).prop('id');

其值

$(this).prop('value');