问题
I want to get the id value of the content below?
<form id="mainForm" name="mainForm">
<input type="radio" id="4" name="rads" value="1" checked>
<input type="radio" id="3" name="rads" value="2" />
<input type="radio" id="2" name="rads" value="3" />
<input type="radio" id="1" name="rads" value="4" />
</form>
<span id="result"></span>
<span id="test"></span>
<script>
document.mainForm.onclick = function(){
var radVal = document.mainForm.rads.value;
var idVal = document.getElementsById('id');
result.innerHTML = 'You selected: '+radVal;
test.innerHTML = 'You id: '+idVal;
}
</script>
You selected value: 1 You selected id: 4
回答1:
You should do
document.mainForm.onclick = function(){
var radVal = document.mainForm.rads.value;
var idVal = document.querySelector('[name="rads"]:checked').id;
result.innerHTML = 'You selected: '+radVal;
test.innerHTML = 'You id: '+idVal;
}
You need to select the checked element using document.querySelector('[name="rads"]:checked')
then get the id using .id
回答2:
With Jquery you can do as follow:
var selectedOption = $(':radio[name="rads"]:checked');
var id = $(selectedOption).attr('id');
var value = $(selectedOption).attr('value');
See the jsFiddle: http://jsfiddle.net/od5fot5m/
回答3:
using JQuery, this should get the value of the id for the checked input $('input:checked').attr('id')
回答4:
A quick jQuery example.
$(function(){ // when DOM is loaded
$('input[name="rads"]').on('click', function(){ // attaching a click event handler to the input elements with the name "rads"
if( $(this).is(':checked') ) // If the user clicked radio, is in checked state
{
$('#result').text( 'You selected: ' + $(this).val() ); // display its value
$('#test').text( 'You id: ' + $(this).attr('id') ); // display its ID attribute's name
}
});
});
Hope it will give you some ideas.
回答5:
var inputs = document.getElementsByTagName('input');
var result = document.getElementById('result');
var test = document.getElementById('test');
for(i=0; i<inputs.length; i++) {
inputs[i].addEventListener("click", function(){
result.innerHTML = 'You selected: '+ this.value;
test.innerHTML = 'You id: '+ this.id;
});
}
That should work without jQuery.
回答6:
Thank you everyone :) There is a problem, Why not print the data on the screen, although it is selected? " checked "
<input type="radio" id="4" name="rads" value="1" checked>
Coming option is selected but cannot write on the screen :(
来源:https://stackoverflow.com/questions/33782404/taking-the-id-value