簡體   English   中英

檢查先前單擊的單選按鈕

[英]Check previously clicked radio button

我有一個在不同組中具有多個單選按鈕的表單。 例如類別車輛有兩個單選按鈕

  1. 2輪車
  2. 四輪車

與其他類別相同,有2-2個單選按鈕。

我想做的是,當我從2輪車中檢查4輪車時,我彈出警告消息,確定要切換,如果是,那么確定,但是不,我想再次檢查2輪車單選按鈕。 我不能從id做到這一點,因為我也必須在其他字段上做到這一點。

<input type="radio"/>

您的問題不是很清楚,但是據我了解,我想您想要的是:

$(document).ready(function(){
$('#submit_button').click(function() {
    if (!$("input[@name='radioName']:checked").val()) {
     alert('Nothing is checked!');
    return false;
    }
else {
  alert('One of the radio buttons is checked!');
}
 });
 });

並為所有無線電輸入添加相同的名稱標簽:

<input type="radio" name="radioName"/>

這可能是您要實現的目標:

var old_input = $('input[name="wheeler"]:checked');
$('input[name="wheeler"]').change(function(e) {
    console.log(e);
    if (
        old_input.next().text() == '2 Wheeler' &&
        $(this).next().text() == '4 Wheeler'
    ) {
        if (confirm('Are you sure you want to change?')) {
            old_input = $(this);
        }
        else {
            this.checked = 0;
            old_input.get()[0].checked = 1;
        }
    }
    else {
        old_input = $(this);
    }
});

http://jsfiddle.net/pQpk7/

我認為您正在尋找的http://jsfiddle.net/7rF3d/首次選中單選按鈕時,沒有任何反應。 當某人檢查另一個人時,首先會提示他進行確認。 如果用戶取消,將恢復舊的已檢查的收音機。

var lastChecked;

$("input[type=radio]").click(function() {

    if(typeof(lastChecked) != "undefined" && !confirm("are you sure?")) {

        $("input[type=radio]:checked").attr("checked", "false");

        $(lastChecked).prop("checked", true);

    } else {

        lastChecked = $('input[type=radio]:checked');

    }

});

由於jQuery沒有在問題中標記,因此這是一種純JS方法。 伙計們,認真的嘗試在問題中甚至沒有標記的情況下嘗試放棄建議jQuery解決方案。

您可以通過使用click事件並在選中至少一個單選按鈕的情況下返回false來實現此目的,然后對window.confirm的回答為false,這將阻止它按預期選擇新按鈕。

var oneChecked=false;
var elem=document.getElementsByName("wheeler");

for (var i=0;i<elem.length;i++) {
   elem[i].onclick=function(e) {
       if (oneChecked && !window.confirm("Are you sure to switch?")) {
           return false;
       } else {
           oneChecked=true;
       }
   }
}

小提琴

暫無
暫無

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

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