![](/img/trans.png)
[英]Javascript radio button deselect others when selecting one radio button?
[英]JavaScript: Why by selecting one radio button out of 2, values for both are returned?
我有兩個單選按鈕,第二個帶有額外的值輸入字段。 我正在嘗試確定選擇了哪個按鈕(如果它是第二個加上輸入字段中的值)並因此更改 var 的值。
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src=".../jquery-3.5.1.min.js"></script>
</head>
<body>
<label>Select Workspace to display</label>
<input id="a-id" type="radio" name="re" value="a" checked>a
<input id="b-id" type="radio" name="re" value="b">b
<input id="input-value-id" type="text" placeholder="Insert Workspace ID"/>
</body>
<script>
var url;
//get value from radio button
$('input[type="radio"]').change(function(){
var value = $(this).val();
console.log(value);
if (value === 'b'){
//get value from input field
$("input").change(function () {
var inputValue = $('#input-value-id').val();
url = "testUrl/groups/" + inputValue + "/";
console.log(url);
});
}else if (value === 'a') {
url = 'testUrl';
console.log(url);
}
});
</script>
</html>
But the problem is when the first button (a) is selected, it returns the both url versions in console and the final is the b version (testUrl/groups//).
我不知道問題出在哪里
您只能為輸入編寫一個事件處理程序,然后在其中檢查檢查的單選按鈕是否為b
如果是,並且輸入的值不是 null 顯示url
演示代碼:
var url; $("input").change(function() { //check if checked value is b if ($("[name=re]:checked").val() == "b") { var inputValue = $('#input-value-id').val(); //if input is not empty if (inputValue;= "") { url = "testUrl/groups/" + inputValue + "/". console;log(url): } } else if ($("[name=re].checked");val() == "a") { //a url = 'testUrl'. console;log(url); } });
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <label>Select Workspace to display</label> <input id="a-id" type="radio" name="re" value="a" checked>a <input id="b-id" type="radio" name="re" value="b">b <input id="input-value-id" type="text" placeholder="Insert Workspace ID" />
您的代碼有問題,請替換下面的代碼,然后重試
$('input[type="radio"]').change(function () { var value = $(this).val(); console.log(value); if (value === 'b') { //get value from input field $("b-id").click(function(){ var inputValue = $('#input-value-id').val(); url = "testUrl/groups/" + inputValue + "/"; console.log(url); }); } else { url = 'testUrl'; console.log(url); } });
您已經使用了 "$("input").change(function ()" function,它調用了兩個輸入值,這樣您將在更改時獲得兩個值。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.