Javascript:尝试创建一个构造函数,将表单输入作为参数

时间:2017-02-04 18:54:17

标签: javascript jquery html

我有一个让我疯狂的Javascript问题。我正在尝试将表单连接到构造函数。它应该获取输入字段的值,然后将它们设置为等于新Person对象中的属性。

问题在于,在提交时,它将属性设置为等于空字符串,我无法弄清楚为什么,即使我知道实时值正在更新时更新。

脚本

//will hold an array of people objects
var list = [];

//constructor that builds new people to add to address book
function Person(first, last, address, number, email) { //new person constructor
    this.firstName = first;
    this.lastName = last;
    this.address = address;
    this.number = number;
    this.email = email;
};

// When the submit button is clicked, create a new person and add the values of
// the form fields  to the properties of the object
$("#addform").submit(function (e) {
    e.preventDefault();
    var person = new Person($("input[name = 'fname']").val(),
                            $("input[name = 'lname']").val(),
                            $("input[name = 'email']").val(),
                            $("input[name = 'address']").val(),
                            $("input[name = 'phone']").val());
    list.push(person);
    console.log(list);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="addform">
      <input type="text" name="fname" placeholder="First name">
      <input type="text" name="lname" placeholder="Last name">
      <input type="email" name="email" placeholder="email">
      <input type="input" name="address" placeholder="address">
      <input type="tel" name="phone" placeholder="phone number">
      <button type="submit" id="submitbtn">Submit</button>
      <button type="button" id="closebtn">Close</button>
    </form>

2 个答案:

答案 0 :(得分:0)

更改构造函数顺序

{{1}}

答案 1 :(得分:0)

我认为你的代码看起来很好,除了传递给构造函数的参数的顺序是错误的。这是应该如何:

//will hold an array of people objects
var list = [];

//constructor that builds new people to add to address book
function Person(first, last, address, number, email) { //new person constructor
    this.firstName = first;
    this.lastName = last;
    this.address = address;
    this.number = number;
    this.email = email;
};

// When the submit button is clicked, create a new person and add the values of
// the form fields  to the properties of the object
$("#addform").submit(function (e) {
    e.preventDefault();
    var person = new Person($("input[name = 'fname']").val(),
                            $("input[name = 'lname']").val(),
                            $("input[name = 'address']").val(),
                            $("input[name = 'phone']").val(),
                            $("input[name = 'email']").val());
    list.push(person);
    console.log(list);
});

此外,StackOverflow代码段不允许处理submit事件。所以这是一支带有工作代码的笔:http://codepen.io/jetpackpony/pen/ggKrgb?editors=1011