Is it possible to concatenate a jQuery selector with a variable?

2

I have the following code inside a javascript function that is inside a .php page:

if (indice_da_aba == -1)
{
   window.alert('não existe ABAS AINDA');
}
else                    
if (indice_da_aba == 0)
{
   $('a[href="#tab_00"]').tab('show');
}
else
if (indice_da_aba == 1)
{
   $('a[href="#tab_01"]').tab('show');
}
else
if (indice_da_aba == 2)
{
   $('a[href="#tab_02"]').tab('show');
}

As you can see, there are many if s.

I wonder if it is possible to write a if as follows:

if (indice_da_aba == -1)
{
   window.alert('não existe ABAS AINDA');
}
else                    
{
   $('a[href="#tab_0+indice_da_aba+"]').tab('show');
}

The way I wrote does not work. Is there a way to write (concatenate) this line or is it not possible?

    
asked by anonymous 30.10.2017 / 20:34

2 answers

6

Yes, using the concatenation operator ( + ).

$('a[href="#tab_0' + indice_da_aba + '"]').tab('show');

But for this, you need to have a value on each side of the operator. In the code shown, you even used + , but forgot to close the quotation marks to "close" the string.

You can also do this in a more modern way, using template strings >:

$('a[href="#tab_0${indice_da_aba}"]').tab('show');

Note that the latter form may not work in some browsers.

See working:

const indice_da_aba = 123;

console.log('a[href="#tab_0' + indice_da_aba + '"]');
console.log('a[href="#tab_0${indice_da_aba}"]');
    
30.10.2017 / 20:37
4

You just forgot aspas simples before and after +

if (indice_da_aba == -1){
   window.alert('não existe ABAS AINDA');
}else{
   $('a[href="#tab_0'+indice_da_aba+'"]').tab('show');
}
    
30.10.2017 / 20:37