Alvaro
Alvaro

Reputation: 41605

Storing array of data into input with jQuery

Each time the user clicks over a checkbox I add a couple of values to a hidden input value.

Each checkbox stores 2 values and it looks like this:

<input type="checkbox" class="first" value="9598864;3">

Where the first value would be: 9598864 and the second: 3.

Currently I am adding data to the input in this way:

var currentValue = $('#myInput').val();
var text;

//adding the value to the input + separator "-"
if($(this).is(':checked')){
    $('#myInput').val(currentValue + "-" + $(this).val());
}

//erasing the value from the input + separator "-"
else{
    text = currentValue .replace("-" + $(this).val(), "");
    $('#myInput').val(text);
}

The result is something like this:

<input type="hidden" name="demo" value="-9582856;3-9598864;3" id="myInput">

Where i get an array of 2 elements each one with another 2 elements inside:

Element 1:

  • 9582856
  • 3

Element 2:

  • 9598864
  • 3

What I am doing now is processing the data on the server side (PHP) and exploding those strings by - and ; to get the desirable elements.

Is there any other better way to accomplish this task? Which would be the correct way to store an array of data inside an input using jQuery or Javascript?

Thanks.

Upvotes: 0

Views: 562

Answers (1)

Nick
Nick

Reputation: 4212

I think your apporach is good, because even if you post vars in some other kind of datastructure ex. obj or array, you have to write some code on server side to handle it. In this situation using explod funk is simplier to use.

Hope this help

Upvotes: 1

Related Questions