이상하게 라디오 관련 처리는 매번 할 때마다 바로바로 기억이 안나 정리해둔다.

 

[HTML]

1
2
3
4
5
6
7
8
9
10
11
12
13
14
<ul>
    <li>
        <input type="radio" id="type" name="type" value="1"><label for="type1">radio1</label>
        <input type="text" id="type_val" name="type_val" />
    </li>
    <li>
        <input type="radio" id="type" name="type" value="2"><label for="type2">radio2</label>
        <input type="text" id="type_val" name="type_val" />
    </li>
    <li>
        <input type="radio" id="type" name="type" value="3"><label for="type3">radio3</label>
        <input type="text" id="type_val" name="type_val" />
    </li>
</ul>
cs

 

[script]

1
2
3
4
5
6
7
8
9
$('input[type=radio][name=type]').change(function(){
    var arr = $('input[type=radio][name=type]');
    console.log($(this).val())
    for(var i=0; i<arr.length; i++){
        if($(this).val() != $(arr[i]).val()){
            $(arr[i]).siblings('input').val("");
        }
    }
});
cs

2번라인의 arr 은 radio 엘리먼트 배열이 들어가게 된다.

반복문을 돌려 this (현재 선택된 radio) 의 value 와 같지 않은 input value 는 비워준다.

※ 변수를 $() 로 감싸주면 javascript 변수가 jQuery 변수로 변환된다.

 

※ radio 버튼 강제 선택시키기

$("input:radio[name=radioGrp]:radio[value='U']").prop("checked", true);

참고

 

반응형

+ Recent posts