asp.net: run javascript on click? - c#

i have a form and a button a form:
<asp:Button ID="Button1" runat="server" Text="Button" OnClick="SubmitData" />
i have a method in my c# program. the method is called SubmitData
however i would also like to run a javascript function on this button click as well. how do i do this?
here is my javascript function:
var selectedLanguages = new Array();
jQuery('#lstProblems option:selected').each(function() {
selectedLanguages.push(jQuery(this).val());
});
i got it from here: jquery listbox return what user selected
how do i run it ? do i have to put it in <script></script> and do some_Function(etc...) ?

you should use the OnClientClick='myJsFunc();'
<asp:Button ID="Button1" runat="server" Text="Button" OnClick="SubmitData" OnClientClick="aaa()" />
<script type="text/javascript">
function aaa()
{
var selectedLanguages = new Array();
jQuery('#lstProblems option:selected').each(function() {
selectedLanguages.push(jQuery(this).val());
});
}
</script>

You can use OnClientClick event
<asp:Button ID="Button1" runat="server" Text="Button" OnClientClick="Your javascript function" OnClick="SubmitData" />

Set up your server side event code the way it seems to be already, then in the Page_Load method of your code behind add the following line:
Button1.Attributes.Add("onclick","yourJavascriptFunction();");
EDIT: To run the function from your edited question, simply create a function of the same name in your javascript file. Something like this:
<script type="text/javascript">
function yourJavascriptFunction()
{
var selectedLanguages = new Array();
jQuery('#lstProblems option:selected').each(function() {
selectedLanguages.push(jQuery(this).val());
});
}
</script>

Related

Jquery 2 clicks event

I had a page with many FileUploads and I am having a problem with jQuery to fire up 2 .click events to remove files at the certain point when a RadioBoxList .click(is selected) event, two buttons calling same function as delete_Click on code behind..
My code as following :
<asp:Button ID="delBtn1" runat="server" Text="DeleteFile" OnClick="delete_Click" ClientIDMode="Static" />
<asp:Button ID="delBtn2" runat="server" Text="DeleteFile" OnClick="delete_Click" ClientIDMode="Static" />
$("#rblist").click(function() {
if ($("#rbl_1").prop("checked")) {
$(".someclass").hide();
uploadCheck1();
uploadCheck2();
$("delBtn1").click();
$('delBtn2').click();
}
});
first click never fired, wondering where is the problem? I am new to jQuery and hoping someone can point out my mistake,thank you!
You need ClientID to get ASP.NET controls with jQuery:
$('#<%= rblist.ClientID %>').click(function() {
if ($('#<%= rbl_1.ClientID %>').prop("checked")) {
$(".someclass").hide();
uploadCheck1();
uploadCheck2();
$('#<%= delBtn1.ClientID %>').click();
$('#<%= delBtn2.ClientID %>').click();
}
});
Use the dblclick event
$(document).ready(function(){
$("p").dblclick(function(){
alert("The the page.");
});
});
you are selecting the button control with id so you need to specify the Jquery id selector(#)
try below code
$("#rblist").click(function() {
if ($("#rbl_1").prop("checked")) {
$(".someclass").hide();
uploadCheck1();
uploadCheck2();
$("#delBtn1").click(); //change here
$('#delBtn2').click();//change here
}
});

How to call a javascript function before and after button click event call in asp.net

i have created "ButtonClick" function in ASP.NET as following:
<asp:Button ID="btnLogin" runat="server" Text="Login" CssClass="button" CausesValidation="true" onclick="btnLogin_Click"/>
i want to know, is it possible to call a javascript function before and after calling asp.net button click function...???
Thanks.
Yes it's possible, here is quick example:
Java script function to call.
<script type="text/javascript">
function clientValidate() {
alert("execute before");
return true;
}
function executeAfter() {
alert("execute after");
}
</script>
Here is snapshoot for button
<asp:Button ID="btnLogin" runat="server" Text="Login" CausesValidation="true" OnClientClick="clientValidate()" onclick="btnLogin_Click"/>
Notice property onClientClick="clientValidate()", it will be trigger script before button click on the server.
On the server side:
protected void btnLogin_Click(object sender, EventArgs e)
{
ScriptManager.RegisterClientScriptBlock(this, GetType(), "none", "<script>executeAfter();</script>", false);
}
Notice executeAfter();, it will trigger javascript execution after server event.
Don't forget to place <asp:ScriptManager runat="server"></asp:ScriptManager> in your aspx file.
Hope it help
put this on your page and make sure you have a scriptmanager. these codes will handle your pre & post postbacks.
var prm, postBackElement;
if (typeof Sys != "undefined") {
prm = Sys.WebForms.PageRequestManager.getInstance();
prm.add_initializeRequest(InitializeRequest);
prm.add_endRequest(EndRequest);
}
function InitializeRequest(sender, e) {
postBackElement = e.get_postBackElement();
if (postBackElement.id == "btnLogin") {
// before click codes
}
}
function EndRequest(sender, e) {
if (postBackElement.id == "btnLogin") {
// after click codes
}
}
Before:
<script type="text/javascript">
function executeBefore() {
alert("execute before");
}
</script>
<asp:Button ID="btnLogin" runat="server" Text="Login" CausesValidation="true" OnClientClick="executeBefore()" onclick="btnLogin_Click"/>
After:
<script type="text/javascript">
function executeAfter() {
alert("execute after ");
}
</script>
Add this code to your server side event:
Page.ClientScript.RegisterStartupScript(GetType(), "none", "<script>executeAfter();</script>", false);
If you don't have a master page, or are not using ajax, there is no need to add ScriptManager.
You can call Java scrip function before server side click using OnClientClick():
aspx(design)
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<script type="text/javascript">
function Test() {
alert('client click');
}
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:Button Text="btn" runat="server" ID="btn"
OnClick="btn_Click" OnClientClick="Test()" />
</div>
</form>
</body>
</html>
.cs
protected void btn_Click(object sender, EventArgs e)
{
Response.Write("Server Click");
}
First time you can call your javascript function in Button's OnClientClick event passing your function name.
<asp:Button ID="btnLogin" runat="server" Text="Login" CssClass="button" CausesValidation="true" onclick="btnLogin_Click" OnClientClick="return functionNAME();"/>
Second time, in your button click event btnLogin_Click call js as follow
ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "script", "<script type='text/javascript'>functionNA();</script>", false);
For calling it before, you could consider using onload function, like this example:
<body onload="myFunction()">
For calling it afterwards, just link the button to execute JS onClick?
I don't think I quite understand your intentions.

how can i pass parameters from javascript to hidden field in controls vb.net

i have a control that has two asp:HiddenField
<asp:HiddenField runat="server" ID="tabTitle" />
<asp:HiddenField runat="server" ID="tabMenu" />
this control load in a page called Alarms
the control on the alarms page look like this
<alarm:SubscriptionPanel ID="pnlSubscription" runat="server" />
what iam trying to do is passing value from pagealarms to the control hidden fields and there is a function at the control code behind that reads the hidden fields values
Question is how can i pass javascript values to hidden field in controls on page load
thanks in advance
You can use JQuery for it like this
Example :
$("input[type=hidden][id='<%=tabTitle.ClientID%>']").val("Hello World");
$("input[type=hidden][id='<%=tabMenu.ClientID%>']").val("Hello World");
If you are using ASP.NET 4.0 your best bet is to set the ClientIDMode property on those controls to static and then simply use javascript to populate the hidden elements using plain ol' document.getElementById(). Something like this:
<asp:HiddenField runat="server" ID="tabTitle" ClientIDMode="Static" />
//since the id mode in the hidden element is static;
//you should be able to do this safely:
document.getElementById('tabTitle').value = myvalue;
If you are not on ASP.NET 4.0; jQuery will help here since you can find an element using partial matching as HatSoft showed you in his answer but with a slight difference:
$("input[type=hidden][id*='tabTitle']").val("Hello World");
Note the id*= part. This gets all input elements whose ids contain the word tabTitle
Besides the approach commented by #Icarus, you could expose a JavaScript function from your control.
The problem you would face if you use ClientIDMode=Static in that, you would be restricted to add only one alarm:SubscriptionPanel control to your page
If you are planning to use only one control on each page, then the easiest approach is the one commented by #Icarus, however I would consider it as a temporal approach
This alternative encapsulates the logic where it really belongs, inside the custom control:
Output
ASCX
<div id="<%: this.ClientID %>">
<asp:HiddenField runat="server" ID="hidden1" Value="one" />
<asp:HiddenField runat="server" ID="hidden2" />
<asp:Button Text="Post me" runat="server" OnClick="postme_Click" />
<asp:Label runat="server" ID="lbl"></asp:Label>
<script type="text/javascript">
$(function () {
var myObj = {
setHidden1: function (myValue) {
$("#<%: this.hidden1.ClientID %>").val(myValue);
},
getHidden1: function () {
return $("#<%: this.hidden1.ClientID %>").val();
},
helloWorld: function () {
alert("hellow world");
}
};
$("#<%: this.ClientID %>").data("data", myObj);
});
</script>
</div>
ASCX code behind
protected void postme_Click(object sender, EventArgs e)
{
this.lbl.Text = "Posted: " + this.hidden1.Value;
}
ASPX
<script type="text/javascript">
$(function () {
$("#myPageButton").click(function () {
$("#<%: this.myControl.ClientID %>").data("data").setHidden1("plop");
$("#<%: this.myControl2.ClientID %>").data("data").setHidden1("plop2");
});
});
</script>
<input type="button" id="myPageButton" value="Set Hidden value" />
<uc1:EncapsulateJavaScriptLogicInUserControl ID="myControl"
runat="server" />
<uc1:EncapsulateJavaScriptLogicInUserControl ID="myControl2"
runat="server" />
<uc1:EncapsulateJavaScriptLogicInUserControl ID="myControl3"
runat="server" />
I just found another way, that looks even more object oriented, however, it requires you to use the Microsoft AJAX library.
ASCX
Change: $("#<%: this.ClientID %>").data("data", myObj);
Into: $.extend($get("<%: this.ClientID %>"), myObj);
ASPX
Change:
$("#<%: this.myControl.ClientID %>").data("data").setHidden1("plop");
$("#<%: this.myControl2.ClientID %>").data("data").setHidden1("plop2");
Into:
$get("<%: this.myControl.ClientID %>").setHidden1("plop");
$get("<%: this.myControl2.ClientID %>").setHidden1("plop2");
With this approach you remove the use of the .data jQuery function

Check all CheckBoxes in GridView

I have a GridView in ASP.NET/C# with a CheckBoxField, a BoundField and 2 ButtonFields. All 4 of them has a header to make clear where the column stands for. At the Page_Load event I set the ВataЫource of the GridView to my filled DataTable.
I want to make it easier to use for the user, and want to make a checkbox in the header. When that checkbox is checked by the user, all CheckBoxes should be checked in the GridView. I have set the HeaderText of the CheckBoxField to <input type='checkbox' />, and it shows a checkbox in the header now.
Now I want to add a function to that checkbox, that when it's checked, all CheckBoxes will be checked en vice versa. I tried to do it with jQuery, but it didn't work because I can't find a way to give all the CheckBoxes in the GridView the same ID or NAME.
Is there a event that occurs when I check the HTML based checkbox within the header? If yes, which event?
If no, how can i trigger a event when I check that checkbox, and change the GridView from my code-behind.
And if none of that is possible, how can i do it on another way, with javascript, jQuery or maybe with a ASP.net control.
I hope you can help me with this, but please don't expect i'm a code guru. I'm a intern at a company where the need a system, with this functionality.
Update:
Thank you everyone for helping me out. What is the easiest way to get the DataSource back into the DataTable, because i need to know which rows were selected and which were not?
Using jQuery, you get all the check boxes inside the GridView, and then for each one you change the status as you like. You call this javascript function from onclick of a link or a button, or what ever you like.
function CheckAll()
{
var updateButtons = jQuery('#<%=gvGridViewId.ClientID%> input[type=checkbox]');
updateButtons.each( function() {
// use this line to change the status if check to uncheck and vice versa
// or make it as you like with similar function
jQuery(this).attr("checked", !this.checked);
});
}
try this code according to you
in grid view
<asp:TemplateField>
<HeaderTemplate>
<asp:CheckBox ID="headerchkbox" runat="server" CssClass="chkheader" />
</HeaderTemplate>
<ItemTemplate>
<asp:CheckBox ID="CheckBoxAssign" runat="server" CssClass="chkitems" />
</ItemTemplate>
</asp:TemplateField>
java script
<script type="text/javascript">
$(window).bind('load', function () {
var headerChk = $(".chkheader input");
var itemChk = $(".chkitems input");
headerChk.bind("click", function () { itemChk.each(function () { this.checked = headerChk[0].checked; })
});
itemChk.bind("click", function () { if ($(this).checked == false) headerChk[0].checked = false; });
});
</script>
Here is a sample I have put together for you.
ASPX
<head runat="server">
<title></title>
<script src="Scripts/jquery-1.4.1.min.js" type="text/javascript"></script>
<script type="text/javascript">
var allCheckBoxSelector = '#<%=GridView1.ClientID%> input[id*="chkAll"]:checkbox';
var checkBoxSelector = '#<%=GridView1.ClientID%> input[id*="chkSelected"]:checkbox';
function ToggleCheckUncheckAllOptionAsNeeded() {
var totalCheckboxes = $(checkBoxSelector),
checkedCheckboxes = totalCheckboxes.filter(":checked"),
noCheckboxesAreChecked = (checkedCheckboxes.length === 0),
allCheckboxesAreChecked = (totalCheckboxes.length === checkedCheckboxes.length);
$(allCheckBoxSelector).attr('checked', allCheckboxesAreChecked);
}
$(document).ready(function () {
$(allCheckBoxSelector).live('click', function () {
$(checkBoxSelector).attr('checked', $(this).is(':checked'));
ToggleCheckUncheckAllOptionAsNeeded();
});
$(checkBoxSelector).live('click', ToggleCheckUncheckAllOptionAsNeeded);
ToggleCheckUncheckAllOptionAsNeeded();
});
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:GridView ID="GridView1" runat="server">
<Columns>
<asp:TemplateField>
<HeaderTemplate>
<asp:CheckBox ID="chkAll" runat="server" />
</HeaderTemplate>
<ItemTemplate>
<asp:CheckBox ID="chkSelected" runat="server" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</div>
</form>
</body>
C#
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
List<string> lstObjects = new List<string> { "aaa", "bbb" };
GridView1.DataSource = lstObjects;
GridView1.DataBind();
}
}
If you are using the latest version of jQuery (1.7)
Use the following:
<script type="text/javascript">
var allCheckBoxSelector = '#<%=GridView1.ClientID%> input[id*="chkAll"]:checkbox';
var checkBoxSelector = '#<%=GridView1.ClientID%> input[id*="chkSelected"]:checkbox';
function ToggleCheckUncheckAllOptionAsNeeded() {
var totalCheckboxes = $(checkBoxSelector),
checkedCheckboxes = totalCheckboxes.filter(":checked"),
noCheckboxesAreChecked = (checkedCheckboxes.length === 0),
allCheckboxesAreChecked = (totalCheckboxes.length === checkedCheckboxes.length);
$(allCheckBoxSelector).attr('checked', allCheckboxesAreChecked);
}
$(document).ready(function () {
$(allCheckBoxSelector).click(function () {
$(checkBoxSelector).attr('checked', $(this).is(':checked'));
ToggleCheckUncheckAllOptionAsNeeded();
});
$(checkBoxSelector).click(ToggleCheckUncheckAllOptionAsNeeded);
ToggleCheckUncheckAllOptionAsNeeded();
});
</script>

Can I call a function after a ValidationSummary?

I have a ValidationSummary on client side (which should be called by asp:LinkButton) that check my RequiredFieldValidator and CustomValidator :
<asp:ValidationSummary
ID="valSum"
runat="server"
CssClass="label"
HeaderText="There are these errors:"
ShowSummary="False"
ShowMessageBox="True"
EnableClientScript="True"
DisplayMode="BulletList">
</asp:ValidationSummary>
and I need, if there are the errors (so there are empty fields or the custom validators fail) call another javascript function.
I really hope that this is possible on .NET 3.5, right?
I've read a similar question on SO here, but is not clear at all.
Place this script at the page's end:
<script type="text/javascript">
var originalValidationSummaryOnSubmit = ValidationSummaryOnSubmit;
ValidationSummaryOnSubmit = function (validationGroup) {
originalValidationSummaryOnSubmit(validationGroup);
if (Page_IsValid === false) {
alert("boo!");
}
}
</script>
Yes this is possible. You will need to change the OnClientClick property of your linkbutton and/or other controls causing the validation to perform. Also put your CausesValidation property to false.
<asp:LinkButton ID="lnkButton1" runat="server" CausesValidation="false" OnClientClick="return DoValidation('');" ... />
Javascript function:
function DoValidation(validationGroup) {
var isValid = Page_ClientValidate(validationGroup);
if (!isValid){
isValid = DoSomethingElse();
}
return isValid;
}
If you want to only validate a group you can pass the name of the group to the 'DoValidation' function.
<asp:LinkButton ID="lnkButton1" runat="server" CausesValidation="false" OnClientClick="return DoValidation('NameOfGroup');" ... />

Categories

Resources