如何在 jquery 追加后保持选择


How to keep select after jquery append

好的,伙计们,这是小提琴http://jsfiddle.net/wKbXx/24/

$(function() {
$( 'input[name=q1]' ).on( 'change', function() {
    var sel = $('[id^="comm"]'), opt = $( '<option/>' );
    if ($(this).is(':checked')) {
        sel.append( $("<option />").val(this.value).text( this.id ) );
    } else {
        $('option[value=' + this.value + ']').remove();
    }
});
});

我需要做的是使用复选框选择两种颜色。让我们说红色和蓝色。然后使用选择,标记一个红色和一个蓝色。然后选中绿色。我希望它保留所选数据。现在,一旦您选择绿色,它就会擦除该数据。我该怎么做?

更新以反映工作答案..更新的小提琴

我会采用稍微不同的方法;而不是总是重置选择框,我会检查更改的复选框中的文本是否已包含在选择框中。如果是,我会假设它已被取消选中并从选择框中删除该选项。否则,我将只将该新选项附加到选择框中。

$(function() {
    $( 'input[name=q1]' ).on( 'change', function() {
        var sel = $('[id^="comm"]'), opt = $( '<option/>' );
        if (sel.find('option').text().indexOf(this.id) > 0) {
            $('option[value=' + this.value + ']').remove();
        } else {
            sel.append( $("<option />").val(this.value).text( this.id ) );
        }
    });
});

此版本的缺点是,选择框中颜色的顺序由单击复选框的顺序决定;对于您的版本,选择框中的颜色顺序始终与复选框中的顺序相同。

(希望这是有道理的。

这里有一个小提琴:http://jsfiddle.net/Niffler/0hLxzvh8/

这可能是您问题的答案...你也应该把你的重写放在上面。

$(function() {
    var sel = $('[id^="comm"]'), opt = $( '<option/>' );
    sel.html( opt.clone().text( '[Select One]' ) );
    $( 'input[name=q1]' ).on( 'change', function() {
        if ($(this).is(':checked')) {
            sel.append( $("<option />").val(this.value).text( this.id ) );
        }
        else {
            //Remove where ID matches up
            sel.children().remove();
        }
        if( sel.find( 'option' ).length > 1 ) {
           if( sel.find( 'option' ).length === 2 ) {
                sel.find( 'option' ).eq( 1 ).attr( 'selected',true );
            }
        } 
    });
});

干杯!

在替换选项之前,您需要获取选择框的值,然后在最后重置值。

$(function() {
$( 'input[name=q1]' ).on( 'change', function() {
    var sel = $('[id^="comm"]'), opt = $( '<option/>' );
    sel.each(function(){
        sel.data('previous', sel.val());
    });
    // overwrite the existing options
    sel.html( opt.clone().text( '[Select One]' ) );
    $( 'input[name=q1]:checked' ).each( function() {
        sel.append( $("<option />").val(this.value).text( this.id ) );
    }); 
    // if it had a value, set it back to that.
    if ( currentValue != '' ){
        sel.each(function(){
            sel.val(sel.data('previous'));
        });
    } else {   
        if( sel.find( 'option' ).length > 1 ) {
          if( sel.find( 'option' ).length === 2 ) {
                sel.find( 'option' ).eq( 1 ).attr( 'selected',true );
            }
        } 
    }
});
});