如何阅读表单中的输入数据?

时间:2016-05-18 13:50:09

标签: javascript html forms google-geocoder

我刚刚开始学习JavaScript,因此不太了解如何使用表单或如何从中读取表单。我试图使用Google的地理编码,并需要一些帮助来构建一个JS表格来阅读。

我有以下JS代码,输出经度&纬度,只需要一个表格来存储一些地址。我的代码如下:

var geocoder = new google.maps.Geocoder();
var address  = document.getElementById("address").value;
geocoder.geocode( {'address': address}, function(results, status) {
    if(status == google.maps.GeocoderStatus.OK)
    { 
        results[0].geometry.location.latitude
        results[0].geometry.location.longitude
    }
    else
    {
        alert("Geocode was not successful for the following reason: " + status)
    }
});

我想要一些帮助,如果可能的话,建立一个表格,这段代码可以从中读取地址,其中ElementID ="地址"。这样的表格怎么样?如果有人可以花一两分钟来解释JS如何与表单一起工作,我将非常感激。任何帮助表示赞赏!感谢你们。

2 个答案:

答案 0 :(得分:1)

JS dosent关心你需要从DOM获取表单的引用然后你可以做你想要的(得到值)。

一个简单的表单可能看起来像这样

<form>
 First name:<br>
 <input type="text" id="firstname"><br>
 Address:<br>
 <input type="text" id="address">
</form>
<button onclick="myFunc()">Done!</button>

因此,当单击该按钮时,它将运行一个函数myFunc,它将从表单中获取您的数据并提醒它。

function myFunc(){
  var name = document.getElementById("firstname").value;
  var address = document.getElementById("address").value;
  alert(name + " lives at " + address);
}

更多关于通过id获取元素的信息 https://developer.mozilla.org/en-US/docs/Web/API/Document/getElementById

你也可以使用jquery

function myFunc(){
  var name = $("#firstname").val();
  var address = $("#address").val();
  alert(name + " lives at " + address);
}

https://api.jquery.com/id-selector/

答案 1 :(得分:0)

首先在html中创建一个Form。在其中加入您的外部JavaScript文件。

<head>
<script type="text/javascript" src="index.js"></script> //index.js is name of  javascript file which is in same location of this jsp page.
</head>
<body>
<form name="EmployeeDetails" action="ServletEmployee" method="post">
Employee Name:<input type="text" id="name"><br>
EmployeeID:<input type="text" id="employID"><br>
<input type="submit" value="Submit">
</form>  
<input type="button" name="Click" id="mybutton" onclick="myButtonClick">
</body>

在您的外部javascript文件中......即index.js

window.onload = function(){ // function which reads the value from html form on load without any button click.
var employeename = document.getElementById("name").value;
var employeeid = document.getElementById("employID").value;
alert("Name : "+employeename+" : EmployeeID : "+employeeid);
}

function myButtonClick(){  // function to read value from html form on click of button.
var empname = document.getElementById("name").value;
var empid = document.getElementById("employID").value;
alert("Name : "+empname+" : EmployeeID : "+empid);
}