-1

It's been a while since I've coded in jQuery, but this is an issue I don't remember happening before. I have a simple form:

    <form id="location">
        <input type="text" name="city" id="city" placeholder="Enter your city" required="required">
        <input type="text" name="zip" id="zip" placeholder="Enter your zip code" required="required">
        <input type="submit" name="submit" value="GET Weather" id="submit">
    </form>

and a call to get the value of the inputs:

    <script>
    $('#submit').click(function() {
        var city = $('#city').val();
        var zip = $("#zip").val();
    });
    console.log(city);
    console.log(zip);
    </script>

And for some reason I'm getting the HTML returned back of the two inputs as so-

        <input type="text" name="zip" id="zip" placeholder="Enter your zip code" required="required">

Why am I not getting back the values of the inputs?

Jacob Ruff
  • 13
  • 2
  • What with the down vote? Don't shoot people down for trying to learn coding =/ – Noobit Apr 30 '17 at 08:22
  • place the console.log calls inside the event handler, and wrap everything in the document.ready() as in `$(function() { your code; });` out of JQuery Documentation:`A page can't be manipulated safely until the document is "ready." jQuery detects this state of readiness for you.` - https://learn.jquery.com/using-jquery-core/document-ready/ – Stavm Apr 30 '17 at 08:23
  • At least related: http://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call – T.J. Crowder Apr 30 '17 at 08:30

2 Answers2

2

JS is function-scoped. Your 2 variables don't exist outside the .submit() function. You have to put the 2 console.logs there.

Also, the function is triggered only when submit is called. You were basically printing the console.logs before that.

$('#submit').click(function() {
    var city = $('#city').val();
    var zip = $("#zip").val();
    console.log(city, zip);
});
Raul Rene
  • 10,014
  • 9
  • 53
  • 75
  • I was scratching my head for quite awhile trying to figure this out. Like I said, its been a while. There was also some issue with my submit button, but I got that fixed. Thank you. – Jacob Ruff Apr 30 '17 at 08:42
0

Please define these 2 variables in global scope or print these two values inside function like,

<script>
    var city ="", zip ="";
    $('#submit').click(function() {
        city = $('#city').val();
        zip = $("#zip").val();
        show();
    });

   function show(){
    console.log(city);
    console.log(zip);
  }  
</script>

or simply,

   $('#submit').click(function() {
        var city = $('#city').val();
        var zip = $("#zip").val();
    console.log(city);
    console.log(zip);    
});

Currently, where you print values it is outside scope of those two variables. Also, I see there is no action attribute in your form.

Nitesh
  • 1,490
  • 1
  • 12
  • 20