我使用複選框和JavaScript來過濾搜索結果。 其實我使用此代碼alterate url和獲得的結果,但我會得到本格式的結果:A = A1,A2 & B = B1,B2 & C = C1,C2代替A = A1 & A = A2 & B = B1 $ B = B2 & C = C1 & C = C2Javascript將值傳遞給網址
這是代碼
<input type="checkbox" name="a" value="A1" /> A1 Value
<input type="checkbox" name="a" value="A2" /> A2 Value
<input type="checkbox" name="b" value="B1" /> B1 Value
<input type="checkbox" name="b" value="B2" /> B2 Value
<input type="checkbox" name="c" value="C1" /> C1 Value
<input type="checkbox" name="c" value="C2" /> C2 Value
<input type="button" value="Test" onclick="javascript:checkbox_test()">
<script type="text/javascript">
// function will loop through all input tags and create
// url string from checked checkboxes
function checkbox_test() {
var counter = 0, // counter for checked checkboxes
i = 0, // loop variable
url = '', // final url string
// get a collection of objects with the specified 'input' TAGNAME
input_obj = document.getElementsByTagName('input');
// loop through all collected objects
for (i = 0; i < input_obj.length; i++) {
// if input object is checkbox and checkbox is checked then ...
if (input_obj[i].type === 'checkbox' && input_obj[i].checked === true) {
// ... increase counter and concatenate checkbox value to the url string
counter++;
url = url + '&c=' + input_obj[i].value;
}
}
// display url string or message if there is no checked checkboxes
if (counter > 0) {
// remove first "&" from the generated url string
url = url.substr(1);
// display final url string
alert(url);
// or you can send checkbox values
// window.location.href = 'my_page.php?' + url;
}
else {
alert('There is no checked checkbox');
}
}
</script>