0

Hello I want to create an array in javascript

var sortValues = array(
                 2 => array(3,4,5),
                 3 => array(5,6,7), 
                 12 => array (7,4,5) 
                 );

Now I am looping through all textboxes of my form. Every textbox has id like 2_3 means 2 will be the main index of the array.

My html markup looks like

<input type="text" value="3" id="2_5" name="2_5">
<input type="text" value="4" id="2_5" name="2_6">
<input type="text" value="5" id="2_5" name="2_7">
<input type="text" value="5" id="3_1" name="3_1">
<input type="text" value="6" id="3_2" name="3_2">
..................................

Now I want to check if 2 exists in array sortValues, I will take the value of the text box and and will check if this value exists in the array against 2 then I will put an alert that value already exists, if value doesn't exists push the value in sub array. Means I need to put 3 against 2 I will check if 3 exists against 2, if yes put alert else push in array.

If 2 (main index) doens't exist create a new index in array and so on. I have tried so far

var sortvalues = new Array();
$(":text").each(function () {
    if($(this).val() != '') {
        id = $(this).attr('id');
        ids = id.split("_");
        parent = ids[0];
        child = ids[1];
        if(typeof sortvalues[parent] !== 'undefined') {
            if(typeof sortvalues[parent][$(this).val()] !== 'undefined') {
                alert("Value already exists");
            } else {
                sortvalues[parent][] = $(this).val();
            }
        } else {
            sortvalues.push(parent);
        }
    }
});
console.log(sortValues);

Which gives ["2", "2", "2"] which is wrong. Can Any body guide me how can I achieve above mentioned array in above mentioned criteria ??/

2
  • what is your html markup, can you create fiddle ? Commented Mar 12, 2013 at 7:32
  • You're mixing JavaScript and PHP, sortvalues[parent][] = $(this).val() is not right. Also your top array declaration is not valid JS syntax. Commented Mar 12, 2013 at 7:32

1 Answer 1

0

Do you mean to create an array in another array?

For example :

var sortValues = new Array();
sortValues[2] = Array(3,4,5);

Please clarify your question. And the following:

sortvalues[parent][] = $(this).val()  --> you can't leave empty for the second array.

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.