开发者

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:

$(funct开发者_JAVA技巧ion(){
    $('#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.


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


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());
    });
});


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


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);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜