2
votes

I have a unordered list dynamicly created from radio input labels. How to get checked radio button when click the created list item'?

List items created dynamicly from radio values. When clicked one of item

<ul id="listSec">
    <li>Item1 menu </li>
    <li>Item2 menu </li>
    <li>Item3 menu </li>
</ul>

Depended radio form. when clicked Item3 menu, Item3 radio must checked so on.

<form>
    <div id="formForItems">
       <input type="radio" name="items" value="1" checked> Item1 radio <br>
       <input type="radio" name="items" value="2"> Item2 radio  <br>
       <input type="radio" name="items" value="3"> Item3 radio 
    </div>
</form>

Also it will be great if clicked list item get a class as active.

3

3 Answers

2
votes

Use event delegation for dynamically generated li. In click event get the index of clicked li and then check the same indexed radio.

$(document).on('click', '#listSec li', function () {
    var index = $(this).index();
    $('#formForItems input:radio').eq(index).prop('checked', true);
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<ul id="listSec">
    <li>Item1 menu </li>
    <li>Item2 menu </li>
    <li>Item3 menu </li>
</ul>

<form>
    <div id="formForItems">
        <input type="radio" name="items" value="1" checked> Item1 radio <br>
        <input type="radio" name="items" value="2"> Item2 radio  <br>
        <input type="radio" name="items" value="3"> Item3 radio
    </div>
</form>
1
votes

$(document).on('click', "#listSec li", function(e){
  var index = $("#listSec li").removeClass('active').index(this);
  $(this).addClass('active');
  $('#formForItems input[name="items"]').eq(index).prop('checked', true);
})
.active{
  color:red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<ul id="listSec">
    <li>Item1 menu </li>
    <li>Item2 menu </li>
    <li>Item3 menu </li>
</ul>
Depended radio form. when clicked Item3 menu, Item3 radio must checked so on.

<form>
    <div id="formForItems">
       <input type="radio" name="items" value="1" checked> Item1 radio <br>
       <input type="radio" name="items" value="2"> Item2 radio  <br>
       <input type="radio" name="items" value="3"> Item3 radio 
    </div>
</form>
1
votes

I would write something like this:

    $(document).on("click","#listSec > li",function(){
      //remove active class from all the inputs
      $("#formForItems > input").removeClass("active");

      //get index of clicked element
      var index = $("#listSec > li").index(this);

      //check the corresponding radio and add "active" class
      $("#formForItems > input").eq(index).prop("checked",true).addClass("active");
    });

See here