April 22, 2012

join method is not working in jquery

Question by prerna

JSFiddle

$(".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/

Answer by Starx

One of the weird issues I have encountered, but escaping the - fixes the problem.

var newString = id.join('-');

Usage: Demo

$(".commentbox").on("click",".btnSave",function(){
        var id = $(this).attr("id").split("-");
        id.shift();
        var newString = id.join('-');
        alert(newString);
   });       
});​

Author: Nabin Nepal (Starx)

Hello, I am Nabin Nepal and you can call me Starx. This is my blog where write about my life and my involvements. I am a Software Developer, A Cyclist and a Realist. I hope you will find my blog interesting. Follow me on Google+

...

Please fill the form - I will response as fast as I can!