jQuery 에서 Select input 에 option 을 추가 삭제하는 코드이다. 영어라 두려워말고 살짝 읽어보면 이해 가능할 것이다.

URL : http://www.electrictoolbox.com/jquery-add-option-select-jquery/


select box의 내용 가져오기
    $("#select_box > option:selected").val();
select box의 값 설정
    $("#select_box > option[@value=지정값]").attr("selected", "true")

My last jQuery post looked at how to count the number of options in a select and then clear all options from the select. This post looks at how to add a new option to a select with jQuery.

Working Example

The following is an example showing an already populated select. Clicking the "Add option" button adds a new option to the end of the select and makes it the selected one. Clicking "Replace options" replaces them with a new set of options and then selects the "Green" one.

Note that the above example will not work if you are reading this in a feed reader. In this case click through to view this post in a web browser.

Adding a single option - by appending HTML

Adding a single option can be done by appending HTML to the select box. The select in the above example has an id of "example" i.e. <select id="example"> and using this method adding a new option by appending HTML can look like this:

1$('#example').append('<option value="foo" selected="selected">Foo</option>');

This newly added option will be the selected option; to change this behavior remove the selected="selected" part.

Adding a single option - by appending a new option - method 1

To avoid having to write and append HTML and stick with a more Javascript approach the new option can be appended with jQuery by creating a new option object. This next example does not work correctly in Internet Explorer; it will add the new option but only the value and not display any text.

1$('#example').append(new Option('Foo', 'foo', true, true));

The true, true part at the end will make this item the selected one.

Adding a single option - by appending a new option - method 2

This method gets a handle to the options and adds a new option to the array of options. This does work in Internet Explorer and is the more traditional Javascript way of adding options.

1var options = $('#example').attr('options');
2options[options.length] = new Option('Foo', 'foo', true, true);

Adding multiple options

Using the final method above this last example shows how to replace the existing set of options with a new set, which may have been retrieved from an AJAX call or similar.

01var newOptions = {
02    'red' : 'Red',
03    'blue' : 'Blue',
04    'green' : 'Green',
05    'yellow' : 'Yellow'
06};
07var selectedOption = 'green';
08 
09var select = $('#example');
10var options = select.attr('options');
11$('option', select).remove();
12 
13$.each(newOptions, function(val, text) {
14    options[options.length] = new Option(text, val);
15});
16select.val(selectedOption);

Lines 1 to 7 define the new options with an associative array and the one which will be selected. This is what might have been retrieved from an AJAX call.

Lines 9 and 10 cache a handles to #example and its options.

Line 11 removes all the existing options.

Lines 13 to 15 loop through the new options and add them to the select box.

And finally line 16 sets the selected option.

Alternative methods

There are some alternative methods to adding options to a select box with jQuery using various plug-ins and I may look at these in a future post.

Related posts:


크리에이티브 커먼즈 라이센스
Creative Commons License
이올린에 북마크하기(0) 이올린에 추천하기(0)

Posted by 홍반장

2010/11/01 09:49 2010/11/01 09:49
, , ,
Response
No Trackback , No Comment
RSS :
http://tcbs17.cafe24.com/tc/rss/response/5603

    var rowCnt = 0;
        
function fnInputCreate(tbodyId, pnum,limitCount, pnumSize,pnumColor) {
    var myTbody = document.getElementById(tbodyId);

    //alert(tbodyId);

    var row     = document.createElement("tr");
    var rowId = "row" + rowCnt++;

    var cell             = document.createElement("td");
    var cell2             = document.createElement("td");
    var cell3             = document.createElement("td");
    var cell4             = document.createElement("td");
    var cell5             = document.createElement("td");
    var i_idx             = document.createElement("input");    //-- o_idx
    var i_pnum         = document.createElement("input");    //-- o_num
    var i_countchk    = document.createElement("input");    //-- o_countcheck
    var i_size             = document.createElement("select");    //-- o_size
    var i_color         = document.createElement("select");    //-- o_color
    var i_count        = document.createElement("input");    //-- o_count

    row.setAttribute("style","text-align:center;")
    
    i_idx.setAttribute("type", "hidden");
    i_idx.setAttribute("name", "o_idx[]");
    i_idx.setAttribute("value", "");
    i_pnum.setAttribute("type", "hidden");
    i_pnum.setAttribute("name", "o_num[]");
    i_pnum.setAttribute("value", pnum);
    i_countchk.setAttribute("type", "hidden");
    i_countchk.setAttribute("name", "o_countcheck[]");
    i_countchk.setAttribute("value", limitCount);
    
    i_size.setAttribute("name", "o_size[]");
    i_size.setAttribute("value", "M");
    i_size.setAttribute("style", "width:60px;");
    
    //--- Size Option first
    if (isIE()) {
        i_size.options[0] = new Option("Size", "");
    }
    else {
        i_sizeop     = document.createElement("option");    //-- o_size  - option
        i_sizeop.appendChild(document.createTextNode("Size"));
        i_sizeop.setAttribute("value", "");
        i_size.options.add(i_sizeop);
    }    
    for (var i = 0; i < pnumSize.length; i++){
            ii = i +1;
        if (isIE()) {
            i_size.options[ii] = new Option(pnumSize[i], pnumSize[i]);    
        }else{
            i_sizeop     = document.createElement("option");    //-- o_size  - option
            i_sizeop.appendChild(document.createTextNode(pnumSize[i]));
            i_sizeop.setAttribute("value", pnumSize[i]);
            i_size.options.add(i_sizeop);
        }
    };
        
    i_color.setAttribute("name", "o_color[]");
    i_color.setAttribute("value", "1");
    i_color.setAttribute("style", "width:100px;");
    
    //--- Color Option First
    if (isIE()) {
        i_color.options[0] = new Option("Color", "");    
    }else{
        i_colorop     = document.createElement("option");    //-- o_color - option
        i_colorop.appendChild(document.createTextNode("Color"));
        i_colorop.setAttribute("value", "");
        i_color.options.add(i_colorop);
    }
    for (var i = 0; i < pnumColor.length; i++){
            ii = i + 1;
        if (isIE()) {
            i_color.options[ii] = new Option(colorchip_name(pnumColor[i]), pnumColor[i]);    
        }else{
            i_colorop     = document.createElement("option");    //-- o_size  - option
           //i_colorop.appendChild(document.createTextNode(pnumColor[i]));
            i_colorop.appendChild(document.createTextNode(colorchip_name(pnumColor[i])));
            i_colorop.setAttribute("value", pnumColor[i]);
            i_color.options.add(i_colorop);
        }
    };
    
    
    
    
    i_count.setAttribute("type", "text");
    i_count.setAttribute("name", "o_count[]");
    i_count.setAttribute("value", limitCount);
    i_count.setAttribute("style", "ime-mode:disabled;width:50px;text-align:right;");

    var button  = document.createElement("input");
    var button2 = document.createElement("input");

    if (isIE()) {
        row.id  = rowId;
        button  = document.createElement("<input onclick=\"fnInputCreate('" + tbodyId + "','" + pnum + "','" + limitCount + "', size_" + pnum + ", color_" + pnum + ")\"  />");
        button2 = document.createElement("<input onclick=\"fnInputRemove('" + rowId + "')\"    />");
    } else {
        row.setAttribute("id", rowId);
        button.setAttribute("onclick", "fnInputCreate('" + tbodyId + "','" + pnum + "','" + limitCount + "', size_" + pnum + ", color_" + pnum + ")");
        button2.setAttribute("onclick", "fnInputRemove('" + rowId + "')");
    }

    button.setAttribute("type",  "button");
    button.setAttribute("value", "+");
    button.setAttribute("class", "newButton");
    button.setAttribute("style", "width:25px;");
    button2.setAttribute("type", "button");
    button2.setAttribute("value", "-");
    button2.setAttribute("class", "newButton");
    button2.setAttribute("style", "width:25px;");
 
    cell.appendChild(i_idx);
    cell.appendChild(i_pnum);
    cell.appendChild(i_countchk);
    cell.appendChild(i_size);
    cell2.appendChild(i_color);
    cell3.appendChild(i_count);
    cell4.appendChild(button);
    cell5.appendChild(button2);

    row.appendChild(cell);
    row.appendChild(cell2);
    row.appendChild(cell3);
    row.appendChild(cell4);
    row.appendChild(cell5);

    myTbody.appendChild(row);
}

function delEventPresentRow(buttonObj) {
    var tableBody = document.getElementById("targetBody");
    var index = buttonObj.parentElement.parentElement.rowIndex;
    tableBody.removeChild(tableBody.childNodes[index]);
}

function fnInputRemove(rowId) {
    var row = document.getElementById(rowId);
    //alert(rowId);
    row.parentNode.removeChild(row);
}

크리에이티브 커먼즈 라이센스
Creative Commons License
이올린에 북마크하기(0) 이올린에 추천하기(0)

Posted by 홍반장

2010/06/29 15:14 2010/06/29 15:14
, , , , , ,
Response
No Trackback , No Comment
RSS :
http://tcbs17.cafe24.com/tc/rss/response/5314


블로그 이미지

- 홍반장

Archives

Recent Trackbacks

Calendar

«   2024/11   »
          1 2
3 4 5 6 7 8 9
10 11 12 13 14 15 16
17 18 19 20 21 22 23
24 25 26 27 28 29 30
Statistics Graph

Site Stats

Total hits:
236193
Today:
662
Yesterday:
195