0

When the users presses the button, I need the program to populate the text field with a string variable from an API (JSON).

Here is what I have, but it is not working:

<label for="weatherYVR"></label>
<input name="weatherYVR" type="text" id="weatherYVR" value="" size="45" />

<button onclick="weatherYVR">YVR Weather</button>
<script>
function weatherYVR() {

    function fillText(x) {
        document.getElementById("weatherYVR").value = x
    }

    jQuery(document).ready(function($) {
        $.ajax({
            url : "http://api.wunderground.com/api/XXXXXAPIKEYXXXXXX/geolookup/conditions/q/YVR.json",
            dataType : "jsonp",
            success : function(parsed_json) {
                var location = parsed_json['location']['city'];
                var weather = parsed_json['current_observation']['wind_string'];
                fillText(weather)
            }
        });
    });
}
</script>
mittmemo
  • 2,062
  • 3
  • 20
  • 27

1 Answers1

2

I fixed up a couple things in your code. Due to your using jQuery, I eliminated some base javascript and replaced it with the jQuery counterpart.

    <label for="weatherYVR"></label>
    <input name="weatherYVR" type="text" id="weatherYVR" value="" size="45" />

    <button onclick="weatherYVR()">YVR Weather</button>
    <script>

    function weatherYVR() {
        jQuery.ajax({
            url : "http://api.wunderground.com/api/XXXXXAPIKEYXXXXXX/geolookup/conditions/q/YVR.json",
            dataType : "jsonp",
            success : function(parsed_json) {
                var location = parsed_json['location']['city'];
                var weather = parsed_json['current_observation']['wind_string'];
                jQuery('#weatherYVR').val(weather);
            }
        });
    }
    </script>

You had some discrepancies in your code, such as varying the jQuery identifier from $ to jQuery. In addition, the structure of your functions was a little bit off. For example, the line jQuery(document).ready(function($) {...}); runs things when the document is fully loaded, so why would you do this inside of a function? Also the function declaration for fillText() is a bit unnecessary and the location for where it is defined is unorthodox if not improper javascript EDIT: It works, but is a bit wonky as described here. Just take a look at the docs to get the hang of things. Overall, it seems like you have the right idea.

Community
  • 1
  • 1
Hurricane Development
  • 2,449
  • 1
  • 19
  • 40