简体   繁体   中英

jquery - add values from one listbox to another, but do not include blank lines?

I have some jQuery code that copies the selected values from one listbox to another:

$(adPerson + " option:selected").each(function(){  
    $(toNames).append($(this).clone());  
});     

I'm trying to make sure no blank lines are added to the destination listbox, so I tried this:

$(adPerson + " option:selected").each(function(){  
       if($(this).text != "")
       {
    $(toNames).append($(this).clone()); 
       } 
}); 

The above code does not work - I think is is because of the way .each is used.

Any ideas?

Derek

First off, you need to use text() instead of text if you wanted to test that way. It is a function, not a property.

However, all you need to is use the :not(:empty) jQuery selector:

$(adPerson + " option:selected:not(:empty)").each(function(){  
    $(toNames).append($(this).clone());  
});

You could further simplify it by using this:

$(toNames).append( $(adPerson + " option:selected:not(:empty)").clone() );

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