2

I have a UL in my code

<ul>
  <li><input type="radio" name="color" id="0" value="0"/>RED</li>
  <li><input type="radio" name="color" id="1" value="1"/>GREEN</li>
  <li><input type="radio" name="color" id="2" value="2"/>BLUE</li>
</ul>

IS there anyway to access these elements using the id's of these radio buttons directly or is it a compulsion to use JQUERY...

5 Answers 5

1

Yes, there is, of course.

Use

document.getElementById("ElementIdToSelect");

to select elements by their id's.

Sign up to request clarification or add additional context in comments.

Comments

0
for(var i = 0; i < 3; i++){
    var radio = document.getElementById(i + '');
    // use radio
}

I suggest using meaningful ids

EDIT: if you want to get selected value:

var radios = document.getElementsByName('color');
var selectedValue;
for(var i = 0; i < radios.length; i++){
    if(radios[i].selected){
        selectedValue = radios[i].value;
        break;
    }
}

Comments

0

You mean document.getElementById("0")? This should work as you required. It's javascript standard

Comments

0

With the help of plain javascript you can access any selector by applying its proper ID. Jquery is the nothing but the enhanced version of Js.

Using Javascript :-

document.getElementById("0")  // wil point to first radio button

document.getElementById("1")  // wil point to second radio button

Using Jquery :-

$(document).ready(function() {
// Handler for .ready() called.
$('#0').YOUREVENT(function(){
  });
});

Ultimately they perform the same operation in the end.

Thanks...

Comments

0

Yes:

document.getElementById('Your ID')

You have to remind yourself that jQuery is just plain javascript so everything made in jQuery can be made in native javascript. Don't overuse jQuery for simple tasks

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.