Modify onclick function with jQuery
- by Chris Barr
I've got a button that has an onclick event in it, which was set on the back end from .NET. Beside it is a checkbox
<button class="img_button" onclick="if(buttonLoader(this)){WebForm_DoPostBackWithOptions(new WebForm_PostBackOptions('uxBtnRelease', '', true, '', 'somepage.aspx?oupid=5&fp=true', false, true))} return false;" type="button">Release</button>
<input type="checkbox" checked="checked" id="myCheckbox">
When the checkbox is clicked, needs to change the value of the query string in the URL inside the onclick function of the button.
So far I have this, and the idea is right, but I keep getting errors when it's run: "Uncaught SyntaxError: Unexpected token ILLEGAL"
var defaultReleaseOnClick=null;
$("#myCheckbox").click(function(){
var $releaseBtn = $(".img_button");
if(defaultReleaseOnClick==null) defaultReleaseOnClick=$releaseBtn.attr("onclick");
var newOnClickString = defaultReleaseOnClick.toString().replace(/&fp=[a-z]+'/i,"&fp="+this.checked);
$releaseBtn.removeAttr("onclick").click(eval(newOnClickString));
});
I know it seems kinda hacky to convert the function to a string, do a replacement, and then try to convert it back to a function, but I don't know any other way to do it.
Any ideas?
I've set up a demo here: http://jsbin.com/asiwu4/edit