![](/img/trans.png)
[英]How to pass an array's element as an argument to a function in javascript?
[英]Pass Array HTML Element(s) in JavaScript
我有一系列的复选框,如下所示,
<input type="checkbox" value="1" id="a_r_id[1]" name="a_r_id[1]">
<input type="checkbox" value="1" id="a_r_id[2]" name="a_r_id[2]">
<input type="checkbox" value="1" id="a_r_id[3]" name="a_r_id[3]">
<input type="checkbox" value="1" id="a_r_id[4]" name="a_r_id[4]">
在我的页面中...,我只想通过JavaScript(jQuery AJAX)提交选中的一个...我该怎么做?
编辑:
实际上,我想在选中的复选框上获取所有数组键,以便可以通过Ajax发布它。 像“ 1,4”这样的字符串。
var keys = [],
keystring;
$('input[name^="a_r_id"]:checked').each(function () {
keys.push($(this).attr('name').replace(/a_r_id\[(\d+)\]/, '$1'));
});
keystring = keys.join();
当然,有更好的方法可以执行此操作,但这可以在构架时回答您的问题。
最后,我在上面找到了我的问题的答案。 我会在这里写下来。
问题:如何从数组HTML元素中获取“关键字”? (就我而言,我只想选中复选框)
我的答案代码是这样的:
//first, i get every checked checkbox using jQuery selector,
//as mentioned by DerekHenderson.
var list_agent = $('input[name^="a_r_id"]:checked');
var l_c_agent = new Array();
//then, i create a loop to loop each object returned.
for(var i=0;i<list_agent.length;i++){
//after that, i'm using Regular Expression ( match() ) on every returned object id and throw it into some array.
l_c_agent[i] = list_agent[i].id.match(/[0-9]+/);
}
//finally, i join the array using javascript join() method so that i can pass it using jQuery AJAX as a string to my controller and process it.
var clean_agent_list = l_c_agent.join();
var add_url = 'test.php';
$.ajax({
url: add_url,
type: "GET",
data : { 'list_agent' : clean_agent_list },
success: function(data_return) {
//alert(data_return);
}
});
输出将是这样的(如果使用上面的示例问题,并且我们仅检查ID为1,3和4的元素)
1,3,4
如果有人有更好的代码,请在此处编写,以便我们讨论解决我的问题的更好方法。
您想要的方法似乎有些倒退; 浏览器将仅提交已选中的复选框,但是这里是:
var re = /\[(\d+)\]$/,
numbers = [];
$('input[name^="a_r_id\\["]:checked').each(function() {
numbers.push(+this.name.match(re)[1]);
});
console.log(numbers.join(','));
它选中所有名称以“ a_r_id [”开头的复选框。 然后,使用正则表达式提取方括号之间的数字部分,并将其添加到值列表中。
我想你想做这样的事情
<input type="checkbox" value="1" id="a_r_id_1" name="a_r_id[]">
<input type="checkbox" value="2" id="a_r_id_2" name="a_r_id[]">
<input type="checkbox" value="3" id="a_r_id_3" name="a_r_id[]">
<input type="checkbox" value="4" id="a_r_id_4" name="a_r_id[]">
单选按钮似乎比此处更适用,而不是复选框,请尝试以下操作:
<input type="radio" name="radiogroup" value="1" id="a_r_id[1]" name="a_r_id[1]">
<input type="radio" name="radiogroup" value="2" id="a_r_id[2]" name="a_r_id[2]">
<input type="radio" name="radiogroup" value="3" id="a_r_id[3]" name="a_r_id[3]">
您可以使用以下方法获取所选值
$("input:radio[name=radiogroup]").click(function() {
var value = $(this).val();
//
do something with var
//
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.