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.
The concat() method joins two or more strings.
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.
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.
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.
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');
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With