Set an ID for all radio buttons When the pages are loaded

I have a lot of radio button groups. I want to set all radio button ids as parent div id + itselves. As the radio buttons come from external HTML and in some cases I have to use the same buttons multiple times on the same page. My example code is below and when you select a radio button its id and form id are set correctly. Is there a way to do this automatically on page load and not based on selection?

<div id="x1" class="section">
  <form id="" class="myFormClass">
    <input id="" class="myRadio" name="someName-1" value="one">one
    <input id="" class="myRadio" name="someName-1" value="two">two
  </form>
</div>
<div id="x2" class="section">
  <form id="" class="myFormClass">
    <input id="" class="myRadio" name="someName-2" value="three">three
    <input id="" class="myRadio" name="someName-2" value="four">four
  </form>
</div>

<script>
  $(document).on('change', "input:radio", function(){
    var parentId = $(this).closest(".section").attr("id");
    var radioValue = this.value;
    var radioName = this.name;
    $(this).parent("form").attr("id", parentId + radioName + "Form") 
    $(this).attr("id", parentId + "-" + radioValue);
  })
</script>

      

And let me ask one more question. When I try to get some elements with a common attribute of them, I can only get the first element.

var iNeedYou = $("input:radio[name='someName-1']").val();

      

returns "one". Is there a way to get them all?

Thank.

+3


source to share


1 answer


Use $( document ).ready()

( $(function()

for brevity) to run the code on page load. Set your inputs to a value type='radio'

if you want switches.

For your additional question: you can use $('yourSelector').each(function(){

to select multiple items. See example.

Also see specifying the ids you provide in the example (parent div id + own value):



$(function() {
    $('input[type=radio]').each(function(){
        var parentId = $(this).closest(".section").attr("id");
        $(this).attr("id", parentId + $(this).val());        
    });
});

      

Fiddle: http://jsfiddle.net/ddan/4nxhbw8s/1/

+2


source







All Articles