0

I am just learning jquery and javascript and i have a function that unwraps [select] elements on my page and displays them as buttons. There could be multiple select boxes on my page so I need to dynanically name the following variables based on the elementname that is passed in, so that when the buttons are clicked it passed the correct values:

selector1
currentvalue1
hidden1
svalue1

This is the function:

function doUnwrap(elementname) {
    var selector1 = document.getElementById('' + elementname + '');
    var currentvalue1 = selector1[selector1.selectedIndex].text;
    var hidden1 = $('<input type="hidden" name="' + elementname + '">');
    hidden1.val($('[name=' + elementname + ']').val());
    hidden1.insertAfter($('[name=' + elementname + ']'));

    $("[name=" + elementname + "] option").unwrap().each(function () {
        var btn = $('<div class="btn"  id="' + $(this).attr('value') + '">' + $(this).text() + '</div>');

        if ($(this).text() == currentvalue[i]) {
            var btn = $('<div class="btn" id="' + $(this).attr('value') + '" >' + $(this).text() + '</div>');
            if ($(this).is(':checked')) btn.addClass('on');
            $(this).replaceWith(btn);
        } else {
            var btn = $('<div class="btn" id="' + $(this).attr('value') + '"  >' + $(this).text() + '</div>');
            $(this).replaceWith(btn);
        };

    });

    $(document).on('click', '.btn', function () {
        $('.btn').removeClass('on');
        $(this).addClass('on');
        $('input[name=' + elementname + ']').val($(this).text());

        var sValue1 = "&value=" + elementname + "|" + $(this).attr('id') + "";
        executeAjaxEvent(sValue1, null, "ComboBoxAjaxHandler", false, null, true);
    });
}
Cristiano Soares
  • 619
  • 1
  • 9
  • 20
Steve
  • 1
  • 3
    It's for this exact reason that dynamic id/name attributes should be avoided; it turns the code in to a mess of hard to maintain spaghetti. A much better idea is to use common classes and then traverse the DOM to find related elements. If you can show us a sample of the HTML that's generated (note the HTML output itself, not the code that generates the HTML) then I'm sure someone here will be able to show you exactly how to do that. Also note that delegated event handlers would probably help too. – Rory McCrossan Feb 15 '19 at 14:32
  • Possible duplicate of [Use dynamic variable names in JavaScript](https://stackoverflow.com/questions/5117127/use-dynamic-variable-names-in-javascript) – Jared Smith Feb 15 '19 at 14:34

0 Answers0