Jump to content


Photo

Removing comma seperated value


  • Please log in to reply
2 replies to this topic

#1 dweb

dweb

    Advanced Member

  • Members
  • PipPipPip
  • 113 posts

Posted 20 June 2013 - 07:44 AM

hi all

 

i have a input field on my webpage that looks like

<input name="people" id="people" value="1,4,6,8,10,23">

and I want to run a javascript so when my link, such as

<a href='javascript:remove_comma(3)'>click</a>

is clicked, it would remove the 3rd comma separated value, leaving me with

<input name="people" id="people" value="1,4,8,10,23">

but i might also do

<a href='javascript:remove_comma(1)'>click</a>

<a href='javascript:remove_comma(5)'>click</a>

can anyone help?

 

thanks



#2 Adam

Adam

    Advanced Member

  • Gurus
  • 5,693 posts
  • LocationSheffield / UK

Posted 20 June 2013 - 10:15 AM

Use the split() string method to convert the string into an array, and then use splice() to remove the item specified. Remember that array indexes start from 0. You can convert the array back to a string using join().

Edited by Adam, 20 June 2013 - 10:17 AM.


#3 Xaotique

Xaotique

    Advanced Member

  • Members
  • PipPipPip
  • 565 posts
  • LocationPennsylvania, United States
  • Age:22

Posted 20 June 2013 - 11:51 AM

Just to give an example of what Adam said.

JSFiddle: http://jsfiddle.net/gfFG9/

function removeCSV(elm, pos)
{
    var arr = elm.value.split(',');
    arr.splice(pos, 1);
    
    elm.value = arr.join(',');
}

var element = window.document.querySelector("#people");
removeCSV(element, 0); // Remove the first value.

/*
 * 0, 1, 2, 3 .. for elements.  Element 1 is the second, 2
 * the third, and so on.
 */

Edited by Xaotique, 20 June 2013 - 11:52 AM.





0 user(s) are reading this topic

0 members, 0 guests, 0 anonymous users

Cheap Linux VPS from $5
SSD Storage, 30 day Guarantee
1 TB of BW, 100% Network Uptime

AlphaBit.com