jQuery : 양식 입력 지우기
양식을 지우는 다른 방법을 시도했습니다.
<form action="service.php" id="addRunner" name="addRunner" method="post">
First Name: <input type="text" name="txtFirstName" id="txtFirstName" /><br />
Last Name: <input type="text" name="txtLastName" id="txtLastName" /><br />
Gender: <select id="ddlGender" name="ddlGender"><option value="">--Please Select--</option>
<option value="f">Female</option>
<option value="m">Male</option>
</select><br />
Finish Time:
<input type="text" name="txtMinutes" id="txtMinutes" size="10" maxlength="2">(Minutes)
<input type="text" name="txtSeconds" id="txtSeconds" size="10" maxlength="2">(Seconds)
<br />
<button type="submit" name="btnSave" id="btnSave">Add Runner</button>
<input type="hidden" name="action" value="addRunner" id="action">
</form>
jQuery # 1 :
function clearInputs(){
$("#txtFirstName").val('');
$("#txtLastName").val('');
$("#ddlGender").val('');
$("#txtMinutes").val('');
$("#txtSeconds").val('');
}
이것은 완벽하게 작동합니다.
jQuery # 2 :
function clearInputs(data){
$("#addRunner :input").each(function(){
$(this).val('');
});
이렇게하면 양식이 지워지지 만 더 이상 정보를 제출할 수 없습니다. 버튼을 다시 클릭하려고했지만 아무 동작도하지 않습니다.
다음은 버튼 클릭 핸들러입니다.
$("#btnSave").click(function(){
var data = $("#addRunner :input").serializeArray();
$.post($("#addRunner").attr('action'), data, function(json){
if (json.status == "fail"){
alert(json.message);
}
if (json.status == "success"){
alert(json.message);
clearInputs();
}
}, "json");
});
PHP 포스트 코드 :
<?php
if($_POST){
if ($_POST['action'] == 'addRunner') {
$fname = htmlspecialchars($_POST['txtFirstName']);
$lname = htmlspecialchars($_POST['txtLastName']);
$gender = htmlspecialchars($_POST['ddlGender']);
$minutes = htmlspecialchars($_POST['txtMinutes']);
$seconds = htmlspecialchars($_POST['txtSeconds']);
if(preg_match('/[^\w\s]/i', $fname) || preg_match('/[^\w\s]/i', $lname)) {
fail('Invalid name provided.');
}
if( empty($fname) || empty($lname) ) {
fail('Please enter a first and last name.');
}
if( empty($gender) ) {
fail('Please select a gender.');
}
if( empty($minutes) || empty($seconds) ) {
fail('Please enter minutes and seconds.');
}
$time = $minutes.":".$seconds;
$query = "INSERT INTO runners SET first_name='$fname', last_name='$lname', gender='$gender', finish_time='$time'";
$result = db_connection($query);
if ($result) {
$msg = "Runner: ".$fname." ".$lname." added successfully" ;
success($msg);
} else {
fail('Insert failed.');
}
exit;
}
}
jQuery 메서드 # 2를 사용하면 콘솔에 다음 오류가 표시됩니다.
Uncaught TypeError: Cannot read property 'status' of null
왜 이런 일이 발생합니까?
다음 주요 정보를 포함하는 것을 잊었습니다.
function fail ($message){
die(json_encode(array('status'=>'fail', 'message'=>$message)));
}
function success ($message){
die(json_encode(array('status'=>'success', 'message'=>$message)));
그러면 jQuery의 AJAX 함수로 메시지가 다시 전송됩니다. 방법 # 2를 사용하여 양식을 한 번 제출하면 성공 / 실패 메시지가 비워진 것 같습니다.
데모 : http://jsfiddle.net/xavi3r/D3prt/
$(':input','#myform')
.not(':button, :submit, :reset, :hidden')
.val('')
.removeAttr('checked')
.removeAttr('selected');
원래 답변 : jQuery로 다단계 양식 재설정
Mike의 제안 (댓글에서) 확인란을 유지하고 그대로 선택합니다!
Warning: If you're creating elements (so they're not in the dom), replace :hidden
with [type=hidden]
or all fields will be ignored!
$(':input','#myform')
.removeAttr('checked')
.removeAttr('selected')
.not(':button, :submit, :reset, :hidden, :radio, :checkbox')
.val('');
I'd recomment using good old javascript:
document.getElementById("addRunner").reset();
Took some searching and reading to find a method that suited my situation, on form submit, run ajax to a remote php script, on success/failure inform user, on complete clear the form.
I had some default values, all other methods involved .val('') thereby not resetting but clearing the form.
I got this too work by adding a reset button to the form, which had an id of myform
:
$("#myform > input[type=reset]").trigger('click');
This for me had the correct outcome on resetting the form, oh and dont forget the
event.preventDefault();
to stop the form submitting in browser, like I did :).
Regards
Jacko
You may try
$("#addRunner input").each(function(){ ... });
Inputs are no selectors, so you do not need the :
Haven't tested it with your code. Just a fast guess!
I figured out what it was! When I cleared the fields using the each() method, it also cleared the hidden field which the php needed to run:
if ($_POST['action'] == 'addRunner')
I used the :not() on the selection to stop it from clearing the hidden field.
참고URL : https://stackoverflow.com/questions/7792320/jquery-clearing-form-inputs
'UFO ET IT' 카테고리의 다른 글
서랍 레이아웃을 왼쪽으로하여 메인 콘텐츠를 이동하는 방법 (0) | 2020.12.02 |
---|---|
자바에서 두 날짜 사이의 날짜 목록을 얻는 방법 (0) | 2020.12.02 |
다운로드 한 PIP 패키지를 캐시하는 방법 (0) | 2020.12.02 |
설치 프로그램 MSI가 오류 코드 1603과 함께 반환되어 AppFabric 설치에 실패했습니다. (0) | 2020.12.02 |
Scrollview는 하나의 직계 자식 만 호스트 할 수 있습니다. (0) | 2020.12.02 |