HTML DOM Input Radio name 屬性
HTML DOM Input radio name 屬性用於設定或返回 input radio 欄位的 name 屬性。name 屬性在將表單資料提交至伺服器之後識別表單資料時具有幫助作用。JavaScript 還可以使用 name 屬性來引用表單元素,以便稍後進行處理。
語法
以下是語法 −
設定 name 屬性。
radioObject.name = name
在此,name 用於指定單選按鈕名稱。
示例
讓我們看一個 radio name 屬性的示例 −
<!DOCTYPE html> <html> <body> <h1>Input radio name Property</h1> <form id="FORM1"> FRUIT: <input type="radio" name="fruits" id="Orange">Orange </form> <p>Change the name of the above radio button by clicking the below button</p> <button type=”button” onclick="changeName()">CHANGE NAME</button> <p id="Sample"></p> <script> function changeName() { document.getElementById("Orange").name ="colors" ; document.getElementById("Sample").innerHTML = "Radio button name is now colors"; } </script> </body> </html>
輸出
這將產生以下輸出 −
單擊 CHANGE NAME 按鈕時 −
在以上示例中 −
我們首先在 form 中建立一個 input 元素,其 type="radio",name="fruits",id="Orange" −
<form> FRUIT: <input type="radio" name="fruits" id="Orange">Orange </form>
然後我們建立一個 CHANGE NAME 按鈕,當用戶單擊時將執行 changeName() 方法 −
<button type=”button” onclick="changeName()">CHANGE NAME</button>
changeName() 方法使用 getElementById() 方法來獲取輸入欄位型別為單選並且設定其名稱屬性值為“colors”。然後,此更改反映在 ID 為“Sample”的段落中,並使用其 innerHTML 屬性顯示預期的文字
function changeName() { document.getElementById("Orange").name ="colors" ; document.getElementById("Sample").innerHTML = "Radio button name is now colors"; }
廣告