拉表单输入的JavaScript问题

时间:2017-03-04 21:52:09

标签: javascript jquery

我想从城市名称中拉出来。并将它放在顶部的var中,它表示达拉斯,这样当某人进入城市名称时,它会自动用正确的城市名称更新var。我为早期冗长的评论道歉。堆栈溢出需要更多。

Turn HTML Form Input into JavaScript Variable

Obtain form input fields using jQuery?

<!DOCTYPE html>
<html>
<head>
  <title></title>
  <meta charset="utf-8">
  <link rel="stylesheet" type="text/css" href="style.css"></style>
  <script type="text/javascript" rel="script" type="script" href="script.jss"></script>
  <script type="text/javascript" src='http://code.jquery.com/jquery-1.10.2.min.js'></script> 
  <script type="text/javascript">

        $(document).ready(function() {

           // $("#submit").click(function(){
           // alert("The paragraph was clicked.");
           // });  // Submit button click


            var city = "dallas"       <==== code to pull from form   
              console.log(city);         

           $.get("http://api.openweathermap.org/data/2.5/weather?q="+ city + "&&units=imperial&APPID=46468f48fc0759e3d79e69e4127838da"   //api call with imperial units
          ,function(data){
            console.log(data);
          $("#weather").append(data.name);   // City name
          $("#temp").append(data.main.temp)  //temp pull
           });
       });       

  </script>


</head>
<body>
    <div id='wrapper'>

         <div id = "formdiv">

        <form id= "forminfo">

          <input  type="text" name="city" value="cityname"  >   <---this 
          <input id = "submit" type="submit" ></input>
        </form>


        </div>
      <div id = 'weather'> </div>
      <div id='temp'> <p></p> </div>


</body>
</html>

2 个答案:

答案 0 :(得分:0)

如果您正在谈论抓取此字段格式的值:

<input  type="text" name="city" value="cityname"  >

你可以这样做:

var city = $("input[name='city']").val();

以下是整个实施的示例:

$(document).ready(function() {
    $("#forminfo").on("submit", function(e) {
        e.preventDefault();
        var city = $("input[name='city']").val(); 
        console.log(city);         
        $.get("http://api.openweathermap.org/data/2.5/weather?q="+ city + "&&units=imperial&APPID=46468f48fc0759e3d79e69e4127838da"   //api call with imperial units
        ,function(data){
            console.log(data);
            $("#weather").append(data.name);   // City name
            $("#temp").append(data.main.temp)  //temp pull
        });
    });
});

答案 1 :(得分:0)

var city = "";
$("input[name='city']").blur( function() { 
    city = $("input[name='city']").val();
 } )