onclick checkbox event

吃可爱长大的小学妹 提交于 2019-12-13 05:44:28

问题


All I am trying to do is onclick of checkbox, append its value to the URL and redirect..How do I do this??

$(document).ready(function() {   
    var url = 'http://mysite.com/results.aspx';   
        $('.LocType').click (function ()
            {
                var thisCheck = $(this);
            if (thischeck.is (':checked'))
             {
            // Do stuff
             window.location.href = "http://www.yahoo.com";  

             }
        });
}); 

<div class="MyOptions"> 
    Hospitals<input class="LocType" type="checkbox" value="Hospital"/> &#160;  
    Offices<input class="LocType" type="checkbox" value="Office"/> &#160;  
    Facilities<input class="LocType" type="checkbox" value="Facility"/> 
</div> 

回答1:


That's really not a good UI design - users do not expect navigation to occur via checkboxes - but here's the code you want:

$('.LocType').click (function () {
   if (this.checked) {
       // Do stuff
       window.location.href = "http://www.yahoo.com?paramNameHere=" + this.value;
   }
});

You don't need $(this) inside the function because this is enough to just check the checked state and get the value.

You didn't say what the resulting URL should look like, so I've just appended the value with a generic paramNameHere parameter.




回答2:


if you set up your function to recive a parameter javascript would give you an event that have the ellement that fire the event, you cuold do archive this whit the next code:

$('.LocType').click (function (e) {
   if (this.checked) {
       // Do stuff
       window.location.href = "http://www.yahoo.com" + e.target.value;
      //e.target is the element that fire up the event
   }
});


来源:https://stackoverflow.com/questions/9439587/onclick-checkbox-event

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!