0
<div id="values">10 67 87 100 56</div>

<div id="#val1">87</div>

How can I delete 87 value from array when click the #val1 with jquery?

1
  • Show your code with the array please. Commented Nov 18, 2012 at 10:45

4 Answers 4

3

Another way of doing it could be like this:

​$(function​ () {
    $("#val1").click(function() {
        var arr = $("#values").text().split(" "); // Create an array of the values
        var toRemove = $(this).text(); // Get the value to remove

        // Remove the value
        arr = $.grep(arr, function(value) {
            return value != toRemove;
        });

        // Add the new array back as text (without the removed value)
        $("#values").text(arr.join(" "));
    });
});​

See fiddle here

Sign up to request clarification or add additional context in comments.

Comments

2

Well you are not really talking about an array here. Just some textual values within a <div> element.

What you could do is create an array from the existing values like this -

var selection = $("#val1").text();
var divValues = $("#values").text().split(' ');

Then assemble a new array consisting solely of values that do not match the selected value (in this case 87).

var newValues = [];
$.each(divValues,function(index,value){
  if (value != selection){
    newValues.push(value);
  }
});

Now we join the array values back together to get back to the textual content we extracted earlier.

$("#values").text(newValues.join(' '));

2 Comments

The first example could be a little problematic, I'm thinking if one of the values would be 187, 287, etc...
@mar - very, very true... I removed that suggestion. Thanks for the feedback.
2

try something like

var y = [10, 67, 87 ,100 ,56] //or $("#values").text().split(' ');
var removeItem = 67;

y = jQuery.grep(y, function(value) {
  return value != removeItem;
});

JsFiddle

Comments

1

if #values contains array like data which is separated by space then you can do something like :

 $('#val').click(function () {
            var delVal = $("#val").text();
            var arr = $("#values").text().split(' ');
            $("#values").html("");
            for (i = 0; i < arr.length; i++) {
                if (arr[i] != delVal)
                    $("#values").append(arr[i] + " ");
            }
        });

check this in jsFiddle : http://jsfiddle.net/Milian/buNaM/

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.