1

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...) ?

Community
  • 1
  • 1
Alex Gordon
  • 57,446
  • 287
  • 670
  • 1,062

3 Answers3

5

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>
Royi Namir
  • 144,742
  • 138
  • 468
  • 792
3

You can use OnClientClick event

<asp:Button ID="Button1" runat="server" Text="Button" OnClientClick="Your javascript function" OnClick="SubmitData"  />
meziantou
  • 20,589
  • 7
  • 64
  • 83
2

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>
BrosephRoseph
  • 250
  • 2
  • 8
  • @j rose this is a beautiful answer thanks so much can you see edited question please – Alex Gordon Sep 19 '11 at 19:20
  • @j rose thank you!! perhaps you can help with this? http://stackoverflow.com/questions/7476329/asp-net-invalid-postback-or-callback-argument – Alex Gordon Sep 19 '11 at 19:37