unable to set href inside click event of Jquery - asp.net

Hi I am trying to set href using Jquery inside click event of RadioButtonList but that doesnt work If I take the same code to document.ready event it works fine but not in click event. Please advice.
$(document).ready(function() {
url = "Results.aspx?latitude=" +latitude + "&Longitude=" + longitude;
$("a[href='http://www.google.com/']").attr("href", url); // this works..
}
$('.rbl input').click(function() {
id = $(this).parent().children("input").val();
url = "Results.aspx?latitude=" + latitude + "&Longitude=" + longitude + "&ServiceCenterProductTypeId=" + id;
//alert(url);
$("a[href='http://www.google.com/']").attr("href", url); //this doesnt work....
});
});

Looks to me like you have an extra closing curly bracket } after this line:
$("a[href='http://www.google.com/']").attr("href", url); // this works..

You (probably) have the AutoPostBack property set to true, causing a postback to the server which reloads the entire page.
Therefore, your changes in Javascript are overwritten by the postback.

Related

Getting JS Error (for - event.srcElement.id) in WebForm

I am building a dynamic user control (ascx) which contains a placeholder. Inside the placeholder, there will be n tables. Inside each table, in one of the cells i have the link button as below.
HyperLink lnkButton = new HyperLink();
lnkButton.ID = "lnkButton_" + ID.ToString();
lnkButton.Text = tstText;
lnkButton.NavigateUrl = "javascript:JS_Click();";
I have to call a JS function on the link button click (no postback).
In the JS function, i have to get the id of the control that invoked that JS function. In this case, it will be link button. I am writing the below code in the JS Function:
var ctrl = event.srcElement.id;
but i am getting 'Object Required' error in javaScript.
Few other things: This user control will be loaded in default.aspx page and the JS Function i am writing in default.aspx.
I am not sure why this is not working. I am using IE6/7, VS 2005. Is there any other function or way available to get the srcElement.id. Please help.
Try passing this along when you invoke the method
lnkButton.NavigateUrl = "javascript:JS_Click(this);";
then you can write this in your JS_Click event
function JS_Click(obj)
{
alert("Now I have my object " + obj.id);
}
Another option would be to use jQuery and wire up to the click event on your link buttons.
Add a CssClass attribute to the LinkButton's you are creating:
HyperLink lnkButton = new HyperLink();
lnkButton.ID = "lnkButton_" + ID.ToString();
lnkButton.Text = tstText;
lnkButton.CssClass = "linkButton";
Then write the follwoing JS/ JQuery in your ASPX page:
$(document).ready(function()
{
$('.linkButton', '#userControlID').click(function(e)
{
alert('You clicked linkbutton with ID ' + e.target.id);
});
});
In the above example each link button has class="linkButton" and they are contained within your usercontrol with ID="userControlID".

How can I disable all buttons and links on my page, but still let the postback occur?

I'm trying to prevent the user from clicking on more than one postback-causing element on the page. In other words, if they click the 'continue' submit button, they shouldn't be able to cause another postback before the original request comes back.
I've had a go with two versions of jQuery code. Neither does exactly what I want:
This version will disable all the postback elements, but in doing so, it stops the clicked element from firing. For the record, I don't think the .removeAttr('onclick') is really required, but leaving it out doesn't seem to change the behaviour.
$(function() {
$('a, :button, :submit').click(function() {
var elements = $('a, :button, :submit');
elements.attr('disabled', 'disabled').removeAttr('onclick');
});
});
This version disables all other postback elements, but it lets me reuse the same element that was clicked - I don't want to be able to hit the same button twice.
$(function() {
$('a, :button, :submit').click(function() {
var otherelements = $('a:not(#' + $(this).attr('id') + '), :button:not(#' + $(this).attr('id') + '), :submit:not(#' + $(this).attr('id') + ')');
elements.attr('disabled', 'disabled').removeAttr('onclick');
});
});
How can I prevent this behaviour?
I just tested your first approach without JQuery, and it worked fine, i.e. disabling the submit button didn't prevent the form submission.
<form method="get">
<input type="text" name="textfield" value="a" />
<input type="submit" onclick="this.disabled=true">
</form>
Maybe you want to double check is there is anything else, e.g. JQuery, going on?
Maybe you could put a flag or something that it could remember what button it was clicked and if that flag exist, you can remove the onclick event on that postback-causing element. But I think this cannot be done in client side scripting alone, since once the page is submitted, all client side elements and scripts are refreshed.
Perhaps instead of making this a click function make it onmouseup so it fires after the click event has occured.
Here's a final version that worked - just overriding the form submit event rather than looking at any individual elements.
var submitted = false;
$(function() {
$('form').bind('submit', function() {
if (!submitted) {
submitted = true;
return true;
} else {
return false;
}
});
});
Thanks all for your suggestions.

asp.net checkbox converted to three-state checkbox, not hitting original event handler

I have a usercontrol with an asp.net checkbox in it. I'm attempting to write a jquery script to convert that normal checkbox into a three-state checkbox. The states are 'checked', 'unchecked', and 'intermediate'. Clicking on an intermediate state should change the state to checked, clicking on an unchecked state should change the state to checked, and clicking on the checked state should change the state to unchecked.
My idea was to be able to insert a normal asp.net checkbox into the page and then call the jquery function to make it three-state.
Here's my jquery function, which is rough but working:
function SetTriStateCheckBox(checkboxfinder, initialval, originalCkbxUniqueID) {
var i = 0;
var chks = $(checkboxfinder);
if (initialval){ chks.val(initialval); }
chks.hide().each(function() {
var img = $('<img class="tristate_image" src="../Images/tristateimages/' + $(this).val() + '.gif" />');
$(this).attr("checked", ($(this).val()=="unchecked"?"false":"true"));
$(this).attr("name", "input" + i + "image" + i);
img.attr("name", "" + i + "image" + i);
i++;
$(this).before(img);
});
$(".tristate_image").click(function() {
t = $("[name='input" + $(this).attr("name") + "']");
var tval = t.val();
$(this).attr("src", "../Images/tristateimages/" + (tval=="checked" ? "unchecked" : "checked") + ".gif");
switch (tval) {
case "unchecked":
t.val("checked").attr("checked", "true");
break;
case "intermediate":
t.val("checked").attr("checked", "true");
break;
case "checked":
t.val("unchecked").removeAttr("checked");
}
setTimeout('__doPostBack(\'' + originalCkbxUniqueID + '\',\'\')', 0);
});
}
Here's a simplified version of my OnPreRender event handler which registers a startup script:
protected override void OnPreRender(EventArgs e)
{
string tristatescript = " SetTriStateCheckBox('input[id$=\"ckbx1\"]', 'intermediate','"
+ ckbx1.UniqueID + "'); ";
ScriptManager.RegisterStartupScript(this, this.GetType(), "ckbx1_tristate", tristatescript, true);
base.OnPreRender(e);
}
Everything seems to work correctly, except that I'm not hitting the event handler of the original checkbox when I post back, after clicking my newly inserted image. It does hit Page_Load.
If I take out the .hide() part of the jquery, and click on the original checkbox, Request.Params['__EVENTTARGET'] is the same as when clicking the newly inserted image.
I'm not sure where to go from here. Any suggestions?
I decided to go a different way with this. It turns out it's much easier to use an linkbutton, with an image in it, to simulate a three-state checkbox. It has it's own postback events and all you have to do is change the imageurl.
:-)

Update HiddenFiled value on parent window after child window is close Javascript,VS2005 c#

I have a child window and a parent window with a hiddenfield hdnSelectedFields .I am changing the value of hdnSelectedFields.
Code:
String vStrScript = "<script language=javascript>function CloseParent() {window.opener.document.getElementById('hdnSelectedFields').Value = '" + tempstring + "'; alert(window.opener.document.getElementById('hdnSelectedFields').Value);window.close(); } window.opener.document.forms[0].submit(); setTimeout(CloseParent, 5);</script>";
When I close the window the hdnSelectedFields value is set but when I access the hdnSelectedFields on parent window pageload it shows old value of hdnSelectedFields.
if you see the alert in JavaScriptit shows updated hdnSelectedFields value when parent is loaded completed.
Any suggestion how can I access hdnSelectedFields updated value on parent pageload.
Dee
The property of the input box you want is value, not Value.
first of all: you should go for the #-selector, as ids must be unique per definition!
in your popup:
$(document).ready(function() {
setTimeout(function() {
var hiddenField = $('#hdnSelectedFields', window.opener);
// you could do some checking here, eg. hiddenField.length for ensuring existance
hiddenField.val('new value');
alert(hiddenField.val()); // for debug reason
window.opener.document.forms[0].submit();
window.close();
}, 5);
});
in your opener:
$(document).ready(function() {
var hiddenField = $('#hdnSelectedFields');
var hiddenFieldValue = hiddenField.val();
alert(hiddenFieldValue); // for debug reason
});
edit:
your fatal mistake is following:
function CloseParent() {
window.opener.document.getElementById('hdnSelectedFields').Value = '" + hdnCheckedAttribute.Value + "';
window.close();
}
window.opener.document.forms[0].submit();
setTimeout(CloseParent, 15);
so, what will happen when you open the popup?
... biiig drum roll!
submit the form
wait 15ms
set the hiddenField
somewhere in between pt 1 and 3 your $(document).ready() of your opener happens ...
missing pt 3 (due to parallelism), no value is set to the hiddenField.
you might see my workaround in my solution for your popup, which states:
setTimeout(function() {
[...]
window.opener.document.forms[0].submit();
window.close();
}, 5);
window.opener.$('#hiddenvariable').val('somevalue');

Redirect from pop up window

how can i redirect to other page from pop up window with response.redirect.
I'm assuming that you're wanting to do this when the user presses a button or something on the popup. You can use ClientScript.RegisterStartupScript function to get ASP.Net to put some JavaScript in the right place so that it's executed as soon as the postback has completed. Something like this...
public void RedirectParent(string url)
{
string js = "";
js += "window.opener.location.href='" + url + "';";
js += "window.close();";
ClientScript.RegisterStartupScript(this.GetType, "redirect", js, true);
}
You can remove the window.close() line if you want to keep the popup open, but I'm guessing that you want to close it automatically.
The "redirect" bit on the last line is just the name that you want to assign to the script - this can be anything you wish.
Once popup is opened to a given URL you cannot use server side script to redirect the parent. You need to use javascript inside the popup:
if (opener && !opener.closed) {
opener.location.href = "http://www.example.com/somenewurl";
}

Resources