it-source

jQuery를 사용하여 로드 시 선택한 라디오 옵션을 설정하는 방법

criticalcode 2023. 5. 11. 21:33
반응형

jQuery를 사용하여 로드 시 선택한 라디오 옵션을 설정하는 방법

jQuery를 사용하여 로드 시 라디오 옵션을 설정하는 방법은 무엇입니까?

기본값이 설정되지 않았는지 확인한 다음 기본값을 설정해야 합니다.

예를 들어 다음과 같은 라디오 단추가 있다고 가정합니다.

    <input type='radio' name='gender' value='Male'>
    <input type='radio' name='gender' value='Female'>

라디오를 선택하지 않은 경우 로드 시 "남성" 값이 있는 항목을 선택하려고 했습니다.

    $(function() {
        var $radios = $('input:radio[name=gender]');
        if($radios.is(':checked') === false) {
            $radios.filter('[value=Male]').prop('checked', true);
        }
    });

정기선 한 대는 어떻습니까?

$('input:radio[name="gender"]').filter('[value="Male"]').attr('checked', true);

이 경우 form.reset() 오류가 발생합니다.

$('input:radio[name=gender][value=Male]').attr('checked', true);

하지만 이 방법은 효과가 있습니다.

$('input:radio[name=gender][value=Male]').click();

JQuery에는 실제로 라디오와 확인란에 대해 확인된 상태를 설정하는 두 가지 방법이 있으며 HTML 마크업에서 값 속성을 사용하는지 여부에 따라 달라집니다.

값 속성이 있는 경우:

$("[name=myRadio]").val(["myValue"]);

값 속성이 없는 경우:

$("#myRadio1").prop("checked", true);

추가 세부 정보

첫 번째 경우, 우리는 이름을 사용하여 전체 무선 그룹을 지정하고 JQuery에게 val 함수를 사용하여 선택할 무선을 찾으라고 말합니다.val 함수는 1자리 배열을 사용하고 일치하는 값을 가진 라디오를 찾아 checked=true로 설정합니다.동일한 이름을 가진 다른 항목은 선택 취소됩니다.일치하는 값을 가진 라디오가 없으면 모두 선택 취소됩니다.이름과 값이 같은 라디오가 여러 개 있는 경우 마지막 라디오가 선택되고 다른 라디오는 선택 취소됩니다.

무선에 값 속성을 사용하지 않는 경우 고유 ID를 사용하여 그룹에서 특정 무선을 선택해야 합니다.이 경우 "체크된" 속성을 설정하려면 prop 함수를 사용해야 합니다.많은 사람들이 확인란에 값 속성을 사용하지 않기 때문에 #2는 확인란에 라디오보다 더 적합합니다.또한 동일한 이름을 가진 확인란은 그룹을 형성하지 않으므로 다음 작업을 수행할 수 있습니다.$("[name=myCheckBox").prop("checked", true);확인란을 선택합니다.

http://jsbin.com/OSULAtu/1/edit?html,output 에서 이 코드를 사용할 수 있습니다.

저는 @Amc의 답변이 좋았습니다.저는 필터() 호출을 사용하지 않기 위해 표현이 더 축약될 수 있다는 것을 발견했습니다(@chaiko도 분명히 이것을 알아차렸습니다).또한 prop()는 jQuery v1.6+의 경우 trat()에 비해 사용할 수 있는 방법입니다. 이 주제에 대한 공식 모범 사례는 prop()대한 jQuery 문서를 참조하십시오.

@Paolo Bergantino의 답변과 동일한 입력 태그를 고려합니다.

<input type='radio' name='gender' value='Male'>
<input type='radio' name='gender' value='Female'>

업데이트된 One-liner는 다음과 같은 내용을 읽을 수 있습니다.

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

저는 그 이름이 독특하고 그룹의 모든 라디오가 같은 이름을 가지고 있다고 가정할 수 있다고 생각합니다.그런 다음 jQuery 지원을 다음과 같이 사용할 수 있습니다.

$("[name=gender]").val(["Male"]);

참고: 배열을 전달하는 것은 중요합니다.

조건부 버전:

if (!$("[name=gender]:checked").length) {
    $("[name=gender]").val(["Male"]);
}

기본 JS 솔루션:

 document.querySelector('input[name=gender][value=Female]').checked = true;

http://jsfiddle.net/jzQvH/75/

HTML:

<input type='radio' name='gender' value='Male'> Male
<input type='radio' name='gender' value='Female'>Female

실제로 동적으로 설정하고 수신 데이터에 해당하는 라디오를 선택하면 됩니다.전달된 데이터의 성별 값을 사용하거나 기본값을 사용하는 것입니다.

if(data['gender'] == ''){
 $('input:radio[name="gender"][value="Male"]').prop('checked', true);
}else{
  $('input:radio[name="gender"][value="' + data['gender'] +'"]').prop('checked', true);
};

다음은 위의 방법을 사용한 예입니다.

<div class="ui-field-contain">
<fieldset data-role="controlgroup" data-type="horizontal">    <legend>Choose a pet:</legend>
    <input type="radio" name="radio-choice-2" id="radio-choice-1" value="choice1">
    <label for="radio-choice-1">Cat</label>

    <input type="radio" name="radio-choice-2" id="radio-choice-2" value="choice2">
    <label for="radio-choice-2">Dog</label>

    <input type="radio" name="radio-choice-2" id="radio-choice-3" value="choice3">
    <label for="radio-choice-3">Hamster</label>

    <input type="radio" name="radio-choice-2" id="radio-choice-4" value="choice4">
    <label for="radio-choice-4">Lizard</label>
  </fieldset>
</div>

Javascript에서:

$("[name = 'radio-choice-2'][value='choice3']").prop('checked', true).checkboxradio('refresh');

모델에서 값을 전달하고 값을 기준으로 로드 시 그룹에서 라디오 버튼을 선택하려면 다음을 사용합니다.

질문:

var priority = Model.Priority; //coming for razor model in this case
var allInputIds = "#slider-vertical-" + itemIndex + " fieldset input";

$(allInputIds).val([priority]); //Select at start up

그리고 html:

<div id="@("slider-vertical-"+Model.Id)">
 <fieldset data-role="controlgroup" data-type="horizontal" data-mini="true">
    <input type="radio" name="@("radio-choice-b-"+Model.Id)" id="@("high-"+Model.Id)" value="1" checked="checked">
    <label for="@("high-"+Model.Id)" style="width:100px">@UIStrings.PriorityHighText</label>

    <input type="radio" name="@("radio-choice-b-"+Model.Id)" id="@("medium-"+Model.Id)" value="2">
    <label for="@("medium-"+Model.Id)" style="width:100px">@UIStrings.PriorityMediumText</label>

    <input type="radio" name="@("radio-choice-b-"+Model.Id)" id="@("low-"+Model.Id)" value="3">
    <label for="@("low-"+Model.Id)" style="width:100px">@UIStrings.PriorityLowText</label>
 </fieldset>
</div>

그 모든 것이 필요하지 않습니다.간단하고 오래된 HTML로 원하는 것을 이룰 수 있습니다.기본적으로 다음과 같이 선택할 무선을 선택할 수 있습니다.
<input type='radio' name='gender' checked='true' value='Male'>
페이지가 로드되면 확인됩니다.

 $("form input:[name=gender]").filter('[value=Male]').attr('checked', true);

무선 입력 값을 가져올 때 다음 동작에 주의하십시오.

$('input[name="myRadio"]').change(function(e) { // Select the radio input group

    // This returns the value of the checked radio button
    // which triggered the event.
    console.log( $(this).val() ); 

    // but this will return the first radio button's value,
    // regardless of checked state of the radio group.
    console.log( $('input[name="myRadio"]').val() ); 

});

그렇게$('input[name="myRadio"]').val()라디오 입력의 선택된 값을 반환하지 않습니다. 사용자가 예상할 수도 있습니다. 첫 번째 라디오 단추의 값을 반환합니다.

//만약 당신이 자바스크립트나 백본과 같은 프레임워크에서 그것을 하고 있다면, 당신은 이런 것을 많이 접하게 될 것입니다.

$MobileRadio = $( '#mobileUrlRadio' );

하는 동안에

$MobileRadio.checked = true;

효과가 없을 것입니다

$MobileRadio[0].checked = true;

할 것이다.

당신의 선택자는 위의 다른 남자들도 추천한 대로 될 수 있습니다.

여러 라디오 단추에 사용할 수 있습니다.

$('input:radio[name="Aspirant.Gender"][value='+jsonData.Gender+']').prop('checked', true);

언급URL : https://stackoverflow.com/questions/871063/how-to-set-radio-option-checked-onload-with-jquery

반응형