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

Asked

Viewed 376 times

2

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

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 ifs.

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 it doesn’t work. There would be a sure way to write (concatenate) that line or it’s not possible?

  • I couldn’t use $('a[href="#tab_0'+indice_da_aba+'"]')? What I think you’re missing is the closes and opens parenthesis to concatenate the variable.

2 answers

6


Yes, using the concatenation operator (+).

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

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

Can also do in a more modern way using strings template:

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

Note that this last 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}"]`);

4

You just forgot the aspas simples before and after the +

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

  • I withdraw my negative. Now it is explained :P.

  • 2

    @Gustavocinque Sorry, I had posted before explaining rs, ai editei. Thanks :D

  • Before and after the +.

  • @DVD Exactly, I edited the reply, thank you!

  • @Rafael Augusto good afternoon :). After LINQ posted the answer and I saw that I had forgotten the simple quote I felt like a pastel with nothing inside... :). Thank you for your attention. I marked the LINQ response as accepted because the other way he showed did not know :). Hugs and thanks for your attention :)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.