开发者

How to filter comma separated integer values in javascript

开发者 https://www.devze.com 2023-03-25 04:23 出处:网络
I have a varaiable in javascript like the following var elem开发者_开发技巧ent = parent.document.getElementById(\'productCollectionField\');

I have a varaiable in javascript like the following

  var elem开发者_开发技巧ent = 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.


var myResults = values.split(",")

You will then have an array you can parse


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);    


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,

0

精彩评论

暂无评论...
验证码 换一张
取 消