简体   繁体   中英

Call javascript function on page_load event

In asp.net website, inside .aspx i have following code

<script type="text/javascript">
    function callme(option) {
        document.getElementById("t1").value = option;
    }
</script>
<div id="content" runat="server"></div>

<input type="text" id="t1" />

On code behind file inside Page_Load :

content.InnerHtml = MyClassObject.MyMethod(...);

Inside MyClass :

public String MyMethod(...)
{
   ... //some code
   String str1 ="<select id=\"s1\" onchange=\"callme(this.value)\">" +
                    "  <option value=\"1\">One</option>"+
                    "  <option value=\"2\">Two</option>" +
                    "  <option value=\"3\">Three</option>" +                          
                    "</select>";
   ... // some code
   return str1;

Whenever i select any option from dropdownlist it reflects its value inside the textbox t1. But at page load the textbox remains empty. I cannot use default value as the values of the dropdownlist are changing at runtime. How can I add first value of dropdownlist to textbox t1 on page load?

In your onload function in javascript you get the currently selected value in a drowdownlist as follows:

var s1 = document.getElementById("s1");
var selectedVal = s1.options[s1.selectedIndex].value;
<script type="text/javascript">
function BuyG2() {
    alert('Hai Jquery');
}
</script> //jquery in sourse
protected void Page_Load(object sender, EventArgs e)
{
    ScriptManager.RegisterStartupScript(this.Page, this.GetType(), "tmp",
        "<script type='text/javascript'>BuyG2();</script>", false);
} //ASP Button Click Events

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM