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

时间:2012-02-25 04:56:33

标签: javascript jquery checkbox onclick query-string

我想使用jquery而不是内联来实现它,但它不工作,内联工作正常。我想使用jquery的另一个原因是,如果用户选择了多个复选框,则url应该附加已经存在的任何内容+ OR'2nd CheckBox Value',如下所示: “http://mysite/sites/dev/contact-us/Pages/LocationSearchTestPage.aspx?s = bcs_locations& k = Office OR Hospital” 面向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;"> 

2 个答案:

答案 0 :(得分:2)

在复选框上绑定到更改事件。单击时,读取当前复选框值,然后读取所有其他相对复选框。使用您的自定义查询字符串附加您的基本网址并发疯。 :)

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

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;
        }
    });

});

答案 1 :(得分:0)

你可以试试这个。

HTML

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

JS

假设您有一个按钮或其他内容,您要创建一个网址,其中所有选中的LocType复选框值附加到由OR分隔的网址

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/

相关问题