passing string values with special characters to a function Javascript
I have a function that requires full name as an input, this name can have hyphens,apotrohpe,comma etc.
function AddOtherRefDoc(name, number) {
var remove = "<a \href='javascript:void(0);' onclick='removeRefDoctor(this,'"+name+"',"+number+");'\">Remove</a>";
var html = "<li><b> Referral Doctor: </b>"+name+"<b>, Referral No: </b>"+number+ " " +remove+" <i开发者_StackOverflownput type='text' name='ref_docs' value='"+name+"'></input><input type='text' name='ref_nos' value='"+number+"'></input></li>";
jQuery(opener.document).find("#r_docs").append(html);
}
The way I'm passing name to removeRefDoctor(), it's not working. How can I wrap this name into one string so that the function can accept this value.
Thanks a lot for ur help.
It'd be easier for you to read and fix if you'd reimplement it like this for both variables:
var remove = $("<a/>")
.attr('href', 'javascript:void(0);')
.click(function() {
removeRefDoctor(this,name,number);
})
.text('Remove');
I see some errors on the second line.
Use this
var remove = "<a href=\"javascript:void(0);\" onclick=\"removeRefDoctor(this,"+name+","+number+");\">Remove</a>";
You are using single quotes to quote the onclick attribute and to quote the name
value passed in the function. This closes your onclick attribute early. You may also have single quotes in your name
value. You'll need to use double quotes around your name value and also escape any quotes to avoid html parsing issues. Similarly, you'll need to escape quotes where you are using name
as the value for your <input />
var attrName = name.replace(/'/g, ''');
var jsName = attrName.replace(/"/g, '\\"');
Use it in your function like this:
function AddOtherRefDoc(name, number) {
var attrName = name.replace(/'/g, ''');
var jsName = attrName.replace(/"/g, '\\"');
var remove = "<a \href='javascript:void(0);' onclick='removeRefDoctor(this,\""+jsName +"\","+number+");'\">Remove</a>";
var html = "<li><b> Referral Doctor: </b>"+name+"<b>, Referral No: </b>"+number+ " " +remove+" <input type='text' name='ref_docs' value='"+attrName+"'></input><input type='text' name='ref_nos' value='"+number+"'></input></li>";
jQuery(opener.document).find("#r_docs").append(html);
}
That's the answer to why your code isn't working as you expect. All that being said, I'd go with Mike Thompson's approach. That makes a lot more sense and solves a lot of problems for you.
精彩评论