私は狂ったようなJavascriptの問題を抱えています。私はコンストラクタ関数にフォームをフックしようとしています。入力フィールドの値を取得し、新しいPersonオブジェクトのプロパティと同じ値に設定する必要があります。Javascript:引数としてフォームの入力を受け取るコンストラクタを作成しようとしています
問題は、サブミット時に空の文字列と同じプロパティを設定していることです。なぜなら、実際の値が変更時に更新されていることがわかっていても、理由はわかりません。
スクリプト
//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>
updateValue($(this)).val()); 'は、$($ thisと同じです)val($ this ).val()); 'は全く意味がありません。 'this.value = this.value'を実行しています。これは何も変わりません。 – Bergi
あなたは 'submit dom'の後に' submit'リスナーを追加していますか(https://stackoverflow.com/questions/14028959/why-does-jquery-or-a-dom-method-such-as-getelementbyid -not-find-the-element)?あなたのスタックスニペットはしません。 – Bergi
私は間違っているかもしれませんが、セレクタのこの種のオブジェクトの代わりに配列を選択しようとすることができますし、代わりにvalの配列の最初の要素を取得しようとしている – Kejt