taking the id value

taking the id value

本文关键字:value id the taking      更新时间:2023-09-26

我想获得下面内容的id值吗?

<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>

您选择的值:1您选择了id:4

您应该执行

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;
    }

您需要使用document.querySelector('[name="rads"]:checked')选择选中的元素,然后使用.id 获取id

使用Jquery,您可以执行以下操作:

var selectedOption = $(':radio[name="rads"]:checked');
var id = $(selectedOption).attr('id');
var value = $(selectedOption).attr('value');

请参阅jsFiddle:http://jsfiddle.net/od5fot5m/

使用JQuery,这应该会获得检查输入$('input:checked').attr('id') 的id值

一个快速jQuery示例。

$(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
        }
    });
});

希望它能给你一些想法。

    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;
    });
  }    

在没有jQuery的情况下应该可以工作。

谢谢大家:)有一个问题,为什么不在屏幕上打印数据,尽管它被选中了?"已检查"

<input type="radio" id="4" name="rads" value="1" checked>

选择了Coming选项,但无法在屏幕上写入:(