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

3 Answers 3

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>
Sign up to request clarification or add additional context in comments.

3 Comments

<asp:Button ID="Button1" runat="server" Text="Button" OnClick="SubmitData" /> how do i modify this>?
<asp:Button ID="Button1" runat="server" Text="Button" OnClick="SubmitData" OnClientClick="JS function" />
@mid7 thank you!! perhaps you can help with this? stackoverflow.com/questions/7476329/…
3

You can use OnClientClick event

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

Comments

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>

2 Comments

@j rose this is a beautiful answer thanks so much can you see edited question please
@j rose thank you!! perhaps you can help with this? stackoverflow.com/questions/7476329/…

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.