简体   繁体   中英

How to include a variable in a jQuery selector?

In my JavaScript, I have a variable called counter . And I want to append it to a select tag's ID that I dynamically created using my script like-

// Creating a <div>
var random_div = $(document.createElement('div'))
                 .attr("class", "col-md-7");

counter = 5;

random_div.after().html('<select multiple class="js-example-basic-multiple" name="tal' + counter + '" id="tal' + counter + '" > </select>');

random_div.appendTo(main_div);

Now, I'm trying to resolve width of this newly created select tag, but it doesn't work-

$("#tal" + counter).select2({width: 'resolve'});

I even tried it with another variable, but that doesn't work either-

var testing = '#tal' + counter;
$(testing).select2({width: 'resolve'});

Now, if I hard-code this to say $("#tal5").select2({width: 'resolve'}); , it works.

This is really elementary, but I can't seem to figure out a solution.

Do not look up the element, generate the element with jQuery and use the reference

const select = $('<select ...></select'); // make the select
yourElem.append(select) // add it
select.select2({width: 'resolve'}); // fire the select2

There are some js errors because of miss escaping of single quotes and double quotes

  var random_div = $(document.createElement('div')) .attr("class", "col-md-7"); counter = 5; random_div.after().html('<select multiple class="js-example-basic-multiple" name="tal'+counter+'" id="tal'+counter+'" > </select>'); console.log($(random_div).find('#tal'+counter)[0]) 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> 

try this, now its working

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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