javascript on asp button control - c#

i am using asp button control to call a javascript function. but it is not working. it is showing an error
i am calling javascript function as:
<asp:button ID="Button1" runat="server" Text="Button" onclick="rock()" />
the javascript function is as:
function rock() {
var username = prompt("what is your name?", "please enter your name here");
if (username) {
alert("nice to meet you," + username + ".");
}
}
is there any way to call javascript function on asp button?

onclick links to a server method, you want onclientclick. If you had a simple HTML control which was not a server control, you can use onclick but it has a different meaning when it's an ASP.net control.
Fixed code:
<asp:button ID="Button1" runat="server" Text="Button" onclientclick="rock()" />

Change this:
onclick="rock()"
To:
onclientclick="rock()"
Depending on your code, you may need to set CausesPostback = false;

Related

asp button to call java script function

I am a new developer of asp.net, now I have a problem on the issue of how to call java script function in asp.net. (I am lack of java-script)
I have a java-script code that will show the confirm modal popup like this
$('#modals-bootbox-confirm').click(function()
{
bootbox.confirm("Are you sure?", function(result)
{
$.gritter.add({
title: 'Callback!',
text: "BootBox Confirm Callback with result: " + result
});
});
});
I have known that this script binds to item with id "modals-bootbox-confirm" like
<input type="button" id="modals-bootbox-confirm" name="Hello"/>
but in asp the button will be initial with type = "submit" it cannot call this because after click the button it will postback all the time so how to use this script in asp.net
I have tried to change the id in the script to the asp's id but it does not work. How do I get the result from this modal control? Please help.
I know that asp has onClientClick but how to apply this script to it?
its easy man,
Just do this
<asp:Button Id="aa" runat="server" onClientClick="function1();"/>
//and it Javascript turn it into function:
<script>
function1()
{
bootbox.confirm("Are you sure?", function(result)
{
$.gritter.add({
title: 'Callback!',
text: "BootBox Confirm Callback with result: "+ result
});
});
}
</script>
This is how to use OnClientClick:
<asp:Button OnClientClick="doSomething()" runat="server" />
Source: http://www.w3schools.com/aspnet/prop_webcontrol_button_onclientclick.asp
Very Short and Simple:
<asp:Button ID="Button1" runat="server" OnClientClick='return confirm("Are You Sure?")' />

How to implement a click event on textbox in ASP.NET?

In my web application I need a functionality so that when users click on textbox to input values, it should make the button and the other fields visible?
I am using the code provided below but, could not get it working.
C#:
protected void TextBox1_Click(object sender, EventArgs e)
{
ButtonSearch.Visible = true;
}
ASP.NET:
<asp:TextBox ID="TextBox1" runat="server" OnTextChanged="TextBox1_TextChanged" OnClick="TextBox1_Click"></asp:TextBox>
<asp:Button ID="ButtonSearch" runat="server" OnClick="ButtonSearch_Click" Text="Search" Visible="False" />
How to accomplish this?
Set AutoPostback="True". This way the event will be fired server-side, and the button will become visible.
<asp:TextBox ID="TextBox1" runat="server" OnTextChanged="TextBox1_TextChanged" OnClick="TextBox1_Click" AutoPostBack="true"></asp:TextBox>
However, if you only want to toogle visility of a button, you really should considerate javascript. This will save a trip back to the server.
<asp:TextBox onclick="txtBox1_ClientClicked()" ID="TextBox1" runat="server" OnClick="TextBox1_Click"></asp:TextBox>
<asp:Button ID="ButtonSearch" runat="server" OnClick="ButtonSearch_Click" Text="Search" style="display:none;" />
<script type="text/javascript">
function txtBox1_ClientClicked(){
var theButton = document.getElementById('<%=ButtonSearch.ClientID%>');
theButton.style.display = 'block';
}
</script>
You do not need to post back to the server to accomplish your job. You can use client side onFocus event and javascript/jquery, for example.
I know I used an input of type text, and you are using an ASP Control which posts on server, but here is a JSFiddle to get you on the right track: http://jsfiddle.net/Mmjtz/1/
$("<%= ButtonSearch.ClientID %>").click(function(){
$("#TextBox1").show():
});
In this code you need to pass fields ID which you want to visible on the click of button.
Put the textbox inside a div and use the div's onClick event from codebehind. It's not what you asked but it works for me without any errors. Here is a javascript function to implement requested event:
function toggleVisibility()
{
document.getElementById('TextBox1').disabled = true;
/*
...some other code...
*/
}
And of course, you have to define your onclick event at the div definition after implementing this JS function.
<div id="TBdiv" onClick="toggleVisibility()">
<asp:TextBox ID="TextBox1"..../>
</div>
IMPORTANT: Since you now disabled your TextBox from codebehind, you have to enable it in somewhere before you want to use it again. Otherwise you will not see it while the page is running.
jQuery is the perfect solution for your problem. The code would be something like this:
$("#TextBox1").on("click",function(){$("#ButtonSearch").css("visibility", "visible");})
You include the script by adding <script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script> to the page and then you can add the piece of code above to within <script></script> tags.

Understanding hidden fields

I was wondering if you guys could help me understand hidden fields, since I don't think I am getting them to work.
On the aspx page I have:
<asp:HiddenField ID="hidVal" value="" runat="server" />
On a button click I have a JavaScript function called
<button type="button" id="search" onclientclick="search_click()">Search</button>
With the function being
function search_click() {
document.getElementById('hidVal').Value = "1";
<% save(); %>
}
In aspx.cs I have a function that does this:
using (System.IO.StreamWriter file = new System.IO.StreamWriter(#"C:\Users\fgreene\Desktop\savedAdresses.txt", true))
{
file.WriteLine(hidVal.Value);
}
After clicking the button I look into the file and there is no change.
Is my approach correct or am I not understanding how this works?
Putting <% save(); %> in a JavaScript function in an aspx page causes save to be run when the page is built on the server, not when the surrounding JavaScript function is called on the client. At this point, the hidden field is empty, so your file gets a blank line written to it. When the user clicks the button, the hidden field is filled, but there's nothing to tell the server that this has happened.
What you need to do instead is something like:
// In your aspx, for the javascript function: remove the call to save,
// use the correct ID for the hidden field
function search_click() {
document.getElementById('<%= hidVal.ClientID %>').Value = "1";
}
// In your aspx in place of the button put
<asp:Button id="search" runat="server"
onclientclick="search_click(); return true;" onclick="search_click">
Search
</asp:Button>
// This results in a button that calls the javascript function on click, and
// then posts back to the server saying that the button has been clicked
// In your C#, this function gets called when the client posts back to
// say that the button has been clicked.
public protected void search_click(object sender, EventArgs e)
{
using (System.IO.StreamWriter file = new System.IO.StreamWriter(
#"C:\Users\fgreene\Desktop\savedAdresses.txt", true))
{
file.WriteLine(hidVal.Value);
}
}
You'll need to reference the client ID of the hidden field, which is probably not hidVal, as the actual client side ID generated in the HTML will be based on the parent control's naming container. There's two ways to fix this. First, you could make the client ID static on the control (which basically tells ASP.NET make the ID exactly what I said.):
<asp:HiddenField ID="hidVal" value="" ClientIDMode="Static" runat="server" />
Second, you can look up the ClientID property from the server when you generate your JavaScript:
document.getElementById('<%= hidVal.ClientID %>').Value = "1";
This would render out the actual client ID directly in the JavaScript code. Either approach is probably fine, but the second one would only work if the JavaScript is embedded directly in your ASPX file and not in a static .JS file.
Calling server side methods:
The second part of your question is about calling server side code when the button is pressed. You should do this by attaching an OnClick handler to your button:
<button runat="server" id="BtnSearch" onclientclick="search_click()" OnClick="btnSearch_Click">Search</button>
When the button is pressed, the page will be posted back and the btnSearch_Click event handler will be called. You'll then be able to handle any server side logic, as well as check the value of your hidden field. Hope this helps!
What you're trying to do is execute a server side function (save) via a client side call. This won't work as it is calling save() when the page first loads and then putting the return value (which is probably nothing) into the code where you put
<% save(); %>
Instead you need your button to fire the save function, but fire your javascript first. You do this by creating an asp:button (which renders as ) and then adding both an "OnClientClick" (for your javascript) and "OnClick" (for your server side function).
<asp:Button id="btnSearch" runat="server" OnClick="btnSearch_Click" OnClientClick="search_click()" text="Search" />
Then in your C# code you need the method to be named the same as the OnClick value:
protected void btnSearch_Click(object sender, EventArgs e)
{
using (System.IO.StreamWriter file = new System.IO.StreamWriter(#"C:\Users\fgreene\Desktop\savedAdresses.txt", true))
{
file.WriteLine(hidVal.Value);
}
}
The easiest way to create your server side function is to double click on the button in design view, as it will add the correct method call for you.
Hope this helps.
You can change hidden field value in both serverside and client side events.
Change value in client side
<script type="text/javascript">
function setvalue() {
document.getElementById('hidVal').value = "1";
}
</script>
<div>
<asp:HiddenField ID="hidVal" value="" runat="server" />
<br />
<asp:Button ID="Button1" runat="server" Text="Button" OnClientClick="setvalue();" />
</div>
Change value in serverside
<div>
<asp:HiddenField ID="hidVal" value="" runat="server" />
<br />
<asp:Button ID="Button1" runat="server" Text="Button" onclick="Button1_Click" />
</div>
protected void Button1_Click(object sender, EventArgs e)
{
hidVal.Value = "1";
}

call javascript from server

my button on server works on alertMsg() how ever doesnt work on playSelected()
my button on Html works on playSelected() and alertMsg()
anyone can figure out for me why?
javascript
function playSelected() {
var a = "Video/" + document.getElementById("TextBox2").value + ".flv";
jwplayer("mediaplayer").setup({
flashplayer: "jwplayer/player.swf",
file: a,
image: "jwplayer/preview.jpg"
});
}
function alertMsg() {
alert("testing123");
}
button in html
input type="button" runat="server" value="Click me!" onclick='playSelected()'
button in server
asp:Button ID="Button2" runat="server" text="call javascript" OnClientClick="playSelected(); return true;" UseSubmitBehaviour="false"
<asp:Button runat="server"
OnClientClick='playSelected(); return true;'
UseSubmitBehaviour="false" />
Make sure your java script is allowed on the clietn browser. Also do postbacks logic in your page_load event. I would rather create the Button on overriden CreateChildControls method of the page, and on overriden OnPreRender wireup my java script and register the script with ClientScriptManager method RegisterStartupScript. So that you can have nice page life cycle control.

How to make the button_Click event opens the page in a pop-up window in ASP.NET?

The question is simple but I can't find a simple answer to it! .. btw I'll need to pass a QueryString to the page to be open.
Any ideas ?
You can actually link a javascript code into .NET with C#, below is an example, you could replace with your info, and push the parameters.
Response.Write("<script type='text/javascript'>window.open('Page.aspx?ID=" + YourTextField.Text.ToString() + "','_blank');</script>");
You can append on the end of it ?Field=your value passing&nextField=another value.
Is the answer to do this in javascript. As you make the underlying page in asp.net, provide it with the javascript to catch the buttons onclick event and call window.open(URL)
It depends on what you're trying to do but the simplest is to use the OnClientClick property of the Button. Take a look at http://msdn.microsoft.com/en-us/library/7ytf5t7k.aspx, in particular the details bout this property a little bit down.
Basically you'd do something like
<asp:Button ID="Button1" Runat="server"
OnClientClick="ShowPopup();"
Text="Test Client Click" />
With the JS to do your popup
<script type="text/javascript">
function ShowPopup() {
window.open('ThankYou.aspx');
}
</script>
You can also do both an OnClientClick and an OnClick if you need as well.
<asp:Button ID="Button1" Runat="server"
OnClick="Button1_Click"
OnClientClick="ShowPopup();"
Text="Test Client Click" />
Code behind
protected void Button1_Click(Object sender, EventArgs e)
{
Label1.Text = "Server click handler called.";
}

Categories