簡體   English   中英

如何使用 jQuery 檢查單選按鈕?

[英]How to check a radio button with jQuery?

我嘗試使用 jQuery 檢查單選按鈕。 這是我的代碼:

<form>
    <div id='type'>
        <input type='radio' id='radio_1' name='type' value='1' />
        <input type='radio' id='radio_2' name='type' value='2' />
        <input type='radio' id='radio_3' name='type' value='3' /> 
    </div>
</form>

對於等於或高於 (>=) 1.6 的 jQuery 版本,請使用:

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

對於 (<) 1.6 之前的版本,請使用:

$("#radio_1").attr('checked', 'checked');

提示:之后您可能還想在單選按鈕上調用click()change() 有關更多信息,請參閱評論。

嘗試這個。

在這個例子中,我用它的輸入名稱和值來定位它

$("input[name=background][value='some value']").prop("checked",true);

很高興知道:在多字值的情況下,它也會因為撇號而起作用。

在 jQuery 1.6 中添加的另一個函數 prop() 用於相同的目的。

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

簡短易讀的選項:

$("#radio_1").is(":checked")

它返回 true 或 false,因此您可以在“if”語句中使用它。

嘗試這個。

要使用檢查單選按鈕,請使用它。

$('input[name=type][value=2]').attr('checked', true); 

或者

$('input[name=type][value=2]').attr('checked', 'checked');

或者

$('input[name=type][value=2]').prop('checked', 'checked');

要使用ID檢查單選按鈕,請使用它。

$('#radio_1').attr('checked','checked');

或者

$('#radio_1').prop('checked','checked');

嘗試這個:

$("input[name=type]").val(['1']);

http://jsfiddle.net/nwo706xw/

$.prop方式更好:

$(document).ready(function () {                            
    $("#radio_1").prop('checked', true);        
});

你可以像下面這樣測試它:

$(document).ready(function () {                            
    $("#radio_1, #radio_2", "#radio_3").change(function () {
        if ($("#radio_1").is(":checked")) {
            $('#div1').show();
        }
        else if ($("#radio_2").is(":checked")) {
            $('#div2').show();
        }
        else 
            $('#div3').show();
    });        
});

使用prop()方法

在此處輸入圖片說明

鏈接

<p>
    <h5>Radio Selection</h5>

    <label>
        <input type="radio" name="myRadio" value="1"> Option 1
    </label>
    <label>
        <input type="radio" name="myRadio" value="2"> Option 2
    </label>
    <label>
        <input type="radio" name="myRadio" value="3"> Option 3
    </label>
</p>

<p>
    <button>Check Radio Option 2</button>
</p>


<script>
    $(function () {

        $("button").click(function () {
            $("input:radio[value='2']").prop('checked',true);
        });

    });
</script>

令人驚訝的是,盡管有評論,但最受歡迎和接受的答案卻忽略了觸發適當的事件。 確保調用.change() ,否則所有“on change”綁定都將忽略此事件。

$("#radio_1").prop("checked", true).change();

你必須要做

jQuery("#radio_1").attr('checked', 'checked');

那是 HTML 屬性

如果屬性name不起作用,請不要忘記id仍然存在。 這個答案適用於想要在此處定位id人。

$('input[id=element_id][value=element_value]').prop("checked",true);

因為屬性name對我不起作用。 確保不要用雙引號/單引號將idname括起來。

干杯!

我們應該告訴它是一個radio按鈕。所以請嘗試使用以下代碼。

$("input[type='radio'][name='userRadionButtonName']").prop('checked', true);

是的,它對我來說就像這樣:

$("#radio_1").attr('checked', 'checked');

嘗試這個

$(document).ready(function(){
    $("input[name='type']:radio").change(function(){
        if($(this).val() == '1')
        {
          // do something
        }
        else if($(this).val() == '2')
        {
          // do something
        }
        else if($(this).val() == '3')
        {
          // do something
        }
    });
});
$("input[name=inputname]:radio").click(function() {
    if($(this).attr("value")=="yes") {
        $(".inputclassname").show();
    }
    if($(this).attr("value")=="no") {
        $(".inputclassname").hide();
    }
});

獲取價值:

$("[name='type'][checked]").attr("value");

設定值:

$(this).attr({"checked":true}).prop({"checked":true});

選中單選按鈕單擊添加屬性:

$("[name='type']").click(function(){
  $("[name='type']").removeAttr("checked");
  $(this).attr({"checked":true}).prop({"checked":true});
});

用例子試試這個

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="myForm">
<input type="radio" name="radio" value="first"/> 1 <br/>
<input type="radio" name="radio" value="second"/> 2 <br/>
</form>


<script>
$(document).ready(function () {
    $('#myForm').on('click', function () {
        var value = $("[name=radio]:checked").val();

        alert(value);
    })
});
</script>

以防萬一有人在使用 jQuery UI 時試圖實現這一點,您還需要刷新 UI 復選框對象以反映更新后的值:

$("#option2").prop("checked", true); // Check id option2
$("input[name='radio_options']").button("refresh"); // Refresh button set

我使用這個代碼:

我為英語感到抱歉。

 var $j = jQuery.noConflict(); $j(function() { // add handler $j('#radio-1, #radio-2').click(function(){ // find all checked and cancel checked $j('input:radio:checked').prop('checked', false); // this radio add cheked $j(this).prop('checked', true); }); });
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <fieldset class="section"> <legend>Radio buttons</legend> <label> <input type="radio" id="radio-1" checked> Option one is this and that&mdash;be sure to include why it's great </label> <br> <label> <input type="radio" id="radio-2"> Option two can be something else </label> </fieldset>

嘗試這個

var isChecked = $("#radio_1")[0].checked;
function rbcitiSelction(e) {
     debugger
    $('#trpersonalemail').hide();
    $('#trcitiemail').show();
}

function rbpersSelction(e) {
    var personalEmail = $(e).val();
    $('#trpersonalemail').show();
    $('#trcitiemail').hide();
}

$(function() {  
    $("#citiEmail").prop("checked", true)
});

我得到了一些相關的例子來增強,如果我想添加一個新條件,比如說,如果我想在我點擊項目狀態值后隱藏配色方案,除了攤鋪機和鋪路板。

示例在這里:

$(function () {
    $('#CostAnalysis input[type=radio]').click(function () {
        var value = $(this).val();

        if (value == "Supply & Lay") {
            $('#ul-suplay').empty();
            $('#ul-suplay').append('<fieldset data-role="controlgroup"> \

http://jsfiddle.net/m7hg2p94/4/

我剛剛遇到了類似的問題,一個簡單的解決方案是使用:

.click()

如果您在調用函數后刷新收音機,任何其他解決方案都將起作用。

此外,您可以檢查元素是否被選中:

if ($('.myCheckbox').attr('checked'))
{
   //do others stuff
}
else
{
   //do others stuff
}

您可以檢查未檢查的元素:

$('.myCheckbox').attr('checked',true) //Standards way

您也可以通過這種方式取消選中:

$('.myCheckbox').removeAttr('checked')

您可以檢查單選按鈕:

對於等於或高於 (>=) 1.6 的 jQuery 版本,請使用:

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

對於 (<) 1.6 之前的版本,請使用:

$("#radio_1").attr('checked', 'checked');
$("#radio_1").attr('checked', true);
//or
$("#radio_1").attr('checked', 'checked');

我使用了jquery-1.11.3.js

基本啟用和禁用

Tips 1:(單選按鈕類型常見的禁用和啟用)

$("input[type=radio]").attr('disabled', false);
$("input[type=radio]").attr('disabled', true); 

Tips 2:( ID選擇器使用prop()或attr())

$("#paytmradio").prop("checked", true);
$("#sbiradio").prop("checked", false);

jQuery("#paytmradio").attr('checked', 'checked'); // or true this won't work
jQuery("#sbiradio").attr('checked', false);

Tips 3:( Class selector Using prop() or arrt())

$(".paytm").prop("checked", true);
$(".sbi").prop("checked", false);

jQuery(".paytm").attr('checked', 'checked'); // or true
jQuery(".sbi").attr('checked', false);

其他提示

$("#paytmradio").is(":checked")   // Checking is checked or not
$(':radio:not(:checked)').attr('disabled', true); // All not check radio button disabled

$('input[name=payment_type][value=1]').attr('checked', 'checked'); //input type via checked
 $("input:checked", "#paytmradio").val() // get the checked value

索引.html

<div class="col-md-6">      
    <label class="control-label" for="paymenttype">Payment Type <span style="color:red">*</span></label>
    <div id="paymenttype" class="form-group" style="padding-top: inherit;">
        <label class="radio-inline" class="form-control"><input  type="radio" id="paytmradio"  class="paytm" name="paymenttype" value="1" onclick="document.getElementById('paymentFrm').action='paytmTest.php';">PayTM</label>
        <label class="radio-inline" class="form-control"><input  type="radio" id="sbiradio" class="sbi" name="paymenttype" value="2" onclick="document.getElementById('paymentFrm').action='sbiTest.php';">SBI ePAY</label>
    </div>
</div>

這個答案要感謝 Paul LeBeau 在評論中 我想我會把它寫成一個正確的答案,因為令人驚訝的是沒有一個。

唯一對我有用的東西(jQuery 1.12.4,Chrome 86)是:

$(".js-my-radio-button").trigger("click");

這完成了我想要的一切 - 更改哪個單選按鈕看起來被選中(視覺和編程)並觸發事件,例如單選按鈕上的change

只是按照其他答案的建議設置“已檢查”屬性不會更改為我選擇的單選按鈕。

嘗試這個

 $("input:checked", "#radioButton").val()

如果選中返回True如果未選中返回False

jQuery v1.10.1

嘗試這個:

$(document).ready(function(){
  $("#Id").prop("checked", true).checkboxradio('refresh');
});

有時上述解決方案不起作用,那么您可以嘗試以下方法:

jQuery.uniform.update(jQuery("#yourElementID").attr('checked',true));
jQuery.uniform.update(jQuery("#yourElementID").attr('checked',false));

您可以嘗試的另一種方法是:

jQuery("input:radio[name=yourElementName]:nth(0)").attr('checked',true);

我嘗試使用jQuery檢查單選按鈕。 這是我的代碼:

<form>
    <div id='type'>
        <input type='radio' id='radio_1' name='type' value='1' />
        <input type='radio' id='radio_2' name='type' value='2' />
        <input type='radio' id='radio_3' name='type' value='3' /> 
    </div>
</form>

和JavaScript:

jQuery("#radio_1").attr('checked', true);

不起作用:

jQuery("input[value='1']").attr('checked', true);

不起作用:

jQuery('input:radio[name="type"]').filter('[value="1"]').attr('checked', true);

不起作用:

你還有其他主意嗎? 我想念什么?

如果您不希望像jQuery這樣的大型庫包含這么簡單的東西,這里是使用內置DOM方法的替代解決方案:

 // Check checkbox by id: document.querySelector('#radio_1').checked = true; // Check checkbox by value: document.querySelector('#type > [value="1"]').checked = true; // If this is the only input with a value of 1 on the page, you can leave out the #type > document.querySelector('[value="1"]').checked = true; 
 <form> <div id='type'> <input type='radio' id='radio_1' name='type' value='1' /> <input type='radio' id='radio_2' name='type' value='2' /> <input type='radio' id='radio_3' name='type' value='3' /> </div> </form> 

最短的<\/h1>
radio_1.checked<\/code> <\/pre>

 checkBtn.onclick = e=> { console.log( radio_1.checked ); }<\/code><\/pre>
 Select first radio and click button <!-- Question html --> <form> <div id='type'> <input type='radio' id='radio_1' name='type' value='1' \/> <input type='radio' id='radio_2' name='type' value='2' \/> <input type='radio' id='radio_3' name='type' value='3' \/> 
<\/form> <!-- Test html --> <button id="checkBtn">Check<\/button><\/code><\/pre>

"

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM