我无法使用javascript函数来运行html表单中的数据。 我在HTML中有这个表单:
<form id = "form1" onSubmit="getFormObj('form1')">
First name: <input type="text" name="FirstName" value="First"><br>
Last name: <input type="text" name="LastName" value="Last"><br>
Email: <input type="text" name="email" value="johndoe@email.com"><br>
Phone Number: <input type="text" name="phonenumber" value="Phone Number"><br>
<input id="button1" type="submit" value="Create Patient">
</form>
<script type="text/javascript">
document.write(PatientLabel);
</script>
提交按钮连接到JQuery中的JavaScript函数:
$('#button1').click(function() {
createpatient(this);
});
我正在尝试运行的Javascript函数将表单数据存储到对象中,然后将PatientLabel设置为对象的值之一:
var patientdata = {};
var PatientLabel = "";
function createpatient(formId) {
//Turn form data into array data.
var inputs = $('#'+formId).serializeArray();
$.each(inputs, function (i, input) {
patientdata[input.name] = input.value;
});
//If we got this far, print an example
patientLabel = patientdata["FirstName"];
}
但是,当我运行此代码时,应该打印patientLabel的HTML脚本不会显示任何内容!我哪里出错了?
答案 0 :(得分:1)
最后的例子:
<!DOCTYPE html>
<html xmlns='http://www.w3.org/1999/xhtml' xml:lang='en' lang='en'>
<head>
<meta http-equiv='content-type' content='text/html;charset=utf-8' />
<title>Change As You Like</title>
<script type='text/javascript' src='//ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js'></script>
<script type='text/javascript' src='rename.js'></script>
</head>
<body>
<form id='form1' name='form1'>
<label id='firstNameLabel' for='firstName'>First Name: </label><input type='text' id='FirstName' name='firstName' value='First' />
<label id='lastNameLabel' for='lastName'>Last Name: </label><input type='text' id='lastName' name='lastName' value='Last' />
<label id='emailLabel' for='email'>email: </label><input type='text' id='email' name='email' value='johndoe@email.com' />
<label id='phoneNumberLabel' for='phoneNumber'>phone: </label><input type='text' id='phoneNumber' name='phoneNumber' value='(555)555-5555' />
<input type='submit' id='button1' name='button1' value='Create Patient' />
</form>
</body>
</html>
现在rename.js
:
$(function(){
function createPatient(formElement) {
var patientData = {}, inputs = formElement.serializeArray();
$.each(inputs, function(i, o){
patientData[o.name] = o.value;
});
console.log(patientData.firstName);
// in FireBug could see Object like: console.log(patientData);
}
$('#form1').submit(function(){
// run other functions here
createPatient($(this));
return false;
});
});
答案 1 :(得分:-1)
您可能会改变调用函数的方式。如果这有助于createpatient($(this).attr('id'));