0

my select option in HTML is,

<select name="id" id="id" style="width:400px;" onChange="loadAjax(this.value);">
<select name="name" id="name" style="width:400px;">

Which loads the ajax function (using javascript) when the value is change in SELECT (html). But I am in different requirement, that when this select input loads, it should call the loadAjax function directly, and on change as well.

How it could be possible? I tried some things like window.onload, onload, but nothing worked.

4 Answers 4

1

Given that you've tagged your question with "jquery", I'd suggest a jQuery solution:

$(document).ready(function() {
    $("#id").change(function() {
        loadAjax($(this).val());
    }).change();
});

This defines the change handler and then immediately triggers it. (You would remove the inline onclick from your html.)

Or without jQuery perhaps something like this:

window.onload = function() {
   loadAjax(document.getElementById("id").value);
};
Sign up to request clarification or add additional context in comments.

3 Comments

one question. Why are you calling the .change(); after you bind the loadAJax to be called on change of #id ? I'm sorry for the typo.
Edited my comment above, sorry for the typo.
@verisimilitude - Because the question asked how to have loadAjax() be called both on change and on load. Passing a function to .change() binds that function to be called whenever the event happens, but if you call .change() with no parameters it triggers the event.
1
window.onload = function() {
   loadAjax(document.getElementById("id").value);
};

Comments

0

You can also bind change event to #id element.

$(document).ready(function() {
   $("#id").bind("change",function() {
        loadAjax($(this).val());
   });
});

Comments

0

If you are using jQuery then:

$(document).ready(function() {
$("#id").change(function(e) {
 //handle the event
});
});

By using the above you don't have to bind the onChange handler in the select html element. Since jQuery will be able to bind the event for you with the above code.

<select name="id" id="id" style="width:400px;">
<select name="name" id="name" style="width:400px;">

The HTML will look something like this.

Comments

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.