简体   繁体   中英

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

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

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.

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);
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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