Web-Programming/Javascript

[자바스크립트] 동적-라디오 버튼 예제

yehza 2010. 4. 16.


동적-라디오 버튼 예제




<html> 
<body>
<FORM METHOD=POST ACTION="/lib/form_check/echo_post_var.php3">
  <INPUT TYPE="radio" NAME="bbs_type" value='norm' onclick="return drawRadios('norm','no');">일반형</INPUT>
  <INPUT TYPE="radio" NAME="bbs_type" value='norm' onclick="return drawRadios('lect','outer_level');">강좌형</INPUT>
  <INPUT TYPE="radio" NAME="bbs_type" value='norm' onclick="return drawRadios('forum','no');">포럼형</INPUT>
  <hr>
  <div id="nextRdio"></div>
  <INPUT TYPE="submit">
</FORM>
</body>

<script>
function getStyleObject(objectId) {
  var theObject = null;

  // cross-browser function to get an object given its id
  if(document.getElementById && document.getElementById(objectId)) // W3C DOM
    theObject= document.getElementById(objectId);
  else if (document.all && document.all(objectId)) // MSIE 4 DOM
    theObject= document.all(objectId);
  else if (document.layers && document.layers[objectId]) // NN 4 DOM.. note: this won't find nested layers
    theObject = document.layers[objectId];
  else
    theObject=false;
  return theObject;
}

// 인수 checked는 두번째 radio 배열의 key값 중에 하나를 사용하며
// key값과 같은 값을 주면 그 radio를 체크상태로 초기화 할 수 있다
function drawRadios(bbs_type,checked){
  var MENT_TYPES={
    'norm':['no','inner_norm','inner_level','outer_norm','outer_level'],
    'lect':['no','outer_norm','outer_level'],
    'forum':['no']
  };
  var ment_name={
    'no':'사용안함',
    'inner_norm':'내장일반',
    'inner_level':'내장계층',
    'outer_norm':'외부일반',
    'outer_level':'외부계층'
  };
  var ment_type= MENT_TYPES[bbs_type];

  var p = getStyleObject("nextRdio");
  var ul = document.createElement('ul');

  p.innerHTML ='';  // child를 다지운다
  ul.style.display='inline-block';//'block';
//  p.appendChild(ul);


  for(var i=0;i<ment_type.length;i++){
//    li = document.createElement('li');

//    ul.appendChild(li);

    // try/catch: try works in IE 6 (maybe 7) catch works in ff/ns browsers
    // however, no error is thrown in opera 8 (in the try), but no radio is drawn in opera 8 either.
    try{
      rdo = document.createElement('<input type="radio" name="ment_type" />');
    }catch(err){
      rdo = document.createElement('input');
      rdo.setAttribute('type','radio');
      rdo.setAttribute('name','ment_type');
    }
    rdo.id = 'ment_type'+i;
    rdo.value = ment_type[i];

    lbl = document.createElement('label');
    // set the label in IE..
    lbl.setAttribute('htmlFor', rdo.id);
    // set the label for other browsers
    lbl.setAttribute('for', rdo.id);
    var tn = document.createTextNode(ment_name[ment_type[i]]+' ');
    lbl.appendChild(tn);
    p.appendChild(rdo);
    p.appendChild(lbl);

    if (checked==rdo.value)
      rdo.checked = true;
  }
  return true;
}
</script>
</body>






댓글

추천 글