purple11111 purple11111 - 1 year ago 45
Javascript Question

jquery get autonumbered input values and create select box from it

This is part of a bigger project but want to keep it simple for here so I created a fiddle with a good starting position: http://jsfiddle.net/F7aKG/214/

We got a html form with literally hundreds of inputs and we only need to get the values from a few of those to create the selectbox. So we can't get all the inputs into the form.

Lets say we have this code

<input id="jform_params__characters__characters0__character_name" value="first"><br>
<input id="jform_params__characters__characters1__character_name" value="second"><br>
<input id="jform_params__characters__characters2__character_name" value="third"><br>
<input id="jform_params__characters__characters3__character_name" value="fourth"><br>
<input id="jform_params__characters__characters4__character_name" value="fifth"><br>

Normally the values won't be set in the form but did it now as it became tideous to fill it in every time i wanted to test the form. As you can see the only thing changing is the number into the id.

so far to test grabbing the values i got this:

var values = $( "input[id^='jform_params__characters__characters']" ).map( function(){return $(this).val(); }).get();

the question

Right now when clicked the alert gives me
now how can I change this into the options for the selectbox.

I appreciate any tips I can get but if you are willing then I would love to have a complete code example. It would be absolutely great if the above fiddle could be changed with a working selectbox.

Thanks to everyone for reading and helping.

Answer Source


        var values = $( "input[id^='jform_params__characters__characters']" ).map( function(){return $(this).val(); }).get();
        var optionsPlaceholder = '###OPTIONS###';
        var optionPlaceholder = '###OPTION###';
        var select = '<select>' + optionsPlaceholder + '</select>';
        var option = '<option>' + optionPlaceholder + '</option>';
        var options = '';

        for (var i = 0; i < values.length; i++) {
            var currentOption = option.replace(optionPlaceholder, values[i]);
            options += currentOption;

        var selectBox = select.replace(optionsPlaceholder, options);
        var $select = $(selectBox);