Javascript/JQueryでformから値を取得する方法
test.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
</head>
<body>
<form id="formId" name="formName" method="post" action="FortuneAction">
<label>
メール:
<input type="text" name="mail" value="xxxxx@xxxx.xxx" size="20" />
名前:
<input type="text" name="name" value="yamada taro" size="20" />
</label>
<button type="button" onclick="jsMethodP1(formId)">submit p1</button>
<button type="button" onclick="jsMethodP2(formName)">submit p2</button>
<button type="button" onclick="jsMethodP3()">submit p3</button>
<button type="button" onclick="jsMethodP4()">submit p4</button>
<button type="button" onclick="jsMethodP5()">submit p5</button>
<button type="button" onclick="jsMethodP6()">submit p6</button>
</form>
</body>
<script src="https://code.jquery.com/jquery-3.0.0.min.js"></script>
<script>
var jsMethodP1 = function(f){
console.log('pattern1 = ' + $(f).serialize());//id属性から取得
}
var jsMethodP2 = function(f){
console.log('pattern2 = ' + $(f).serialize());//name属性から取得
}
var jsMethodP3 = function(){
console.log('pattern3 = ' + $('form').serialize());//form要素から取得
}
var jsMethodP4 = function(){
console.log('pattern4 = ' + $('#formId').serialize());//id属性から取得
}
var jsMethodP5 = function(){
console.log('pattern5 = ' + $(document.forms.formName).serialize());//name属性から取得
}
var jsMethodP6 = function(){
console.log('pattern6 = ' + $(document.formName).serialize());//name属性から取得
}
</script>
</html>
コンソール
pattern1 = mail=xxxxx%40xxxx.xxx&name=yamada%20taro
pattern2 = mail=xxxxx%40xxxx.xxx&name=yamada%20taro
pattern3 = mail=xxxxx%40xxxx.xxx&name=yamada%20taro
pattern4 = mail=xxxxx%40xxxx.xxx&name=yamada%20taro
pattern5 = mail=xxxxx%40xxxx.xxx&name=yamada%20taro
pattern6 = mail=xxxxx%40xxxx.xxx&name=yamada%20taro