簡體   English   中英

如何從表格輸入type = radio獲取值?

[英]How to get value from form input type=radio?

<input type="radio" value="0" name="type" checked="yes" />
<label>Type 0</label>
<input type="radio" value="1" name="type" />
<label>Type 1</label>

和js:

var type = this.type.value;
alert(type);

如何解決?

該JS代碼在什么情況下運行? 如果this是有問題的單選按鈕,則this.value將返回該值。

如果您的問題是“如何獲取“類型”組中當前選中的單選按鈕的值?” 那么您可能需要執行以下操作:

function getCheckedRadioValue(radioGroupName) {
   var rads = document.getElementsByName(radioGroupName),
       i;
   for (i=0; i < rads.length; i++)
      if (rads[i].checked)
          return rads[i].value;
   return null; // or undefined, or your preferred default for none checked
}

var checkedValue = getCheckedRadioValue("type");

(使用.querySelector().querySelectorAll()會更容易,但並非所有瀏覽器都支持它們。)

只需使用選擇器。

用jQuery

$("input[name=type]:checked").val();

還是沒有jQuery:

document.querySelector("input[name=type]:checked").value;

只需使用this.value而不是this.type.value

this.value將選擇與輸入的value屬性關聯的value (滿口)。

使用jQuery,您可以這樣做

   $(function() {
        $(".rad").click(
        function() {
             alert(this.value);
        });
    });

看到這個JSFiddle

暫無
暫無

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

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