jQuery : select box example1

다음과 같은 JSON 형식의 파일이 있다고 가정한다.

Test.json

{“S1”:[

{“S1_value”:”1″, “S1_text”: “강아지”},

{“S1_value”:”2″, “S1_text”: “고양이”}

],

“S2”:[

{“S2_value”:”1″, “S2_text”: “수박”},

{“S2_value”:”2″, “S2_text”: “사과”}

]

}

 

Test.html

:

:

<script src=”http://ajax.googleapis.com/ajax/libs/jquery/1.5/jquery.min.js” type=”text/javascript”></script>

<script language=javascript>

$(function(){

var ani = ”;

var fru=”;

$.getJSON(“Test.json” function(data){

each(data.S1, function(i, ani_s){????????????//JSON Data 중 S1(애완동물)에 해당 되는것만 가져온다.

ani = ani + “<option value='”+ani_s.S1_value+”‘>”+ani_s.S1_text+”</option>”;

});

 

each(data.S2, function(i, fru_s){????????????//JSON Data 중 S2(과일)에 해당 되는것만 가져온다.

fru = fru + “<option value='”+fru_s.S2_value+”‘>”+fru_s.S2_text+”</option>”;

});

 

$(“#ANI”).empty().append(ani);????????????//애완동물 SelectBox? 초기화 후 append.
$(“#FRU”).empty().append(fru);????????????//과일 SelectBox 초기화 후 append

});

});

</script>

:

중략

:

<label for=”ANI”>애완동물</label><select name=”ANI” ID=”ANI”></select>

<label for=”FRU”>과일</label><select name=”FRUI” ID=”FRU”></select>

:

 

 

기타

SelectBox 애완동물중 고양이 값 선택하기.

$(“#ANI”).val(‘2′);

$(“#ANI>option[value=’2′]”).attr(“selected”, true);

또는 옵션그룹이 있는Select Box?인경우

$(“#ANI> optgroup >option[value=’2’]”).attr(“selected”, true);

 

선택된 값 읽어오기

$(“#ANI option:selected”).val();
$(“select[name=ANI]”).val();

 

선택된 값 삭제

$(‘#ANI option:selected’).remove();

 

SelectBox 애완동물중 고양이?삭제

$(“#ANI option[value=’2′]”).remove();

 

참고?: 유용한 Plug-in

http://www.techiegyan.com/2008/07/26/jquery-handling-html-select/

21 Replies to “jQuery : select box example1”

Leave a Reply

Your email address will not be published.