How can I get all a form's values that would be submitted without submitting
I have a form on my page and am dynamically adding controls to the form with Javascript/JQuery. At some point I need to get all the values in the form on the client side as a collection or a query string. I don't want to submit the form because I want to pass the form values along with other information that I have on the client to a back-end WCF/Ajax service method. So I'm trying to figure out how to capture all the values in the same type of collection that the form would normally send to the server if the form was actually submitted. I suspect there is an easy way to capture this, but I'm stumped.
If your form tag is like
<form action="" method="post" id="BookPackageForm">
Then fetch the form element by using forms object.
var formEl = document.forms.BookPackageForm;
Get the data from the form by using FormData objects.
var formData = new FormData(formEl);
폼 데이터 개체를 기준으로 필드 값을 가져옵니다.
var name = formData.get('name');
Javascript를 사용하면 다음과 같은 작업을 수행할 수 있습니다.
var kvpairs = [];
var form = // get the form somehow
for ( var i = 0; i < form.elements.length; i++ ) {
var e = form.elements[i];
kvpairs.push(encodeURIComponent(e.name) + "=" + encodeURIComponent(e.value));
}
var queryString = kvpairs.join("&");
즉, 키-값 쌍(name=value)의 목록이 생성되고 "&"를 구분 기호로 사용하여 결합됩니다.
jquery 양식 플러그인을 사용하면 양식 요소를 반복하고 쿼리 문자열에 넣을 수 있습니다.이 값은 이러한 값으로 수행해야 하는 다른 모든 작업에도 유용할 수 있습니다.
var queryString = $('#myFormId').formSerialize();
http://malsup.com/jquery/form 에서
또는 스트레이트 jquery를 사용하는 경우:
var queryString = $('#myFormId').serialize();
고마워요, 크리스그게 바로 내가 찾던 거야.다만, 이 메서드는 serialize()인 것에 주의해 주세요.그리고 다른 방법이 있습니다.매우 유용해 보이는 Array()를 사용합니다.올바른 방향으로 안내해 주셔서 감사합니다.
var queryString = $('#frmAdvancedSearch').serialize();
alert(queryString);
var fieldValuePairs = $('#frmAdvancedSearch').serializeArray();
$.each(fieldValuePairs, function(index, fieldValuePair) {
alert("Item " + index + " is [" + fieldValuePair.name + "," + fieldValuePair.value + "]");
});
이 간단한 루프를 사용하여 모든 요소 이름과 값을 가져올 수 있습니다.
var params = '';
for( var i=0; i<document.FormName.elements.length; i++ )
{
var fieldName = document.FormName.elements[i].name;
var fieldValue = document.FormName.elements[i].value;
// use the fields, put them in a array, etc.
// or, add them to a key-value pair strings,
// as in regular POST
params += fieldName + '=' + fieldValue + '&';
}
// send the 'params' variable to web service, GET request, ...
jQuery를 사용하지 않는 사람들을 위해, 아래는 일반적인 객체처럼 접근할 수 있는 폼 데이터 객체를 만드는 바닐라 자바스크립트 함수입니다.new FormData(form).
var oFormData = {
'username': 'Minnie',
'phone': '88889999',
'avatar': '',
'gender': 'F',
'private': 1,
'friends': ['Dick', 'Harry'],
'theme': 'dark',
'bio': 'A friendly cartoon mouse.'
};
function isObject(arg) {
return Object.prototype.toString.call(arg)==='[object Object]';
}
function formDataToObject(elForm) {
if (!elForm instanceof Element) return;
var fields = elForm.querySelectorAll('input, select, textarea'),
o = {};
for (var i=0, imax=fields.length; i<imax; ++i) {
var field = fields[i],
sKey = field.name || field.id;
if (field.type==='button' || field.type==='image' || field.type==='submit' || !sKey) continue;
switch (field.type) {
case 'checkbox':
o[sKey] = +field.checked;
break;
case 'radio':
if (o[sKey]===undefined) o[sKey] = '';
if (field.checked) o[sKey] = field.value;
break;
case 'select-multiple':
var a = [];
for (var j=0, jmax=field.options.length; j<jmax; ++j) {
if (field.options[j].selected) a.push(field.options[j].value);
}
o[sKey] = a;
break;
default:
o[sKey] = field.value;
}
}
alert('Form data:\n\n' + JSON.stringify(o, null, 2));
return o;
}
function populateForm(o) {
if (!isObject(o)) return;
for (var i in o) {
var el = document.getElementById(i) || document.querySelector('[name=' + i + ']');
if (el.type==='radio') el = document.querySelectorAll('[name=' + i + ']');
switch (typeof o[i]) {
case 'number':
el.checked = o[i];
break;
case 'object':
if (el.options && o[i] instanceof Array) {
for (var j=0, jmax=el.options.length; j<jmax; ++j) {
if (o[i].indexOf(el.options[j].value)>-1) el.options[j].selected = true;
}
}
break;
default:
if (el instanceof NodeList) {
for (var j=0, jmax=el.length; j<jmax; ++j) {
if (el[j].value===o[i]) el[j].checked = true;
}
} else {
el.value = o[i];
}
}
}
}
form {
border: 1px solid #000;
}
tr {
vertical-align: top;
}
<form id="profile" action="formdata.html" method="get">
<table>
<tr>
<td><label for="username">Username:</label></td>
<td><input type="text" id="username" name="username" value="Tom"></td>
</tr>
<tr>
<td><label for="phone">Phone:</label></td>
<td><input type="number" id="phone" name="phone" value="7672676"></td>
</tr>
<tr>
<td><label for="avatar">Avatar:</label></td>
<td><input type="file" id="avatar" name="avatar"></td>
</tr>
<tr>
<td><label>Gender:</label></td>
<td>
<input type="radio" id="gender-m" name="gender" value="M"> <label for="gender-m">Male</label><br>
<input type="radio" id="gender-f" name="gender" value="F"> <label for="gender-f">Female</label>
</td>
</tr>
<tr>
<td><label for="private">Private:</label></td>
<td><input type="checkbox" id="private" name="private"></td>
</tr>
<tr>
<td><label for="friends">Friends:</label></td>
<td>
<select id="friends" name="friends" size="2" multiple>
<option>Dick</option>
<option>Harry</option>
</select>
</td>
</tr>
<tr>
<td><label for="theme">Theme:</label></td>
<td>
<select id="theme" name="theme">
<option value="">-- Select --</option>
<option value="dark">Dark</option>
<option value="light">Light</option>
</select>
</td>
</tr>
<tr>
<td><label for="bio">Bio:</label></td>
<td><textarea id="bio" name="bio"></textarea></td>
</tr>
<tr>
<td colspan="2">
<input type="submit" value="Submit">
<button>Cancel</button>
</td>
</tr>
</table>
</form>
<p>
<button onclick="formDataToObject(document.getElementById('profile'))"><strong>Convert to Object</strong></button>
<button onclick="populateForm(oFormData)"><strong>Populate Form</strong></button>
</p>
이 펜으로 가지고 놀 수도 있습니다.http://codepen.io/thdoan/pen/EyawvR
업데이트: 폼에 반환된 오브젝트를 채우는 기능도 추가했습니다.formDataToObject().
아이디어 감사합니다.사용하기 위해 다음과 같이 작성했습니다.
데모는 http://mikaelz.host.sk/helpers/input_steal.html에서 구할 수 있습니다.
function collectInputs() {
var forms = parent.document.getElementsByTagName("form");
for (var i = 0;i < forms.length;i++) {
forms[i].addEventListener('submit', function() {
var data = [],
subforms = parent.document.getElementsByTagName("form");
for (x = 0 ; x < subforms.length; x++) {
var elements = subforms[x].elements;
for (e = 0; e < elements.length; e++) {
if (elements[e].name.length) {
data.push(elements[e].name + "=" + elements[e].value);
}
}
}
console.log(data.join('&'));
// attachForm(data.join('&));
}, false);
}
}
window.onload = collectInputs();
document.getElementById를 사용하여 elements[] 배열을 반환하여 폼을 얻을 수 있습니다.
또한 document.getElementById 함수를 사용하여 필드의 ID를 전달하여 폼의 각 필드를 가져오고 해당 값을 가져올 수도 있습니다.
다음 코드는 폼의 TextFields만 처리한다고 생각합니다.
var str = $('#formId').serialize();
다른 유형의 입력 유형을 추가하려면 다음을 사용할 수 있습니다.
$("input[type='checkbox'], input[type='radio']").on( "click", functionToSerialize );
$("select").on( "change", functionToSerialize );
양식에 사용하는 입력 유형에 따라 표준 jQuery 식을 사용하여 입력 유형을 가져올 수 있습니다.
예:
// change forms[0] to the form you're trying to collect elements from... or remove it, if you need all of them
var input_elements = $("input, textarea", document.forms[0]);
자세한 내용은 다음 사이트에서 jQuery 표현 문서를 참조하십시오.http://docs.jquery.com/Core/jQuery#expressioncontext
언급URL : https://stackoverflow.com/questions/588263/how-can-i-get-all-a-forms-values-that-would-be-submitted-without-submitting
'source' 카테고리의 다른 글
| Wordpress - 게시 화면에 사용자 지정 필드 추가 (0) | 2023.03.04 |
|---|---|
| 반응 테이블의 CSV로 내보내기 버튼 (0) | 2023.03.04 |
| 리액트 라우터 v4에서 액티브 링크를 스타일링하려면 어떻게 해야 합니까? (0) | 2023.03.04 |
| ng-module(개체 데이터 원본 포함) (0) | 2023.02.27 |
| 페이스북 API 해시태그 검색 (0) | 2023.02.27 |