2017-04-09 141 views
0

我想在選中某個複選框時向URL添加文本。 我以爲我只是要爲每個複選框添加多個if語句,但是這不起作用。在一個函數中使用多個if語句?

$("#button1").on("click", function(){ 
    url = ""; 
    if (auswahl_index1[0].checked) { 
     url = page + option_0; 
    } 
    if (auswahl_index2[0].checked) { 
     url = page + option_1; 
    } 
    window.location.href = url; 
}); 

var auswahl_index1 = document.getElementById('yes1'); 
 
var auswahl_index2 = document.getElementById('no1'); 
 
var auswahl_index1 = document.getElementById('yes2'); 
 
var auswahl_index2 = document.getElementById('no2'); 
 
var page = "http://stackoverflow.com"; 
 
var url = page; 
 

 
$("#button1").on("click", function(){ 
 
\t url = ""; 
 
\t if (auswahl_index1[0].checked) { 
 
\t \t url = page + "test1"; 
 
\t } 
 
\t if (auswahl_index2[0].checked) { 
 
\t \t url = page + "test2"; 
 
    } 
 
    if (auswahl_index3[0].checked) { 
 
\t \t url = page + "test3"; 
 
\t } 
 
\t if (auswahl_index4[0].checked) { 
 
\t \t url = page + "test4"; 
 
    } 
 
    \t window.location.href = url; 
 
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
    <input type="radio" name="rdo1" id="yes1"/> 
 
    <input type="radio" name="rdo1" id="no1"/> 
 
    <input type="radio" name="rdo2" id="yes2"/> 
 
    <input type="radio" name="rdo2" id="no2"/> 
 
<button type="button" id="button1">Button</button>

我tryed研究還能做什麼,所有我發現使用「否則,如果」在第二條語句。 Hovever既不會工作,既然這將意味着它只會激活,如果第一個聲明是錯誤的,但兩者同時應該能夠添加到網址。

很抱歉,如果這是一個愚蠢的問題,我只是真正的新jQuery和我不可能找到googleing我的任何問題。 如果您需要更多關於我的問題的信息,請詢問:)

+0

在這個https://api.jquery.com/checked-selector/ – Tareq

+2

看看*「表示沒有工作「*不是一個適當的問題陳述。爲[mcve]提供足夠的html和代碼。我們不能告訴你的變量代表 – charlietfl

+0

謝謝你,我添加了一些上下文的代碼片段 – KeBom

回答

0

我知道在過去我遇到過使用複選框.check的問題。

.prop似乎解決了很多的問題。

如果不是100%的.prop( '檢查', '檢查')或.prop( '檢查')嘗試要麼。

也記在腦海中:如果他們複選框,這意味着他們的多次進行檢查。改用單選按鈕。

var auswahl_index1 = document.getElementsByClassName('yes1'); 
var auswahl_index2 = document.getElementsByClassName('no1'); 


$("#button1").on("click", function(){ 
    url = ""; 
    if (auswahl_index1.prop('checked')) { 
     url = page + option_0; 
    }else if(auswahl_index2.prop('checked')) { 
     url = page + option_1; 
    } else { 
     console.log('say something'); 
     return null; 
    } 
    window.location.href = url; 
}); 

你可以做的替代功能,添加同一類每個複選框:

$('.class-added').change(function(){ 
    url = ""; 
    if (auswahl_index1.prop('checked')) { 
     url = page + option_0; 
    } 
    else if (auswahl_index2.prop('checked') { 
     url = page + option_1; 
    } 
    window.location.href = url; 
}); 
+0

謝謝,我會試試這個。 我實際上已經在使用單選按鈕。 – KeBom