我有输入自动名称的问题,我会尝试解释我需要做什么。我有一个id,我从外部函数得到它。我需要使用这个数字id来创建这样的另一个函数。
var id = 10; // this is the id (from external function)
var value = "n"+bar.toString(); // (I try to cast the id as string)
$("input[name="+value+"]").on('change', function() { // use the cast value to name my input.
alert($("input[name="+value+"]:checked", "#myForm").val());
});
当我尝试这样做时,我得到undefined
,但当我更改var id ="10"
的ID时,我得到了正确的答案,但我有一个数字输入。请帮我弄清楚如何解决这个问题。
答案 0 :(得分:2)
使用此代码不需要id.toString()
var id = getId(); // this is the id (from externel function)
var value = "n" + id;
$("input[name="+value+"]").on('change', function() {
alert($("input[name="+value+"]:checked").val()); //change this selector accordingly
});
function getId() {
return 10;
}
答案 1 :(得分:2)
你想要这样的东西吗?这是基于您在表单中有复选框的假设!
var ids = [10, 20, 30, 11, 12];
$.each(ids, function(index, val) {
var id = val;
var value = "n" + id; // `.toString` is not required!
$("#myForm").find("input[name='"+value+"']").on('change', function() {
if ($(this).is(":checked")) {
alert( $(this).val() );
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="myForm">
<input type="checkbox" name="n10" value="10" />
<input type="checkbox" name="n11" value="11" />
<input type="checkbox" name="n12" value="12" />
</form>
答案 2 :(得分:0)
尝试以下代码:
var id = 10; // this is the id (from externel function)
var value = id.toString(); // (i try to cast the id as string)
console.log(value);
$("input[name="+value+"]").on('change', function() { // use the casted value to name my input.
alert($("input[name="+value+"]:checked", "#myForm").val());
});