join method is not working in jquery
Question by prerna
$(".commentbox").on("click",".btnSave",function(){
var id = $(this).attr("id").split("-");
alert(id);
id.shift();
alert(id);
var newString = id.join('-');
alert(newString);
});
});
Input is btnSave-88eC4B8D2-8F96-4EB5-B42E-08C540D7F171
Output :88eC4B8D2,8F96-4EB5,B42E,08C540D7F171
Whereas it works fine for btnReply
button Why
Please help me out
Answer by naveen
Is this a trick question ? 🙂
The problem is with this line of code
<input type='button' class='btnSave' value='Save' id='btnSave-" + id + "' /> "
Here id passed is actually id="btnSave-88C4B8D2,8F96,4EB5,B42E,08C540D7F171"
because id is an array and that array got converted to a comma separated string because you set it as string attribute. Now you call split(-) on that string which gives you “btnSave” and “88C4B8D2,8F96,4EB5,B42E,08C540D7F171”. Now you shift
and remove the btnSave leaving the single member “88C4B8D2,8F96,4EB5,B42E,08C540D7F171” and then you call join(“-“) on that single string which doesn’t change a thing at all. So, all you have to do is change the above shown like like this
<input type='button' class='btnSave' value='Save' id='btnSave-" + newString + "' /> "
Fiddle here: http://jsfiddle.net/naveen/XHr6e/