javascript - onclick 复选框将复选框值附加到 URL

标签 javascript jquery checkbox onclick query-string

我想使用 jquery 而不是内联来实现这个,但它不起作用,内联工作正常。我想使用 jquery 的另一个原因是,如果用户选择多个复选框,则 url 应该附加已有的内容 + 或“第二个复选框值”,如下所示: “http://mysite/sites/dev/contact-us/Pages/LocationSearchTestPage.aspx?s=bcs_locations&k=办公室或医院” OR 前面和后面的空格没问题。 我怎样才能实现这个目标?有人可以帮我吗?

 Offices<input name="LocType" type="checkbox"  
value="Office" onclick="window.location='http://mysite/sites/dev/contact-us/Pages/LocationSearchTestPage.aspx?s=bcs_locations&k=Office'; return true;"> &#160;
     Hospitals<input name="LocType" type="checkbox"  
value="Hospital" onclick="window.location='http://mysite/sites/dev/contact-us/Pages/LocationSearchTestPage.aspx?s=bcs_locations&k=Hospital'; return true;"> &#160;
     Facilities<input name="LocType" type="checkbox"  
value="Facility" onclick="window.location='http://mysite/sites/dev/contact-us/Pages/LocationSearchTestPage.aspx?s=bcs_locations&k=Facility'; return true;"> 

最佳答案

绑定(bind)到复选框上的更改事件。单击时读取当前复选框值,然后读取所有其他相关复选框。将您的基本 url 附加到您的自定义查询字符串,然后开始疯狂吧。 :)

这尚未经过测试,但希望这是一个很好的起点。

var baseUrl = 'http://mysite/sites/dev/contact-us/Pages/LocationSearchTestPage.aspx?s=bcs_locations&k=';

$(document).ready(function () {

    // listen to change event (customize selector to your needs)
    $('input[type=checkbox]').change(function (e) {

        e.preventDefault();

        if ($(this).is(':checked')) {

            // read in value
            var queryString = $(this).val();

            // loop through siblings (customize selector to your needs)
            var s = $(this).siblings();
            $.each(s, function () {

                // see if checked
                if ($(this).is(':checked')) {

                    // append value
                    queryString += ' OR ' + $(this).val();
                }
            });

            // jump to url
            window.location = baseUrl + queryString;
        }
    });

});

关于javascript - onclick 复选框将复选框值附加到 URL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9441374/

相关文章:

javascript - 我想限制 3 个以上的选择框只选择一个 <option> 一次 - 我做错了什么?

Javascript 在事件时用函数替换 div 的内容

javascript - jquery 多个复选框启用文本字段

php - PHP 和 MYSQL 的复选框

javascript - 如何编写 Rails 代码来处理来自客户端 (JS) 的 Phonegap 开发请求

javascript - 在浏览器中显示实时数据,无需刷新

javascript - 在 VueJS 中观察元素的高度

javascript - 从 iframe 访问和更改父页面(使用 jquery)

php - 复选框总是返回一个值

javascript - Jquery - 用值替换字符串中选定的html标签