Using variable in place of class or id name in jQuery

Last Reply 2 months ago By pandeyism

Posted 2 months ago

how can i use variable in place of class or id name in jquery

var ddlclass = $("#ddlclass" + TrainNumber+"");
for (var j = 0; j < train.length; j++) {
var cls = $("<option value='" + j + "'>" + train[j].ClassCode + "</option>");
    $(ddclass).append(cls); //trying this but unable to append please help
}

 

You are viewing reply posted by: pandeyism 2 months ago.
Posted 2 months ago

Hi Sadakat,

Refer below sample.

HTML

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title></title>
    <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
    <script type="text/javascript">
        $(function () {
            var train = [{ ClassCode: "Train 1" }, { ClassCode: "Train 2"}];
            var ddlclass = $("#ddlclass");
            for (var j = 0; j < train.length; j++) {
                var cls = $("<option value='" + j + "'>" + train[j].ClassCode + "</option>");
                $(ddlclass).append(cls);
            }
        });
    </script>
</head>
<body>
    <select id="ddlclass">
    </select>
</body>
</html>

Demo