Lyan Dwi Pangestu
Lyan Dwi Pangestu

Reputation: 473

append a select box with same option but different name

How can I append a select box with same option and different name. I have a loop, where my php reads a sql table, and for each row, it creates a option tag

this is the function to append:

$(function(){
    $('#add').click(function(){
        var select = $('span[id=combo]').html();
        $('#allCombo').append('<br/><span id="combo">'+select+'</span>');
    });
});

this is the select box:

<span id="allCombo">
                <span id="combo" name="combo">
                    <select name="item">
                        <?php foreach ($items as $item) { ?>
                            <option value="<?php echo $item->item_id; ?>">
                            <?php echo $item->item_name; ?></option>
                        <?php } ?>
                    </select>
                </span>
</span>

Can anyone help me. thanks before.

Upvotes: 0

Views: 455

Answers (4)

Felix Kling
Felix Kling

Reputation: 817238

Use item[] as name . PHP will convert this to an array, so the selected values are in an array stored at $_POST['item'].

But more important is to not duplicate IDs. I suggest to remove the inner span completely, as

  1. you cannot have duplicate IDs and
  2. span tags have no name attribute

so there is no need to keep this tag.

<span id="allCombo">
    <select name="item[]">
        <?php foreach ($items as $item): ?>
            <option value="<?php echo $item->item_id; ?>">
                <?php echo $item->item_name; ?>
            </option>
       <?php endforeach; ?>
     </select>
</span>

The JS code would be:

$(function(){
    $('#add').click(function(){
        $('#allCombo')
           .append('<br />')
           .append($('#allCombo select').first().clone());
    });
});

Upvotes: 0

Seth
Seth

Reputation: 6260

$(function(){
    $('#add').click(function(){
        var select = $('#combo').html();
        $('<br/><span id="combo">'+select+'</span>').appendTo('#allCombo').find.('select').attr('name', 'uniqueName');
    });
});

Upvotes: 1

moritz
moritz

Reputation: 25766

You can always use the clone method:

var new_combo $('span#combo').clone();
new_combo.attr('name', 'second_combo');
new_combo.attr('id', 'second_combo'); // for valid html
$('#allCombo').append(new_combo);

Upvotes: 0

ChrisThompson
ChrisThompson

Reputation: 2008

var newSelect = $('select[name=item]').clone().attr('name', 'newselect');
$('#allCombo').append(newSelect);

Upvotes: 0

Related Questions