开发者

How to fill select box with values from database on onchange event of another select box and without refreshing the page or submitting the form?

I have a html form in php page. The demo code is as follows.

<html>
<head>
</head>
<body>
<form>
<select name="users" onchange="showUser(this.value)">
<option value="">Select a person:</option>
<option value="1">Peter Griffin</option>
<option value="2">Lois Griffin</option>
<option value="3">Glenn Quagmire</option>
<option value="4">Joseph Swanson</option>
</select>
<br>
<select name="job" >
</select>
<br>
<input name="salary" type="text">
<br>
<input name="Submit" type="submit" value="Submit">
</form>
<br>
</body>
</html>

In above form after clicking submit button some validation code in javascript gets executed and after validation the form gets submitted programatically using java script.

The requirement is the when I select a value from first select box; the second select box should gets filled with some values. These values in second select box comes from database. As I dont know anything in AJAX but I want to achieve this using AJAX and javascript/jquery because whenever I select any value from fir开发者_StackOverflowst select box the form should not get submitted or the page should not get refreshed just the second select box gets filled with new values from database.

Please guide me friends in solving this. Thank you!


HTML

<select id="job" name="job" >
</select>

jQuery

function showUser(value){

        $("#job").get(0).options.length = 0;
        $("#job").get(0).options[0] = new Option("Loading jobs", "-1"); 

        $.ajax({
            type: "POST",
            url: "Default.aspx/GetJobs",
            data: "{userID:" + value+ "}",
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function(msg) {
                $("#job").get(0).options.length = 0;
                $("#job").get(0).options[0] = new Option("Select job", "-1"); 

                $.each(msg.d, function(index, item) {
                    $("#job").get(0).options[$("#job").get(0).options.length] = new Option(item.Display, item.Value);
                });
            },
            error: function() {
                $("#job").get(0).options.length = 0;
                alert("Failed to load jobs");
            }
        });
}

Taken from here

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜