Search code examples
javascriptjqueryappendchecked

How add attribute to radio element on new items?


The code can add attribute checked="checked" on first item already loaded from HTML markup. But, when I added a new "item" radio element, the code cannot include the attribute checked="checked". Why this happens?

I tested using the browser console (F12) to see if attribute would be included or not on respective radio input clicked, but no success so far.

If I not add checked="checked" my value is not stored on sql table. But if I add checked="checked" manually, editing on my browser console, my value is updated with success on sql table.

How can I fix this situation?

jsfiddle

<div id="p_scents">
<p>
<span class="custom_radio">
<input type="radio" id="featured-1" name="s_radio" value="1"> <label for="featured-1">item 1</label>
</span>
</p>    
</div>
<span id="add" class="btn btn-sm btn-primary">add</span>
<span id="remove" class="btn btn-sm btn-pub">remove</span>

var i = 1 ;
var scntDiv = $('#p_scents');
function add_track() {
  if(i < 30){       
  i++;  
  $('<p><span class="custom_radio"><input type="radio" id="featured-'+ i +'" name="s_radio" value="'+ i +'"> <label for="featured-'+ i +'">item '+ i +'</label></span></p>').appendTo(scntDiv);  
  }
}

function remove_track() {
  if(i > 1){            
  var select = document.getElementById('p_scents');
  select.removeChild(select.lastChild); 
  i--;
  }
}

document.getElementById('add').addEventListener('click', add_track, false);
document.getElementById('remove').addEventListener('click', remove_track, false);

$("[name='s_radio']").on("click", function() {
    $("[name='s_radio']").attr("checked", false);
    $(this).attr("checked", true);
});

Solution

  • This should solve the problem

    $(document).on('click',"[name='s_radio']",function (e) {
        $("[name='s_radio']").attr("checked", false);
        $(this).attr("checked", true);
    })