0

I have a series of checkboxs and on change event like so:

$(".checkbox").on('change', function () {
          UpdateHolder($(this).attr('id'), customerID, this.checked);
});


function UpdateHolder(questionid, customerid, checked) {
        holder.push({ questionid: questionid, customerid: customerid, checked: checked });
        console.log(holder);
    }

with this, I am able to add an item to the array, but my question is how would I update an item ? I only want to update if a checkbox is selected or not.

2 Answers 2

1

The easiest way to achieve this is to not update the list at all, but instead to create a new one on each action. Try this:

$('.checkbox').on('change', function() {  
    holder = $('.checkbox').map(function() {
        return { 
            questionid: this.id,
            customerid: customerID, // I presume this is a global variable?
            checked: this.checked
        };
    }).get();
    console.log(holder);
});
Sign up to request clarification or add additional context in comments.

2 Comments

True, it doesn't match the topic of your question, but it does meet the goal and is, in practice, a far better pattern to use.
@GuruprasadRao thanks - although I missed get() from my code. Here's an updated example: jsfiddle.net/1Lw5y2c7/1
0

To be able to update existing entries, your function should look something like this:

function UpdateHolder(questionid, customerid, checked) {
    var index = holder.indexOf({
        questionid: questionid,
        customerid: customerid,
        checked: checked
    });
    index = index > -1 ? index : holder.indexOf({
        questionid: questionid,
        customerid: customerid,
        checked: !checked
    });
    //item was not found, insert it
    if( index < 0 ) {
        holder.push({ 
            questionid: questionid, 
            customerid: customerid, 
            checked: checked 
        });
    //item was found, update it
    } else {
        holder[index] = {
            questionid: questionid,
            customerid: customerid,
            checked: checked
        };
    }
    console.log(holder);
}

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.