Programing

$ .serialize ()가 비활성화 된 입력 요소를 어떻게 고려합니까?

lottogame 2020. 7. 4. 10:40
반응형

$ .serialize ()가 비활성화 된 입력 요소를 어떻게 고려합니까?


기본적으로 비활성화 된 입력 요소는에 의해 무시되는 것 같습니다 $.serialize(). 해결 방법이 있습니까?


일시적으로 활성화하십시오.

var myform = $('#myform');

 // Find disabled inputs, and remove the "disabled" attribute
var disabled = myform.find(':input:disabled').removeAttr('disabled');

 // serialize the form
var serialized = myform.serialize();

 // re-disabled the set of inputs that you previously enabled
disabled.attr('disabled','disabled');

비활성화 된 입력 대신 읽기 전용 입력을 사용하십시오.

<input name='hello_world' type='text' value='hello world' readonly />

이것은 serialize ()에 의해 선택되어야합니다.


프록시 함수를 사용할 수 있습니다 ( $.serializeArray()모두에 영향을 미침 $.serialize()).

(function($){
    var proxy = $.fn.serializeArray;
    $.fn.serializeArray = function(){
        var inputs = this.find(':disabled');
        inputs.prop('disabled', false);
        var serialized = proxy.apply( this, arguments );
        inputs.prop('disabled', true);
        return serialized;
    };
})(jQuery);

@ user113716이 핵심 답변을 제공했습니다. 내 기여는 여기에 함수를 추가하여 jQuery를 멋지게 만드는 것입니다.

/**
 * Alternative method to serialize a form with disabled inputs
 */
$.fn.serializeIncludeDisabled = function () {
    let disabled = this.find(":input:disabled").removeAttr("disabled");
    let serialized = this.serialize();
    disabled.attr("disabled", "disabled");
    return serialized;
};

사용법 예 :

$("form").serializeIncludeDisabled();

이 시도:

<input type="checkbox" name="_key" value="value"  disabled="" />
<input type="hidden" name="key" value="value"/>

'disabled'는 W3C 표준에 따라 사용하지 않아야한다는 의미이므로 비활성화 된 입력 요소는 직렬화되지 않습니다. 일부 브라우저는 그렇지 않지만 jQuery는 표준을 준수합니다. 비활성화 된 필드와 동일한 값으로 숨겨진 필드를 추가하거나 jQuery를 통해 다음과 같이하면이 문제를 해결할 수 있습니다.

$('#myform').submit(function() {
  $(this).children('input[hiddeninputname]').val($(this).children('input:disabled').val());
  $.post($(this).attr('url'), $(this).serialize, null, 'html');
});

분명히 둘 이상의 비활성화 된 입력이있는 경우 일치하는 선택기 등을 반복해야합니다.


몇 가지 해결 방법을 볼 수 있지만 여전히 직렬화 함수 작성을 제안한 사람은 없습니까? 여기 당신이 간다 : https://jsfiddle.net/Lnag9kbc/

var data = [];

// here, we will find all inputs (including textareas, selects etc)
// to find just disabled, add ":disabled" to find()
$("#myform").find(':input').each(function(){
    var name = $(this).attr('name');
    var val = $(this).val();
    //is name defined?
    if(typeof name !== typeof undefined && name !== false && typeof val !== typeof undefined)
    {
        //checkboxes needs to be checked:
        if( !$(this).is("input[type=checkbox]") || $(this).prop('checked'))
            data += (data==""?"":"&")+encodeURIComponent(name)+"="+encodeURIComponent(val);
    }
});

In case someone don't want to activate them, then disable them again, you can also try to do this (I modified it from Disabled fields not picked up by serializeArray, from using a plugin to using a normal function):

function getcomment(item)
{
  var data = $(item).serializeArray();
  $(':disabled[name]',item).each(function(){
    data.push({name: item.name,value: $(item).val()});
  });
  return data;
}

So you can call them like this:

getcomment("#formsp .disabledfield");

Just over Aaron Hudon :

Maybe you've got something else than Input (like select), so I changed

this.find(":input:disabled")

to

this.find(":disabled")

참고URL : https://stackoverflow.com/questions/4748655/how-do-i-make-serialize-take-into-account-those-disabled-input-elements

반응형