简体   繁体   English

jQuery输入的动态名称

[英]dynamic name for an input with jQuery

I have an issue with automatic name for input, I'll try to explain what i need to do. 我在输入自动名称时遇到问题,我将尝试解释我需要做的事情。 i have an id, that I get it from an external function. 我有一个ID,可以从外部函数中获取。 I need to use this numeric id to create another function like that. 我需要使用此数字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()); 
});

When I try to do that I get undefined , but when I change the id like that var id ="10" I get the correct answer, but I have a numeric input. 当我尝试这样做时,我得到undefined ,但是当我像var id ="10"这样更改id时,我得到了正确的答案,但是我有一个数字输入。 Please help me figure out how to solve this problem. 请帮我弄清楚如何解决这个问题。

use this code no need for id.toString() 使用此代码无需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;
}

here is the fiddle https://jsfiddle.net/rrehan/srhjwrz4/ 是小提琴https://jsfiddle.net/rrehan/srhjwrz4/

Did you want something like this? 你想要这样的东西吗? This is based on an assumption that you have checkboxes within a form! 这是基于一个假设,即您在表单中有复选框!

 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> 

Try below code: 试试下面的代码:

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

Demo Link 演示链接

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM