每次添加新项目时,使用数组更新隐藏字段值

时间:2015-08-12 12:13:41

标签: jquery arrays onchange var hidden-field

每次将新饼干添加到桶中时,如何使用变量barrel的值更新隐藏的输入字段值?

因此,当添加多个饼干时,字段值可以显示为hobnob, Gingernut, Oreo

...的jQuery

var barrel_items = [];
var barrel = barrel_items;

$('[data-biscuit]').click(function(){
    var biscuit = $(this).data('biscuit');
    add_to_barrel(biscuit);
});


function add_to_barrel(item){

    var name = '';
    switch(item){
        case 'custardcream':
            name = 'Custard Creams';
            break;

        case 'jammydodger':
            name = 'Jammy Dodgers';
            break;
        case 'bourbon':
            name = 'Bourbons';
            break;
        case 'nice':
            name = 'Nice';
            break;
        case 'chocolatedigestive':
            name = 'Chocolate Digestives';
            break;
        case 'digestive':
            name = 'Digestive';
            break;
        case 'fruitshortcake':
            name = 'Fruit Shortcake';
            break;
        case 'gingernut':
            name = 'Gingernut';
            break;
        case 'oreo':
            name = 'Oreo';
            break;
        case 'hobnob':
            name = 'Hobnobs';
            break;
        case 'cookie':
            name = 'Cookies';
            break;


    }

    // If item is already there in array, it's index will be returned,
    // otherwise indexOf() will return -1
    var indexOfItem = barrel_items.indexOf(item);
    if(indexOfItem !== -1)
    {
        $('.barrel .chosen').eq(indexOfItem).remove();
        barrel_items.splice(indexOfItem,1);
    }
    else
    {
        $('.barrel').append('<div class="chosen">' + name + '</div>');
        barrel_items.push(item);
        //alert(barrel);

    }

    if ( barrel.length ) {
        $('.form').addClass( "show");
    } else if (!barrel.length) {
        $('.form').removeClass( "show");
    }

}

HTML ...

<input type="hidden" id="barrel" name="barrel" value="" />

1 个答案:

答案 0 :(得分:2)

这很简单:

$('[data-biscuit]').click(function(){
    var biscuit = $(this).data('biscuit');
    add_to_barrel(biscuit);
    $("#barrel").val(biscuit); //Add biscuit to barrel hidden input
});