views:

585

answers:

1

i have to pass a string value which is stored in a variable to a javascript function

which i'm calling in a button click event of my asp.net c# web application.

i have tried some ways but not getting exactly.

below is the code which i'm using

 protected void Button1_Click(object sender, EventArgs e)
    {
        myButton.Attributes.Add("onclick", "openNewWindow(spcd)");
    }

this is my button click event function

'opennewwindow' is my javascript function and 'spcd' is my variable which is a string variable, which is a public string variable.

below is my javascript function

<script type="text/javascript">

function openNewWindow(spcd) {
//alert("hello");
var tt = spcd;
alert(tt);
var theurl="http://www.gmail.com";
 popupWin = window.open(theurl,
 '_blank',
 'menubar, toolbar, location, directories, status, scrollbars, resizable, dependent, width=640, height=480, left=0, top=0')

}

</script>

but when i do like this my javascript in not working.

can any one tell which is the actual way to do this

+1  A: 

The code you've provided does not call a Javascript function from C#. What it does is add a new attribute to the button to hook up a Javascript event handler. The JS won't be executed until the next time you click the button. If you want to run a JS function on clicking a button, do what you are doing on Page_Load, or wherever, but not in the button's event handler.

Also, you can concat the string that needs to be sent as the value of the attribute like so:

myButton.Attributes.Add("onclick", "openNewWindow('" + spcd + "');";

Just make sure you do that in some of the page's lifecycle event handlers (NOT THE BUTTON CLICK EVENT HANDLER), and also that the spcd variable has the value you need at that point in the lifecycle.

Slavo
thank you very much Slavo
tibin mathew
tibin, if this answered your question you should give it a tick
Rob Fonseca-Ensor