简体   繁体   English

使用 jQuery 根据输入文本更改选中/取消选中的单选按钮

[英]change radio button checked/unchecked on the basis of input text using jQuery

I have a custom year list on the basis of that list I am adding the value to the input field, how can I set the value of radio on the basis of input like if I write 2022 in input field 2020 must be checked in the list我有一个基于该列表的自定义年份列表我正在将值添加到输入字段,如何根据输入设置收音机的值,就像我在输入字段中写 2022 必须在列表中选中

var currentDate = new Date();
  var currentYear = currentDate.getFullYear();
  let startYear =  currentYear - 10;
  let endYear =  currentYear + 10;

  for ( let i = startYear; i <= endYear; i++ ) {
    $('#custom-years-list').append(`
      <li class="checkbox-container">
        <input type="radio" id=${i}  name="startYear">
        <label for=${i}>${i}</label>
      </li>
    `)
  }

that's how I am adding the years in a ul and want to select the radio on the basis of input field这就是我在 ul 中添加年份并希望根据输入字段选择收音机的方式

This solution adds an event listener to your input field (you will need to change the second argument accordingly).此解决方案向您的输入字段添加了一个事件侦听器(您需要相应地更改第二个参数)。 Then it simply grabs the input and sets the appropriate checkbox to checked.然后它简单地获取输入并将适当的复选框设置为选中。

Also your IDs can't be a number.此外,您的 ID 不能是数字。

var currentDate = new Date();
  var currentYear = currentDate.getFullYear();
  let startYear =  currentYear - 10;
  let endYear =  currentYear + 10;

  for ( let i = startYear; i <= endYear; i++ ) {
    $('#custom-years-list').append(`
      <li class="checkbox-container">
        <input value="${i}" type="radio" id=year${i}  name="startYear">
        <label for=year${i}>${i}</label>
      </li>
    `)
  }

$(document).on("input",".input",function(){
    input_year = $(this).val();
    $("#year" + input_year).prop("checked",true);
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM