[英]How to get the NAME and value of a radio button when DYNAMICALLY selected - in jQuery?
[英]How to get the value of a selected radio button when the id for them is dynamically generated?
我的HTML如下所示:
<div id="associatedAPListTable" style="float:left"><Associated (Destination)>
<table border="0" cellspacing="0" cellpadding="0" class="listContainer" align="center" >
<thead>
<tr>
<th class="tableheader" align="left" width="170">MAC address</th>
<th class="tableheader" align="left" width="170">LradName</th>
</tr>
</thead>
<tbody id="associated_tablebody">
</tbody>
</table>
</div>
我的JavaScript如下所示:
function getAssociatedList(){
var associatedAPListArray=[];
var xhrArgs = {
url:"abc/sample/resource",
preventCache: true,
contentType: "application/json"
};
var deferred = dojo.xhrGet(xhrArgs);
deferred.addCallback(function(response){
var associatedApListObj = dojo.fromJson(response);
var firstJsonObject;
var row = '';
for (i=0; i <= dojo.fromJson(associatedApListObj.items).length-1; i++){
firstJsonObject = dojo.fromJson(associatedApListObj.items)[i];
var MacAddress = firstJsonObject.MacAddress;
var LradName=firstJsonObject.LradName;
var style_td='<td align="left" width="170">';
row+='<tr>'+style_td+'<input type="radio"'+'id="associated_'+i+'" name="associatedAp"/ >'+MacAddress+'</td>'+style_td+LradName+'</td></tr>';
}
document.getElementById('associated_tablebody').innerHTML = row;
});
}
因此,既然我已经创建并显示了这些单选按钮,则需要获取所选单选按钮的值。 有人可以告诉我如何使用Javascript而不是jQuery吗?
这将为您提供选中的单选按钮的id
:
document.querySelector('input[type=radio]:checked').getAttribute('id');
如果要监听用户事件,则需要在创建元素后向元素添加事件监听器。
function handleChange(e) {
// is it checked?
console.log(this.checked)
// what's the value?
console.log(this.value)
}
var inputs = document.getElementById('associated_tablebody').querySelectorAll('input')
inputs.forEach(function(el) {
el.addEventListener('change', handleChange)
})
更新资料
我以为您想听每个输入上的事件。 我的错。
如果您只是想查找将html添加到页面后选中的单个单选按钮,则只需将结果过滤到所选元素并存储(或记录)它的值即可:
var inputs = document.getElementById('associated_tablebody').querySelectorAll('input')
var selected = [].slice.call(inputs).filter(function(el) {
return el.checked
}).pop()
console.log(selected.value)
小提琴: https : //jsfiddle.net/jw7e0aL4/8/
首先,我猜您要选择的单选按钮的Mac地址吗?
根据您的代码尚不清楚,因为您说
我需要获取选中的单选按钮的值
但是,您正在生成此输入标签
<input type="radio"'+'id="associated_'+i+'" name="associatedAp"/ >
没有设置任何值,否则可能看起来像这样:
<input type="radio"'+'id="associated_'+i+'" name="associatedAp" value="'+MacAddress+'"/ >
为了清楚起见,整个代码行如下所示:
row+='<tr>'+style_td+'<input type="radio"'+'id="associated_'+i+'" name="associatedAp" value="'+MacAddress+'" />'+MacAddress+'</td>'+style_td+LradName+'</td></tr>';
现在,您需要能够选择它并获取值:
var selection = document.querySelector('input:checked').value;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.