How do I add & remove values from a hidden input field?

<input type="hidden" id="values" value="1,2,1,3" />

<a href="#" id="add" data-value="4">add</a>

<a href="#" id="remove" data-value="1">remove</a>

<script type="text/javascript">
$(document).ready(function()
{
    $('#add').click(function()
    {
        var value = $(this).attr('data-value');

        //add to $('#values')

        return false;
    });

    $('#remove').click(function()
    {
        var value = $(this).attr('data-value');

        //remove all values that match in $('#values');

        return false;
    });
});
</script>

Examples

a) Add, output would be: 1,2,1,3,4

b) Remove, output would be 2,3

Answers


You can achieve this with basic JavaScript functions and some jQuery goodies. Have a look at the documentation of the individual functions to learn more about them.

Add:

$('#values').val(function(i, v) {
    var arr = v.split(',');
    arr.push(value);
    return arr.join(',');
    // or actually easier in this case:
    // return v ? v + ',' + value : value;
});

Remove:

$('#values').val(function(i, v) {
    return $.grep(v.split(','), function(v) { 
        return v != value; 
    }).join(',');        
});

Reference: val, split, push, join, grep

DEMO


Add:

$('#add').click(function() {
    var values = $(this).attr('data-value');
    alert($("#values").val());
    $("#values").val($("#values").val() + values);    
    alert($("#values").val());

    return false;
});

Remove would work the same way.

you can get the value from the hidden input with the .val()


You could use

 var str = $('#values').val() + value;
 $('#values').val(str);

to add values to the textbox


Need Your Help

Query performance difference SQLAlchemy vs pgAdmin

python performance sqlalchemy profiling pgadmin

I'm testing a query in pgAdmin and SQLAlchemy and found that the execution time of both varies substantially (SQLA=0.9sec, pgAdmin=0.090s) . I wonder how this could be?

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.