Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

concat two strings in JQuery

Just like the title above: how to concatenate two strings in JQuery?

This is my code so far:

$(document).ready(function(){           
    serviceName = '<?=$_GET['services'] . ".php";?>';
    serviceID='<?= "#" .$_GET['services'];?>';
    serviceClass = '<?=$_GET['services'];?>';

    if (serviceName != "") {
        alert(serviceID);
        $('.main_content').load(serviceName);
        $(serviceID).addClass("it");
    }
});

As you can see in my above code, in variable name serviceID, I am concatenating hashtag and my GET value and I try to put it on ALERT and the result is correct, but when I assign it to .addClass it’s not working.

Any alternatives and solution is much appreciated.

like image 984
Unknownymous Avatar asked Apr 29 '14 09:04

Unknownymous


People also ask

What is concat jquery?

The concat() method joins two or more strings.

How do you add two strings together?

Concatenation is the process of appending one string to the end of another string. You concatenate strings by using the + operator. For string literals and string constants, concatenation occurs at compile time; no run-time concatenation occurs. For string variables, concatenation occurs only at run time.

How do you concatenate strings in JavaScript?

In JavaScript, we can assign strings to a variable and use concatenation to combine the variable to another string. To concatenate a string, you add a plus sign+ between the strings or string variables you want to connect.

How do I concatenate two fields in JavaScript?

concat() function is used to join two or more strings together in JavaScript. Return value: This function returns a new string that is the combination of all the different strings passed to it as the argument.


1 Answers

I guess you meant that the PHP code should be evaluated before arriving to the client, therefore your code syntax is correct, but check out the following looks cleaner and also not polluting the global JavaScript scope (that's what the var ... is for):

var serviceClass = '<?="{$_GET["services"]}";?>';
var serviceName = serviceClass+'.php';
var serviceId = '#'+serviceClass;

but, since your code syntax is correct, you should verify that you actually have an element with serviceId as the id when your are executing it

if (($(serviceId)||[]).length) {
    alert('your element with the id:'+serviceClass+' exists');
}
else {
    alert('your element with the id:'+serviceClass+' doesn\'t exists');
}
like image 120
Marcelo Waisman Avatar answered Sep 20 '22 23:09

Marcelo Waisman