programing

jQuery를 사용하여 양식 필드 지우기

showcode 2023. 5. 20. 11:01
반응형

jQuery를 사용하여 양식 필드 지우기

양식의 모든 입력 및 텍스트 영역 필드를 지웁니다.입력 버튼을 사용할 때 다음과 같이 작동합니다.reset 명령어:

$(".reset").bind("click", function() {
  $("input[type=text], textarea").val("");
});

양식의 필드뿐만 아니라 페이지의 모든 필드를 지웁니다.실제 재설정 버튼이 있는 형태의 셀렉터는 어떻게 보입니까?

jQuery 1.6+의 경우:

$(':input','#myform')
  .not(':button, :submit, :reset, :hidden')
  .val('')
  .prop('checked', false)
  .prop('selected', false);

jQuery < 1.6의 경우:

$(':input','#myform')
  .not(':button, :submit, :reset, :hidden')
  .val('')
  .removeAttr('checked')
  .removeAttr('selected');

다음 게시물을 참조하십시오.jQuery를 사용하여 다단계 양식 재설정

또는

$('#myform')[0].reset();

jQuery가 제안하는 바와 같이:

"DOM"과 DOM 합니다.checked,selected또는disabled형식 요소의 상태는 .prop() 방법을 사용합니다.

$(".reset").click(function() {
    $(this).closest('form').find("input[type=text], textarea").val("");
});

이것을 사용해서는 안 되는 이유가 있습니까?

$("#form").trigger('reset');

양식 입력 필드의 기본값이 비어 있지 않은 경우는 처리하지 않습니다.

비슷한 것이 작동해야 합니다.

$('yourdiv').find('form')[0].reset();

선택기를 사용하여 값을 빈 값으로 만들면 양식이 재설정되지 않고 모든 필드가 비어 있습니다.재설정은 서버 측에서 양식을 로드한 후 사용자가 편집 작업을 수행하기 전과 동일하게 양식을 만드는 것입니다.이름이 "username"인 입력이 있고 해당 사용자 이름이 서버 측에서 미리 입력된 경우, 이 페이지의 대부분의 솔루션은 해당 값을 사용자가 변경하기 전의 값으로 재설정하지 않고 입력에서 삭제합니다.양식을 재설정해야 하는 경우 다음을 사용합니다.

$('#myform')[0].reset();

양식을 재설정할 필요가 없고 모든 입력을 빈 값(예: 빈 값)으로 채우면 다른 주석의 솔루션을 대부분 사용할 수 있습니다.

간단하지만 매력적으로 작동합니다.

$("#form").trigger('reset'); //jquery
document.getElementById("myform").reset(); //native JS

만약 누군가가 여전히 이 스레드를 읽고 있다면, 여기 jQuery가 아닌 일반 JavaScript를 사용하는 가장 간단한 해결책이 있습니다.입력 필드가 양식 내에 있는 경우 간단한 JavaScript 재설정 명령이 있습니다.

document.getElementById("myform").reset();

자세한 내용은 여기에서 확인하십시오. http://www.w3schools.com/jsref/met_form_reset.asp

건배!

$('form[name="myform"]')[0].reset();

왜 자바스크립트로 해야 하나요?

<form>
    <!-- snip -->
    <input type="reset" value="Reset"/>
</form>

http://www.w3.org/TR/html5/the-input-element.html#attr-input-type-keywords


먼저 시도해 보면 기본값으로 필드를 지울 수 없습니다.

다음은 jQuery를 사용하여 수행하는 방법입니다.

$('.reset').on('click', function() {
    $(this).closest('form').find('input[type=text], textarea').val('');
});

유형에 관계없이 모든 입력 상자를 비우려면 다음과 같이 몇 분 후에

 $('#MyFormId')[0].reset();

양식을 재설정하는 가장 쉬운 방법이 있습니다.

jQuery("#review-form")[0].reset();

또는

$("#review-form").get().reset();

하면 이 Javascript로 간단하게 할 수.getElementById("your-form-id").reset();

를 사용할 .$('#your-form-id')[0].reset();

잊지 잊지 .[0]다음 오류가 발생할 수 있습니다.

유형 오류: $(...). 재설정이 함수가 아닙니다.

JQuery는 또한 사용할 수 있는 이벤트를 제공합니다.

$('#form_id').trigger(")";

시도해봤는데 효과가 있어요.

참고: 이러한 방법은 페이지 로드 시 서버가 설정한 초기 값으로만 양식을 재설정합니다.즉, 임의 변경을 수행하기 전에 입력이 '설정 값'으로 설정된 경우 재설정 방법이 호출된 후 필드가 동일한 값으로 재설정됩니다.

도움이 되길 바랍니다.

$('#editPOIForm').each(function(){ 
    this.reset();
});

editPOIForm는 것은입니다.id양식의 속성을 입력합니다.

은 사용하지 ?document.getElementById("myId").reset();이것은 단순하고 예쁜 것입니다.

해결책은 - ▁is-입니다.
$("#form")[0].reset();

여기서 - 기서사안함용여 -
$(this)[0].reset();

JQuery 을 .trigger()그리고브자트의립크바스티네이..reset()모든 폼 요소를 빈 상태로 재설정할 수 있습니다.

$(".reset").click(function(){
    $("#<form_id>").trigger("reset");
});

를 바꿉니다.<form_id>재설정할 형식의 ID를 사용합니다.

테스트 및 검증된 코드:

  $( document ).ready(function() {
    $('#messageForm').submit(function(e){
       e.preventDefault();
    });
    $('#send').click(function(e){
      $("#messageForm")[0].reset();
    });
  });

는 Javascript에 .$(document).ready그리고 그것은 당신의 논리와 일치해야 합니다.

사용:

$(".reset").click(function() {
  $('input[type=text]').each(function(){
     $(this).val('');
  });
});

여기 제 단추가 있습니다.

<a href="#" class="reset">
  <i class="fa fa-close"></i>
     Reset
</a>

필드를 삭제하고 계정을 제외한다고 합니다.평균 시간 드롭다운 상자에 특정 값(예: 'All')으로 재설정됨을 입력합니다.나머지 필드는 빈 텍스트 상자로 재설정해야 합니다.이 접근 방식은 특정 필드를 삭제하는 데 사용됩니다.

 $(':input').not('#accountType').each( function() {

    if(this.type=='text' || this.type=='textarea'){
             this.value = '';
       }
    else if(this.type=='radio' || this.type=='checkbox'){
         this.checked=false;
      }
         else if(this.type=='select-one' || this.type=='select-multiple'){
              this.value ='All';
     }
 });

몇몇 분들은 라디오 등이 기본 "체크" 상태에서 지워졌다고 불평하셨습니다..not에 :radio, :checkbox Selector를 추가하기만 하면 문제가 해결됩니다.

다른 모든 재설정 기능이 작동하지 않으면 이 기능이 작동합니다.

  • ngen의 답변에서 수정됨

    function form_reset(formID){
        $(':input','#'+formID)
        .not(':button',':submit',':reset',':hidden',':radio',':checkbox')
        .val('');
    }
    
$(document).ready(function() {
    $('#reset').click(function() {
    $('#compose_form').find("input[type=text] , textarea ").each(function() {
    $(this).val('');
   });
  });
});  

jQuery로 일반 재설정 기능을 호출할 경우 이 코드 사용

setTimeout("reset_form()",2000);

그리고 이 기능을 문서 준비 시 사이트 밖에 jQuery 작성

<script>
function reset_form()
{
    var fm=document.getElementById('form1');
    fm.reset();
}
</script>
@using (Ajax.BeginForm("Create", "AcceptanceQualityDefect", new AjaxOptions()
{
    OnSuccess = "ClearInput",
    HttpMethod = "Post",
    UpdateTargetId = "defect-list",
    InsertionMode = InsertionMode.Replace
}, new { @id = "frmID" })) 
  1. frmID의 식별입니다.
  2. OnSuccess는 "JavaScript 함수"라는.ClearInput"

    <script type="text/javascript">
        function ClearInput() {
            //call action for render create view
            $("#frmID").get(0).reset();
        }
    </script>
    
  3. 만약 당신이 이 두 가지를 모두 제대로 한다면, 당신은 그것이 작동하는 것을 막을 수 없을 것입니다.

다음 코드는 모든 양식을 지우고 해당 필드는 비어 있습니다.페이지에 둘 이상의 양식이 있는 경우 특정 양식만 지우려면 양식의 ID 또는 클래스를 언급하십시오.

$("body").find('form').find('input,  textarea').val('');

accountType을 제외한 모든 필드를 지우려면..다음을 사용합니다.

$q(':input','#myform').not('#accountType').val('').removeAttr('checked').removeAttr('selected');

제가 여기서 그리고 관련된 SO 질문들에서 본 코드는 불완전한 것 같습니다.

폼을 재설정하는 것은 HTML에서 원래 값을 설정하는 것을 의미하기 때문에 위의 코드를 기반으로 제가 하고 있던 작은 프로젝트를 위해 이것을 정리했습니다.

            $(':input', this)
                .not(':button, :submit, :reset, :hidden')
                .each(function(i,e) {
                    $(e).val($(e).attr('value') || '')
                        .prop('checked',  false)
                        .prop('selected', false)
                })

            $('option[selected]', this).prop('selected', true)
            $('input[checked]',   this).prop('checked',  true)
            $('textarea',         this).each(function(i,e) { $(e).val($(e).html()) })

부족한 부분이 있거나 개선할 수 있는 부분이 있으면 알려주시기 바랍니다.

페이지에 IHTtpHandler 요청 처리(captcha)를 포함하는 웹 사용자 제어 호출이 포함된 경우 위의 모든 항목은 간단한 경우에 작동하지 않습니다.요청을 보낸 후(이미지 처리를 위해) 아래 코드가 양식의 필드를 지우지 않습니다(HttpHandler 요청을 보내기 전). 모든 것이 올바르게 작동합니다.

<input type="reset"  value="ClearAllFields" onclick="ClearContact()" />

 <script type="text/javascript">
       function ClearContact() {
           ("form :text").val("");
       }
    </script>

범용 jQuery 플러그인을 작성했습니다.

/**
 * Resets any input field or form
 */
$.fn.uReset = function () {
    return this.filter('form, :input').each(function () {
        var input = $(this);
        
        // Reset the form.
        if (input.is('form')) {
            input[0].reset();
            return;
        }

        // Reset any form field.
        if (input.is(':radio, :checkbox')) {
            input.prop('checked', this.defaultChecked);
        } else if (input.is('select')) {
            input.find('option').each(function () {
                $(this).prop('selected', this.defaultSelected);
            });
        } else if (this.defaultValue) {
            input.val(this.defaultValue);
        } else {
            console.log('Cannot reset to default value');
        }
    });
};

$(function () {
    // Test jQuery plugin.
    $('button').click(function (e) {
        e.preventDefault();
        
        var button = $(this),
            inputType = button.val(),
            form = button.closest('form');
        
        if (inputType === 'form') {
            form.uReset()
        } else {
            $('input[type=' + inputType + '], ' + inputType, form).uReset();
        }
    });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<h3>Form</h3>
<form>
    <input type="text" value="default"/><br /><br />
    Ch 1 (default checked) <input type="checkbox" name="color" value="1" checked="checked" /><br />
    Ch 2 <input type="checkbox" name="color" value="2" /><br />
    Ch 3 (default checked) <input type="checkbox" name="color" value="3" checked="checked" /><br /><br />
    <select name="time"><br />
        <option value="15">15</option>
        <option selected="selected" value="30">30</option>
        <option value="45">45</option>
    </select><br /><br />
    R 1 <input type="radio" name="color" value="1" /><br />
    R 2 (default checked) <input type="radio" name="color" value="2" checked="checked" /><br />
    R 3 <input type="radio" name="color" value="3" /><br /><br />
    <textarea>Default text</textarea><br /><br />
    
    <p>Play with form values and then try to reset them</p>
    
    <button type="button" value="text">Reset text input</button>
    <button type="button" value="checkbox">Reset checkboxes</button>
    <button type="button" value="select">Reset select</button>
    <button type="button" value="radio">Reset radios</button>
    <button type="button" value="textarea">Reset textarea</button>
    <button type="button" value="form">Reset the Form</button>
</form>

다음과 같이 숨겨진 재설정 버튼을 추가합니다.

<input id="resetBtn" type="reset" value="reset" style="display:none" />
// Call reset buttons click event
// Similar to ClearInputs('resetBtn');
function ClearInputs(btnSelector) {
     var btn = $("#" + btnSelector);
     btn.click();
}
$('form').submit(function() {

    var el = $(this);

    $('<button type="reset" style="display:none; "></button>')
        .appendTo(el)
        .click()
        .remove()
    ;

    return false;

});

언급URL : https://stackoverflow.com/questions/6364289/clear-form-fields-with-jquery

반응형