简体   繁体   中英

How to add manual option in dynamic appending select options?

This is my javascript code :

$('#select_list_div').empty();

allRecords.push(arrayRec[i]);
allRecords.forEach( function(s) {                               
    $('#select_list_div').append('<option value="' + s.serial_no + '">' + s.serial_no + '.' + s.title + '</option>');   
});

In this code all data from arrayRec is getting added in allRecords . But In this I want to add one option manually, for example :

'<option value="na">Select this</option>'

How can I add this in my JavaScript code ?

Well you just need to prepend another option, so put this code after your forEach :

$('#select_list_div').prepend($("<option />", {
    value: 'na',
    text: 'Select this'
}));

This should work.

$('#select_list_div').empty();

$('#select_list_div').append('<option value="na">Select this</option>');

allRecords.push(arrayRec[i]);

allRecords.forEach( function(s) {                               
    $('#select_list_div').append('<option value="' + s.serial_no + '">' + s.serial_no + '.' + s.title + '</option>');   
});

Or using prependTo()

$("<option value="na">Select this</option>").prependTo("#select_list_div"); 

将元素设为空后,添加以下行。

$('#select_list_div').append('<option value="na">Select this</option>');

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