1

Here's my attempt at trying to remove a value from an array dynamically

$('.btn-remove').click(function() {
    var players = ["compare","13076","13075","13077","12755"];
    var removePlayer = $(this).data('player');
    var idx = $.inArray(removePlayer, players);
    if (idx != -1) {
        players.splice(idx, 1);
    }
    window.location = "/" + players.join('/');
})

For example, $(this).data('player') could equal 13077 and i'd want it to remove that value from the array and then redirect to the url which is attached to the window.location variable

3
  • So you want to redirect to compare/13076/13075/12755? Commented Jan 25, 2015 at 4:13
  • In this specific instance that I've quoted, that'd be correct @RayToal Commented Jan 25, 2015 at 4:14
  • Just a guess, but probably a duplicate of Issue with jQuery data() treating string as number or similar -- the data value from $(this).data('player') is auto-converted to a number, so the $.inArray test fails comparing a number against a string. Commented Jan 25, 2015 at 4:16

1 Answer 1

2

The issue here is that .data converts the player data string value to a number:

Every attempt is made to convert the string to a JavaScript value (this includes booleans, numbers, objects, arrays, and null). A value is only converted to a number if doing so doesn't change the value's representation... The string value "100" is converted to the number 100.

In your example, you're doing

$.inArray(13077, ["compare","13076","13075","13077","12755"]);

rather than

$.inArray("13077", ["compare","13076","13075","13077","12755"]);

You must either convert the data value back to a string (e.g., removePlayer += "") or fill the array with number values instead of strings.

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.