2014-10-13 3 views
0

JavaScript에서 변수로 제출을 클릭하면 양식 입력 값을 가져 오려고합니다.HTML 폼에서 JavaScript로 데이터 가져 오기

그러나 콘솔 로그가 변수를 비어있는 것으로 표시하기 때문에 나는별로 운이없는 것처럼 보입니다. 내가 ADDUSER()를 제거하고 또한 하단의 ADDUSER 함수에 false를 돌려 추가 할 필요가 있었기 때문에

HTML

<html> 
<head> 
    <meta charset="UTF-8"> 
    <title>Registration</title> 
</head> 
<body> 
<fieldset><legend>Registration</legend> 
<form action="#" method="post" id="theForm"> 
    <label for="username">Username<input type="text" name="username" id="username"></label> 
    <label for="name">Name<input type="text" name="name" id="name"></label> 
    <label for="email">Email<input type="email" name="email" id="email"></label> 
    <label for="password">Password<input type="password" name="password" id="password"></label> 
    <label for="age">Age<input type="number" name="age" id="age"></label> 
    <input type="hidden" name="unique" id="unique"> 
    <input type="submit" value="Register!" id="submit"> 
</form> 
</fieldset> 

<div id="output"></div> 

<script src="js/process.js"></script>  

</body> 

</html> 

JS

var output = document.getElementById('output'); 

function addUser() { 
    'use strict'; 
    var username = document.getElementById('username'); 
    var name = document.getElementById('name'); 
    var email = document.getElementById('email'); 
    var password = document.getElementById('password'); 
    var age = document.getElementById('age'); 
    console.log(username.value); 
    console.log(name.value); 
    console.log(password.value); 
} 

// Initial setup: 
function init() { 
    'use strict'; 
    document.getElementById('theForm').onsubmit = addUser(); 
} // End of init() function. 
//On window load call init function 
window.onload = init; 

편집 그것은이었다. ADDUSER는 아무 것도 반환하지 않기 때문에

function init() { 
    'use strict'; 
    document.getElementById('theForm').onsubmit = addUser(); 
} 

에서

+1

왜 head 및 body 태그 외부에 스크립트가 있습니까? 'body' 태그 바로 앞에서 이동하십시오. – karthikr

+0

내 부분의 @karthikr 실수, 지금 업데이트 됨 :) – Adam91Holt

답변

2

이 정의에 onsubmit 동일하게 설정됩니다. addUser 함수를 onsubmit 함수로 사용하려면 대신이 함수를 사용하십시오.

function init() { 
    'use strict'; 
    document.getElementById('theForm').onsubmit = addUser; 
} 

함수 자체를 반환하지 않으려 고합니다.

는 함수의 작업을하기 위해
var addUser = function(){ 
    ... 
} 
+1

고마워 :) 문제 중 하나 였어! 그것은 또한 함수의 끝에 "false false"를 가져야 만했던 것 같습니다. 편집 : 종종 onsubmit과 같은 이벤트 처리기에서 false를 반환하면 이벤트가 실제로 발생하지 않도록 지시하는 방법입니다. 그래서, onsubmit 경우에, 이것은 양식이 제출되지 않는다는 것을 의미 할 것입니다. – Adam91Holt

1

, 당신은 수행 할 수 있습니다 : 나는 통과 또는 설정됩니다 기능을있을 때 또한

는, 나는 그것이 더 합리적이처럼 쓰기 찾을 이 :

function init() { 
     'use strict'; 
     document.getElementById('theForm').onsubmit = function() { addUser(); } 
    } 
당신은 자세한 설명은 아래 게시물을 참조 할 수 있습니다

:

Timing of button.onclick execution

희망 하시겠습니까?

관련 문제