[英]Javascript - ading a checked radio input on a variable after submitting the form
我正在嘗試創建一個石頭剪刀布游戲。
用戶選擇必須使用帶有單選按鈕的表單填充為變量。
當我單擊提交時,我希望選中單選按鈕以作為變量傳遞。 我怎樣才能得到用戶的選擇?
<div id="global">
<h1>Jeu Pierre Feuille Ciseau</h1>
<h3>Choisissez Pierre, Feuille ou Ciseaux:</h3>
<div>
<input type="radio" id="pierre" name="game" value="pierre" checked>
<label for="pierre">Pierre</label>
</div>
<div>
<input type="radio" id="feuille" name="game" value="feuille">
<label for="pierre">Feuille</label>
</div>
<div>
<input type="radio" id="ciseaux" name="game" value="ciseaux">
<label for="pierre">Ciseaux</label>
</div>
<button id="submit">Submit</button>
</div>
<script type="text/javascript">
window.document.getElementById("submit").onclick = function(){
}
</script>
使用 jQuery 並使用$("input[name='game']:checked").val()
會很簡單
$(document).ready(function(){ $("input[type='button']").click(function(){ var radioValue = $("input[name='game']:checked").val(); if(radioValue){ alert("Value - " + radioValue); } }); });
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div id="global"> <h1>Jeu Pierre Feuille Ciseau</h1> <h3>Choisissez Pierre, Feuille ou Ciseaux:</h3> <div> <input type="radio" id="pierre" name="game" value="pierre" checked> <label for="pierre">Pierre</label> </div> <div> <input type="radio" id="feuille" name="game" value="feuille"> <label for="pierre">Feuille</label> </div> <div> <input type="radio" id="ciseaux" name="game" value="ciseaux"> <label for="pierre">Ciseaux</label> </div> <input type="button" value="Submit"> </div>
您可以通過遍歷單選按鈕並找到已檢查的元素來完成此操作。 從那時起,您可以隨心所欲地使用價值
<div id="global">
<h1>Jeu Pierre Feuille Ciseau</h1>
<h3>Choisissez Pierre, Feuille ou Ciseaux:</h3>
<div>
<input type="radio" id="pierre" name="game" value="pierre" checked>
<label for="pierre">Pierre</label>
</div>
<div>
<input type="radio" id="feuille" name="game" value="feuille">
<label for="pierre">Feuille</label>
</div>
<div>
<input type="radio" id="ciseaux" name="game" value="ciseaux">
<label for="pierre">Ciseaux</label>
</div>
<button id="submit">Submit</button>
window.document.getElementById("submit").onclick = function(){
var radioButtons = document.getElementsByName('game');
for (var i = 0, length = radioButtons.length; i < length; i++){
if (radioButtons[i].checked){
// do whatever you want with the checked radio
alert(radioButtons[i].value);
// only one radio button can be checked so break the loop
break;
}
}
}
這是一個可以試用的代碼筆: https://codepen.io/jpcobalt/pen/qBBqWyd
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.