Writing /volume1/Web/Public/dokuwiki/data/log/deprecated/2024-11-14.log failed

文書の過去の版を表示しています。


Writing /volume1/Web/Public/dokuwiki/data/log/deprecated/2024-11-14.log failed

Append select option using jquery

jqueryを利用し、動的にoptionを作成する方法を紹介する。 まずはデモから見てみよう。

Test Page

<html> <head> <script type=“text/javascript” src=“./test/js/jquery-1.4.2.js”></script> <script type=“text/javascript”> <!– function addOption1(){

 var index = $('#example option').length + 1
 $("#example").append($("<option/>").val(index).text("This is option#"+index).attr("selected", "selected"));

}

function remove(){

 $("#example option").remove();

}

function replace(){

 var options = newOptions = {
   'red' : 'Red',
   'blue' : 'Blue',
   'green' : 'Green',
   'yellow' : 'Yellow'
};
$("#example option").remove();
$.each(options, function(key, val){
    $("#example").append($("<option/>").val(key).text(val));
});
$("#example").val("green");

}

function reset(){

$("#example option").remove();
$("#example").append($("<option/>").val("1").text("This is the first option"));
$("#example").append($("<option/>").val("2").text("This is the second option"));
$("#example").append($("<option/>").val("3").text("This is the third option"));

} –> </script> </head> <body> <select id=“example”> <option value=“1”>This is the first item.</option> <option value=“2”>This is the second item.</option> <option value=“3”>This is the third item.</option> </select> <input type=“button” name=“test1” value=“remove” onclick=“remove();”/> <input type=“button” name=“test2” value=“Add an option” onclick=“addOption1();”/> <input type=“button” name=“test3” value=“replace” onclick=“replace();”/> <input type=“button” name=“test4” value=“reset” onclick=“reset();”/> </body> </html> ===== code snippet ===== <code Javascript> function replace(){ var options = newOptions = { 'red' : 'Red', 'blue' : 'Blue', 'green' : 'Green', 'yellow' : 'Yellow' }; $(“#example option”).remove(); $.each(options, function(key, val){ $(“#example”).append($(“<option/>”).val(key).text(val)); }); $(“#example”).val(“green”); } </code> ===== access selected value ===== 因みに、選択された項目を取得する方法を紹介する。 デモを見てみる。 <html> <head> <script type=“text/javascript” src=“./test/js/jquery-1.4.2.js”></script> <script type=“text/javascript”> <!– function showValue(){ alert($(“#example”).val()); } function showText(){ alert($(“#example :selected”).text()); } –> </script> </head> <body> <select id=“example”> <option value=“1”>This is the first item.</option> <option value=“2”>This is the second item.</option> <option value=“3”>This is the third item.</option> </select> <input type=“button” name=“test1” value=“selected vlaue” onclick=“showValue();”/> <input type=“button” name=“test2” value=“selected text” onclick=“showText();”/> </body>

</html>

reference


QR Code
QR Code study:javascript:jquery:select (generated for current page)