简体   繁体   中英

How to Dynamically Change Name attribute of select box

The following Javascript dynamically adds another Select box 'on change' of the original select box. The issue I am having is that when it creates the new select box it gives it the same 'name' and 'id' as the original select box. Therefore when I do a submit action on the form, the last selectbox is the only value submitted. How can I change the 'name' and/or the 'id' attributes of the newly created select box? Honestly I am VERY new to Javascript so if this is an easy fix I do apologize. Thank you ALL in advance!

$(function () {
var values = new Array();

$(document).on('change', '.form-group-multiple-selects .input-group-multiple-select:last-child select', function () {

    var selectsLength = $('.form-group-multiple-selects .input-group-multiple-select select').length;
    var optionsLength = ($(this).find('option').length);



        var sInputGroupHtml = $(this).parent().html();
        var sInputGroupClasses = $(this).parent().attr('class');
        $(this).parent().parent().append('<div class="' + sInputGroupClasses + '">' + sInputGroupHtml + '</div>');



    updateValues();

});

$(document).on('change', '.form-group-multiple-selects .input-group-multiple-select:not(:last-child) select', function () {

    updateValues();

});

$(document).on('click', '.input-group-addon-remove', function () {
    $(this).parent().remove();
    updateValues();
});

function updateValues() {
    values = new Array();
    $('.form-group-multiple-selects .input-group-multiple-select select').each(function () {
        var value = $(this).val();
        if (value != 0 && value != "") {
            values.push(value);
        }
    });

    $('.form-group-multiple-selects .input-group-multiple-select select').find('option').each(function () {
        var optionValue = $(this).val();
        var selectValue = $(this).parent().val();

    });
}

function in_array(needle, haystack) {
    var found = 0;
    for (var i = 0, length = haystack.length; i < length; i++) {
        if (haystack[i] == needle) return i;
        found++;
    }
    return -1;
}

})

have you considered using an array for the select boxes?

The first one, and any that follow can be

<select name="example[]"></select>

And then simply process the array on form submission, you can check for the size and then do a foreach loop if the size is > 1

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