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

onclick checkbox append checkbox value to URL

本文关键字:复选框 URL onclick      更新时间:2023-09-26

我想使用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;"> 

绑定到复选框上的更改事件。单击时读取当前复选框值,然后读取所有其他相对复选框。用自定义查询字符串附加你的基本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;
        }
    });
});

你可以试试这个。

HTML

<input name="LocType" type="checkbox" value="Office" />
<input name="LocType" type="checkbox" value="Hospital" />
<input name="LocType" type="checkbox" value="Facility" />

JS-

假设你有一个按钮或其他东西,点击它你想创建一个url,所有选中的LocType复选框值都附加到由OR 分隔的url上

var url = "http://mysite/sites/dev/contact-us/Pages/LocationSearchTestPage.aspx?s=bcs_locations";
$('button').click(function(){
   //This will get the array containing values of checked LocType checkboxes
   var checkedLocTypeValues = $('input[name=LocType]:checked').map(function(){
        return this.value;
   });
   //Use Array.join() method to join the array elements by " OR "
   url = url + "&k=" + checkedLocTypeValues.join(" OR ");
   //Now you can use url variable which has all the checked  LocType checkboxes value
}

jQuery map()参考-http://api.jquery.com/jQuery.map/