简体   繁体   中英

How to empty select box using jquery when drop down option changes

I have a jQuery click function below where it appends a selected value from one select box to another:

// Add Button
$('#addbtn').click(function() {
    var selectedOption = jQuery("#studentremain option:selected");
    selectedOption.appendTo($("#studentadd"));
});   

Now the problem I am having is that if a user changes an option in a drop down menu, then I want the select box #studentadd to go back to being empty. Problem is that the values appended into the select box remain, how can I empty the select box?

Below is the jQuery function for when drop down menu changes and my attempt on emptying the select box:

$('#sessionsDrop').change(function() {
    if ($(this).val() !== '') {
        var text = $(this).find('option:selected').text();
        $('#studentadd').val('');     
    }
});

HTML/PHP:

Select box:

$addSELECT = "";  
$addSELECT .= '<select name="addtextarea" id="studentadd" size="10">';
$addSELECT .= '</select>'; 

Drop down menu:

$sessionHTML = '<select name="session" id="sessionsDrop">'.PHP_EOL;
$sessionHTML .= '<option value="">Please Select</option>'.PHP_EOL;        
$sessionHTML .= '</select>';

肯定会这样做吗?

$('#studentadd').html('');

To remove the contents of an element you can use empty() :

$('#sessionsDrop').change(function() {
    if ($(this).val() !== '') {
        var text = $(this).find('option:selected').text();
        $('#studentadd').empty();     
    }
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM