+ Start a Discussion
ssssssssssssss 

Single quote ' handling in a onclick javascript custom link

I have a custom link on a custom object Customer, which is an on click Javascript.

 

This link redirects to a new record page of another object MM Account based on some condition, and it pre-populates Customer.name in a field on the redirected page. 

Following is the code for the button:

 

if( (({!Customer__c.MMAccountHolder__c}) == false) )
{
	var str = '{!Customer__c.Name}';
	str.replace("\"", "\\\"");
	window.location="/a0B/e?retURL={!Customer__c.Id}&00NA0000006AZ4u={!Customer__c.Customer_Number__c}&CF00NA0000006AZ4p="+str+"";
}
else
{
             window.location="/{!Customer__c.MMid__c}";
}

 It works fine when usually, but whenever there is a single quote in the customer name, it gives a javascript error, "expected ; "

 

I have in past, handled double quote, but cant seem to handle the single quote.

 

Can anyone please look into this.

 

Thanks for any help.

 

~Sumit

Best Answer chosen by Admin (Salesforce Developers) 
iBr0theriBr0ther

OK. Use this one:

JSENCODE

 

Your button should look as below:

 

//>>>>>begin

if( (({!Customer__c.MMAccountHolder__c}) == false) )
{
    var str = '{!JSENCODE(Customer__c.Name)}';
     
    window.location="/a0B/e?retURL={!Customer__c.Id}&00NA0000006AZ4u={!Customer__c.Customer_Number__c}&CF00NA0000006AZ4p="+str+"";
}
else
{
             window.location="/{!Customer__c.MMid__c}";
}

 

//>>>>end

All Answers

PkSharmaPkSharma

Try to use Double Quotes.

var str = "{!Customer__c.Name}";

 

Hope this will help you.

iBr0theriBr0ther

Lets try this into your button:

 

function myEncode(str){   
    str = encodeURIComponent(str);
    str = str.replace(/'/g, '%27');
    return str;
}

 

ssssssssssssss

Hey PkSharma and PoorMan,

 

Thanks for writing in.

The thing is, we can also have double quotes, in addition to single quotes in the customer name. it will fail then if it will have double quotes. 

 

Can you please check it?

 

Thanks.

iBr0theriBr0ther

I think encodeURIComponent can already handle double quotes.

ssssssssssssss

No it gives an error 'Unexpected Identifier'.

 

Pls help.

iBr0theriBr0ther

OK. Use this one:

JSENCODE

 

Your button should look as below:

 

//>>>>>begin

if( (({!Customer__c.MMAccountHolder__c}) == false) )
{
    var str = '{!JSENCODE(Customer__c.Name)}';
     
    window.location="/a0B/e?retURL={!Customer__c.Id}&00NA0000006AZ4u={!Customer__c.Customer_Number__c}&CF00NA0000006AZ4p="+str+"";
}
else
{
             window.location="/{!Customer__c.MMid__c}";
}

 

//>>>>end

This was selected as the best answer
ssssssssssssss

Thanks Poorman!!

 

That was exactly something I was thinking about that there should be some method which should be called exactly when the value is retrieved. 

 

Thanks again PKSharma and Poorman!!