jQuery serialize는 확인란을 등록하지 않습니다.
jQuery.serialize를 사용하여 양식의 모든 데이터 필드를 검색하고 있습니다.
내 문제는 선택되지 않은 확인란을 검색하지 않는다는 것입니다.
여기에는 다음이 포함됩니다.
<input type="checkbox" id="event_allDay" name="event_allDay" class="checkbox" checked="checked" />
하지만 이건 아니야
<input type="checkbox" id="event_allDay" name="event_allDay" class="checkbox" />
체크되지 않은 체크 박스의 "값"을 어떻게 얻을 수 있습니까?
jQuery serialize
는 요청의 쿼리 문자열 또는 POST 본문에 추가되기 전에 브라우저에서 표준 양식을 직렬화하는 방법을 거의 모방합니다. 선택되지 않은 체크 박스는 브라우저에 포함되지 않습니다. 이는 부울 상태를 가지고 있기 때문에 실제로 의미가 있습니다. 사용자가 선택 (포함)하거나 사용자가 선택하지 않은 (포함되지 않음)입니다.
직렬화해야하는 경우 "왜? 왜 데이터에 존재하는지 확인하지 않습니까?"라고 자문해야합니다.
JavaScript가 양식 데이터를 직렬화하는 방식이 브라우저가 수행하는 방식과 다르게 작동하면 양식의 정상적인 성능 저하 가능성을 제거하는 것입니다. 그래도 꼭 필요한 경우 <select>
예 / 아니요 옵션이 있는 상자를 사용하십시오 . 적어도 JS를 사용하지 않는 사용자는 사이트에서 멀어지지 않으며 HTML 사양에 정의 된 동작을 위반하지 않습니다.
<select id="event_allDay" name="event_allDay">
<option value="0" selected>No</option>
<option value="1">Yes</option>
</select>
나는 과거에 이것을 일부 사이트에서 사용하는 것을 보았고 항상 "그냥 체크 박스를 사용하지 않는 이유" 라고 생각했습니다 .
azatoth의 천재적인 답변을 구축하기 위해 시나리오에 맞게 약간 확장했습니다.
/* Get input values from form */
values = jQuery("#myform").serializeArray();
/* Because serializeArray() ignores unset checkboxes and radio buttons: */
values = values.concat(
jQuery('#myform input[type=checkbox]:not(:checked)').map(
function() {
return {"name": this.name, "value": false}
}).get()
);
직렬화는 쿼리 문자열로 사용되는 것을 의미하므로 선택하지 않으면 쿼리 문자열에 전혀 포함되지 않음을 의미합니다.
체크하지 않은 체크 박스의 값을 정말로 얻으려면 다음을 사용하십시오.
var arr_unchecked_values = $('input[type=checkbox]:not(:checked)').map(function(){return this.value}).get();
쿼리 문자열에 직렬화되지 않은 확인란을 추가하려면 jquery 제출 함수에 다음을 추가합니다.
var moreinfo = '';
$('input[type=checkbox]').each(function() {
if (!this.checked) {
moreinfo += '&'+this.name+'=0';
}
});
다음은 "serializeArray"메서드를 확장하는 또 다른 솔루션입니다 (원래 동작을 유지하면서).
//Store the reference to the original method:
var _serializeArray = $ ji.fn.serializeArray;
//Now extend it with newer "unchecked checkbox" functionality:
$ji.fn.extend({
serializeArray: function () {
//Important: Get the results as you normally would...
var results = _serializeArray.call(this);
//Now, find all the checkboxes and append their "checked" state to the results.
this.find('input[type=checkbox]').each(function (id, item) {
var $item = $ji(item);
var item_value = $item.is(":checked") ? 1 : 0;
var item_name = $item.attr('name');
var result_index = null;
results.each(function (data, index) {
if (data.name == item_name) {
result_index = index;
}
});
if (result_index != null) {
// FOUND replace previous value
results[result_index].value = item_value;
}
else {
// NO value has been found add new one
results.push({name: item_name, value: item_value});
}
});
return results;
}
});
이것은 실제로 "true"또는 "false"부울 결과를 추가하지만 원하는 경우 값을로 변경하여 각각 "1"및 "0"을 사용할 수 있습니다 value: $item.is(":checked") ? 1 : 0
.
용법
평소와 같이 양식에서 메소드를 호출하십시오. $form.serialize()
또는 $form.serializeArray()
. 어떻게해서 든 serialize
사용 serializeArray
하므로 어떤 메서드를 호출하든 적절한 결과 (형식은 다르지만)를 얻을 수 있습니다.
내가 내 시스템에서 사용했으며 Struts에서 사용하는 기술은 다음과 같습니다.
<input type="hidden" name="_fieldname" value="fieldvalue"/>
... 내 양식 생성 로직의 일부로 확인란 바로 옆에 있습니다.
이렇게하면 어떤 체크 박스가 양식에 제공되었지만 선택되지 않은 체크 박스를 재구성 할 수 있습니다. 제공되는 항목과 체크 된 항목을 비교하기위한 약간의 추가 로직을 사용하면 체크되지 않은 체크 박스가 있습니다. 제출은 HTML 또는 AJAX 스타일 제출을 사용하는지 여부에 관계없이 콘텐츠에서 동일합니다.
서버 측을 사용하는 기술에 따라이 구문을 사용할 수 있습니다.
<input type="hidden" name="_fieldname[]" value="fieldvalue"/>
... 이러한 값을 목록으로 쉽게 얻을 수 있습니다.
jQuery serialize는 입력 값 속성을 가져옵니다.
이제 확인란과 라디오 버튼이 작동하도록하는 방법은 무엇입니까? 체크 박스 또는 라디오 버튼의 클릭 이벤트를 0 또는 1로 설정하면 변경 사항을 볼 수 있습니다.
$( "#myform input[type='checkbox']" ).on( "click", function(){
if ($(this).prop('checked')){
$(this).attr('value', 1);
} else {
$(this).attr('value', 0);
}
});
values = $("#myform").serializeArray();
또한 체크 상태 (예 : php)로 확인란을 설정하고 싶을 때
<input type='checkbox' value="<?php echo $product['check']; ?>" checked="<?php echo $product['check']; ?>" />
handleInputs()
ajax 전에 제출 함수에서 add를 호출 할 수 있습니다.
function handleInputs(){
$('input[type=checkbox]').each(function() {
if (!this.checked) {
$(this).attr("value","0");
}else{
$(this).attr("value","1");
}
});
}
완벽하게 작동합니다
질문 또는 현재 답변에서 해결되지 않은 비표준 확인란 직렬화를 사용하는 한 가지 이유 는 직렬화 된 데이터에 명시 적으로 지정된 필드 만 deserialize (변경)하는 것입니다. 예를 들어 jquery serialization 및 deserialization을 사용하는 경우 / 쿠키에서 선호 사항을 저장하고로드합니다.
Thomas Danemar는 serialize()
선택적으로 checkboxesAsBools
옵션 을 선택하도록 표준 방법에 대한 수정을 구현했습니다 . http://tdanemar.wordpress.com/2010/08/24/jquery-serialize-method-and-checkboxes/- 이것은 위에 나열된 구현과 유사합니다. @mydoghasworms에 의해, 표준 직렬화에도 통합되었습니다.
누군가가 언제든지 개선해야 할 사항이있는 경우를 대비하여 Github에 복사했습니다 : https://gist.github.com/1572512
또한 "jquery.deserialize"플러그인은 이제로 직렬화 된 확인란 값을 올바르게 역 직렬화 checkboxesAsBools
하고 직렬화 된 데이터에 언급되지 않은 확인란을 무시합니다. https://github.com/itsadok/jquery.deserialize
var checkboxes = $('#myform').find('input[type="checkbox"]');
$.each( checkboxes, function( key, value ) {
if (value.checked === false) {
value.value = 0;
} else {
value.value = 1;
}
$(value).attr('type', 'hidden');
});
$('#myform').serialize();
트릭은 양식 게시물을 가로 채고 확인란을 숨겨진 입력 필드로 변경하는 것입니다.
예 : 일반 제출
$('form').on("submit", function (e) {
//find the checkboxes
var $checkboxes = $(this).find('input[type=checkbox]');
//loop through the checkboxes and change to hidden fields
$checkboxes.each(function() {
if ($(this)[0].checked) {
$(this).attr('type', 'hidden');
$(this).val(1);
} else {
$(this).attr('type', 'hidden');
$(this).val(0);
}
});
});
예 : AJAX
UI를 업데이트하지 않기 위해 ajax를 통해 양식을 게시하는 경우 몇 가지 더 많은 단계를 거쳐야합니다.
$('form').on("submit", function (e) {
e.preventDefault();
//clone the form, we don't want this to impact the ui
var $form = $('form').clone();
//find the checkboxes
var $checkboxes = $form.find('input[type=checkbox]');
//loop through the checkboxes and change to hidden fields
$checkboxes.each(function() {
if ($(this)[0].checked) {
$(this).attr('type', 'hidden');
$(this).val(1);
} else {
$(this).attr('type', 'hidden');
$(this).val(0);
}
});
$.post("/your/path", $form.serialize());
그러면 체크 된 상태를 사용하여 양식 확인란 값이 부울로 설정됩니다.
var form = $('#myForm');
var data = form.serializeObject();
$('#myForm input[type=checkbox]').each(function() { data[this.name] = this.checked; });
우리가 사용하는 프레임 워크는 동일한 이름으로 두 개의 입력을 생성하므로 양식을 직렬화 할 때 예기치 않은 동작이 발생합니다. 각 확인란 값은 문자열 값이있는 두 요소 배열로 구문 분석됩니다. 데이터를 서버 측에 매핑하는 방법에 따라 의도하지 않은 결과를 얻을 수 있습니다.
내용은 ASP.NET MVC , 우리는 성공적으로있는 형태로 저장 체크 박스 를 통해 AJAX 를 포함하여이 게시물에 언급 된 여러 가지 방법의 조합은 다음과 POST @Jecoms 제안 :
var form = $('#myForm');
// Serialize the form into a JavaScript object using the jQuery.serializeObject plugin
// https://plugins.jquery.com/serializeObject/
var data = form.serializeObject();
// Change the submitted value of checkboxes to the value of the checked property
$('#myForm input[type=checkbox]').each( function () { data[this.name] = this.checked; } );
// For a MVC controller, convert the JS object back into a query string using jQuery.param function
data = $.param(data);
// Perform AJAX POST with the form data
$.ajax({
async: true,
url: 'mvcActionMethodURL',
type: 'POST',
data: data,
success: function (data, textStatus, xhr) {
},
error: function (xhr, status, error) {
}
});
Andy가 제안한 선택 필드를 사용하는 것은 한 번이 아닌 두 번의 마우스 클릭이 필요하기 때문에 반드시 사용자 경험을위한 최상의 옵션은 아닙니다.
또한 "선택"은 확인란보다 UI에서 더 많은 공간을 사용합니다.
Ash의 대답은 간단한 솔루션이지만 배열 필드 의 경우 작동하지 않습니다 .
내 컨텍스트에서 텍스트와 확인란 필드가 혼합 된 행을 보유하는 가변 길이 양식이 있습니다.
<input type="checkbox" value="1" name="thisIsAChkArray[]"/>
<input type="text" value="" name="thisIsATxtArray[]"/>
게시 된 데이터를 디코딩하려면 배열 요소 의 순서 가 중요합니다. 확인되지 않은 항목을 일반 Jquery 직렬화에 추가하는 것만으로는 행 요소의 순서가 유지되지 않습니다.
Ash의 답변을 기반으로 제안 된 솔루션은 다음과 같습니다.
(function($) {
$.fn.serializeWithChkBox = function() {
// perform a serialize form the non-checkbox fields
var values = $(this).find('select')
.add( $(this).find('input[type!=checkbox]') )
.serialize();
// add values for checked and unchecked checkboxes fields
$(this).find('input[type=checkbox]').each(function() {
var chkVal = $(this).is(':checked') ? $(this).val() : "0";
values += "&" + $(this).attr('name') + "=" + chkVal;
});
return values;
}
})(jQuery);
비슷한 문제가 발생하여 모든 양식 입력 값과 선택 / 선택 취소 된 확인란을 수집 할 수있었습니다.
var serialized = this.$('#myform input').map(function() {
return { name: this.name, id: this.id, value: this.checked ? "checked" : "false" };
});
This example assumes you want to post a form back via serialize
and not serializeArray
, and that an unchecked checkbox means false
:
var form = $(formSelector);
var postData = form.serialize();
var checkBoxData = form.find('input[type=checkbox]:not(:checked)').map(function () {
return encodeURIComponent(this.name) + '=' + false;
}).get().join('&');
if (checkBoxData) {
postData += "&" + checkBoxData;
}
$.post(action, postData);
sometimes unchecked means other values, for instance checked could mean yes unchecked no or 0,1 etc it depends on the meaning you want to give.. so could be another state besides "unchecked means it's not in the querystring at all"
"It would make it a lot easier to store information in DB. Because then the number of fields from Serialize would equal the number of fields in table. Now I have to contrll which ones are missing", youre right this is my problem too... so it appears i have to check for this nonexisting value....
but maybe this could be a solution? http://tdanemar.wordpress.com/2010/08/24/jquery-serialize-method-and-checkboxes/
just simply add a hidden input
<input type="hidden" name="your_specific_name">
doesn't need value,i tested this works for me
You Can Get inputs value with jquery serialize
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="checkbox" id="event_allDay" name="event_allDay" checked="checked" onchange="isChecked(this)" value="" />
<script>
function isChecked(element) {
$(element).val($(element).is(':checked').toString());
}
isChecked('#event_allDay');
</script>
Just to expand on the answer(s) above, in my case, I required sending a yes/no against a single ID serialized to my backend catch.
I set the checkbox elements to contain the ID of a particular database column, aka (default checked):
(Laravel Blade)
<div class="checkbox">
<label>
<input type="checkbox" value="{{ $heading->id }}" checked> {{ $heading->name }}
</label>
</div>
When I did my submission, I grabbed the data with:
(jQuery)
let form = $('#formID input[type="checkbox"]').map(function() {
return { id: this.value, value: this.checked ? 1 : 0 };
}).get();
var data = JSON.stringify(form);
$.post( "/your/endpoint", data );
For those using the serialize()
function:
(function ($) {
var serialize = $.fn.serialize;
$.fn.serialize = function () {
let values = serialize.call(this);
let checkboxes = [];
checkboxes = checkboxes.concat(
$('input[type=checkbox]:not(:checked)', this).map(
function () {
return this.name + '=false';
}).get()
);
if(checkboxes.length > 0)
values = checkboxes.join('&') + '&' + values;
return values;
};
})(jQuery);
I have used this way and getting values "0" or if checked "1". This telling that if checkbox input name is not exist in serialized form_data
then it means it is not checked then add value as zero (form_data += '&' + name + '=0'
), but if checked serialize()
function automatically adds it.
/*get all other form inputs*/
var form_data = form.serialize();
/*get checkboxes*/
$.each($("#form_id input[type='checkbox']"), function(){
var name = $(this).attr('name');
if(form_data.indexOf(name)===-1)form_data += '&' + name + '=0';
});
Try this:
$(':input[type="checkbox"]:checked').map(function(){return this.value}).get();
I post the solution that worked for me !
var form = $('#checkboxList input[type="checkbox"]').map(function() {
return { name: this.name, value: this.checked ? this.value : "false" };
}).get();
var data = JSON.stringify(form);
data value is : "[{"name":"cb1","value":"false"},{"name":"cb2","value":"true"},{"name":"cb3","value":"false"},{"name":"cb4","value":"true"}]"
참고URL : https://stackoverflow.com/questions/3029870/jquery-serialize-does-not-register-checkboxes
'developer tip' 카테고리의 다른 글
테이블 표시, redshift에서 동등한 테이블 설명 (0) | 2020.10.28 |
---|---|
SEGV_MAPERR은 무엇입니까? (0) | 2020.10.28 |
Rails 3에서 lib / tasks의 사용자 정의 레이크 작업이 발견되지 않는 이유는 무엇입니까? (0) | 2020.10.28 |
Android-모든 화면의 배경색을 설정하는 방법은 무엇입니까? (0) | 2020.10.28 |
AngularJS가있는 Twitter Bootstrap Navbar-축소가 작동하지 않음 (0) | 2020.10.28 |