admin管理员组

文章数量:1307165

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

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

Share Improve this question edited May 23, 2017 at 11:45 CommunityBot 11 silver badge asked Sep 19, 2011 at 19:11 Alex GordonAlex Gordon 60.9k304 gold badges703 silver badges1.1k bronze badges
Add a ment  | 

3 Answers 3

Reset to default 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>

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>

本文标签: caspnet run javascript on clickStack Overflow