简体   繁体   中英

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM