jquery - 使用数组中的动态数据动态选择id

时间:2017-10-09 09:06:09

标签: php jquery

我有一个如下所示的html选择标记,并使用jquery动态选择id,如下面的代码var trainingnameCtrlVal = $("#x" + i + "_TRAINING_NAME[]").val();所示。如果我使用var trainingnameCtrlVal = $("#x" + i + "_TRAINING_NAME").val();,我将收到错误,这将不会显示任何结果。

<select data-table="assessment_training" 
data-field="x_TRAINING_NAME"
data-value-separator=", " id="x3_TRAINING_NAME[]" 
name="x3_TRAINING_NAME[]" multiple="multiple" 
class="form-control">
<option value="62">Induction Training</option></select>

我使用下面的代码执行但我收到错误

var z = $('select[data-field="x_TRAINING_CATEGORY"]').length-1;
    var training_name = [];
    for (var i = 1; i <= z; i++) {  
        var trainingnameCtrlVal = $("#x" + i + "_TRAINING_NAME[]").val();
        training_name.push(trainingnameCtrlVal);
        alert(trainingnameCtrlVal);
    }

 Error: Syntax error, unrecognized expression: #x1_TRAINING_NAME[]

1 个答案:

答案 0 :(得分:2)

你可以这样使用

$("[id='"+'x'+i+'_TRAINING_NAME[]'+"']")

var a = 'x'+i+'_TRAINING_NAME[]'
$("[id='"+a+"']")

检查下面的代码段

$("select").on("click", function(){
i = 3
var a = 'x'+i+'_TRAINING_NAME[]'
alert($("[id='"+a+"']").val())
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>


<select data-table="assessment_training" 
data-field="x_TRAINING_NAME"
data-value-separator=", " id="x3_TRAINING_NAME[]" 
name="x3_TRAINING_NAME[]" multiple="multiple" 
class="form-control">
<option value="62">Induction Training</option></select>