开发者

Dynamically change form elements with javascript

I'm trying to change the city and state based on the zip code a user enters. This should all be done on the same page with jquery. I found some code elsewhere on this site but couldn't get it to work. Here is the code snippet:

        <script type="text/javascript" src="js/jquery.js"></script>
        <script type="text/javascript" src="js/jquery.validate.js"></script>
        <script type="text/javascript" s开发者_运维技巧rc="js/cufon-yui.js"></script>
        <script type="text/javascript" src="js/Myriad_Pro_700.font.js"></script>
        <script type="text/javascript">

        $("#zip").bind("change", function(e){
          $.getJSON("http://mydomain.com/code.php?zip=" + $("#zip").val(),
                function(data){
                  $.each(data, function(i,item){
                    if (item.field == "city") {
                      $("#city").val(item.value);
                    } else if (item.field == "state") {
                      $("#state").val(item.value);
                    }
                  });
                });
        });

        </script>

and this is my html:

                <label>zip</label>
                <input type="text" name="zip" maxlength="5" id="zip" class="textbox1" />
                <label>first name</label>
                <input type="text" name="fname" class="textbox1" />
                <label>last name</label>
                <input type="text" name="lname" class="textbox1" />
                <label>address</label>
                <input type="text" name="address" class="textbox1" />
                <label>address 2</label>
                <input type="text" name="address2" class="textbox1" />
                <label>city</label>
                <input type="text" name="city" id="city" class="textbox1" />
               <label>state</label>
                <input type="text" name="state" id="state" class="textbox1" maxlength="2" />

The php file outputs the json just fine.


You are trying to access the inputs by ID and your inputs don't have ID's. Either change your selector or give you inputs ID's.


The subdomain is inaccurate (as I said in my email). change

...
$.getJSON("http://mydomain.com/code.php?zip=" + $("#zip").val(),
...

to

...
$.getJSON("http://www.mydomain.com/code.php?zip=" + $("#zip").val(),
...
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜