0

I have a hidden input:

<input type="hidden" id="paidIds" name="paidIds" value="[]">

It starts with an empty array as its value. I want to add and remove items from it but I cant work out how.
This is my code so far:
TO APPEND:

var $paidIds = $('#paidIds').val();
$paidIds.push($id);
$('#paidIds').val($paidIds);

TO REMOVE:

var $paidIds = $('#paidIds').val();
var $index = paidIds.indexOf($id);
if($index != -1) {
    $('#paidIds').val().splice($index, 1);
}
$('#paidIds').val($paidIds);

So far one of the issues is $paidIds is still undefined after:

var $paidIds = $('#paidIds').val(); 

At a loss, and google is not helping -__-

EDIT Got it working partly, in the debugger $paidIds = [4] but it did not set the value.

var $paidIds = JSON.parse($('#paidIds').val());
$paidIds.push($id);
$paidIds = JSON.stringify($paidIds)
$('#paidIds').val($paidIds);

EDIT2 fixed the missing #

3 Answers 3

1

You need to convert string to object.

Change:

$('paidIds').val()

to

$('#paidIds').val()

Try:

var $paidIds = $('#paidIds').val();
if($paidIds != ""){
    $paidIds = JSON.parse($paidIds);
}
Sign up to request clarification or add additional context in comments.

4 Comments

still has invalid selector
Tried it but getting a "Uncaught SyntaxError: Unexpected token u" error on this line var $paidIds = JSON.parse($('paidIds').val());
Thanks fixed the selector typo.
Nvm was my selector typo again
1

try to use JSON.parse when you read from the input, and use JSON.stringify when you set the input's value

Comments

1

I would suggest you store array an a data- attribute and use jQuery.data() to read it rather than parsing the value to an array.

HTML

<input id="paidIds" name="paidIds" data-array="[1,2,3]" value="[1,2,3]">

JS

/* Custom event to handle updates*/    
 $('#paidIds').on('updateArray', function (evt, newVal) {
     var arr = $(this).data('array');
     arr.push(newVal);
     $(this).val(JSON.stringify(arr))
 });

/* Useage*/
 $('button').click(function () {
      var newArrValue=$(this).data('val')
     $('#paidIds').trigger('updateArray', [newArrValue]);
 });

DEMO

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.