Saurabh Kumar
Saurabh Kumar

Reputation: 16661

How to filter comma separated integer values in javascript

I have a varaiable in javascript like the following

  var element = parent.document.getElementById('productCollectionField');
  var values = element.value;

and an input field like

  <input type="hidden" value="1,2,3,4" id ="productCollectionField" />

so var element contains 1,2,3,4

Now I have value 5 and i want to check it in values .? How can i do that...? These numbers can be anything.

Upvotes: 2

Views: 4346

Answers (3)

zatatatata
zatatatata

Reputation: 4821

The simplest solution is to use the following function, which returns true of false whether the number is in the value string or not.

var value = '1,2,3,4';

function checkNumber(number, values) {
    var numberExists = false;
    var strArray = values.split(",")

    for (var i = 0; i < strArray.length; i++)
    {
        // You could use if (strArray[i] == number), but using === is advised
        // since it's more specific about the type
        if ( parseInt(strArray[i]) === number)
            numberExists = true;
    }
    return numberExists;
}

// returns false
checkNumber(5, value);

// returns true
checkNumber(2, value);    

Upvotes: 3

Nemanja
Nemanja

Reputation: 1535

Is jQuery available to you? If yes, you can do it like this:

First, what JMax said:

var myResults = values.split(",")

Define the string that will be the output after the merge:

var newString = '';

Then,

if ( jQuery.inArray( 5, myResults ) == -1 ) {

    myResults.push( 5 );

    newString = myResults.join(',');
}

Cheers,

Upvotes: 2

JMax
JMax

Reputation: 26591

var myResults = values.split(",")

You will then have an array you can parse

Upvotes: 4

Related Questions