[英]Why does my submit button gets re-enabled before all fields are filled in?
我正在使用下面的代碼驗證(通過bootstrap-validator)我的聯系表單中每個字段的內容(還有一個額外的檢查通過谷歌recaptcha)。 您可以在此地址查看並測試表格。
默認情況下,提交按鈕被禁用<button id="submit-btn" class="btn-upper btn-yellow btn" name="submit" type="submit" disabled><i class="fa fa-paper-plane-o" aria-hidden="true"></i> SEND</button>
,一旦所有字段通過bootstrap-validator驗證並完成google recaptcha,就應該重新啟用。
問題 :填寫第一個字段后,會立即重新啟用提交按鈕,因此必須在某處重新激活它(您可以通過在第一個字段中鍵入您的名字然后將鼠標放在提交按鈕上來進行測試,你會看到按鈕是活動的而不是禁用的)
知道問題是什么以及如何解決這個問題?
非常感謝
JS:
$(document).ready(function() {
$('#contact_form').bootstrapValidator({
feedbackIcons: {
valid: 'fa fa-check',
invalid: 'fa fa-times',
validating: 'fa fa-refresh'
},
fields: {
first_name: {
validators: {
stringLength: {
min: 2,
},
notEmpty: {
message: 'aaVeuillez indiquer votre prénom'
}
}
},
last_name: {
validators: {
stringLength: {
min: 2,
},
notEmpty: {
message: 'aaVeuillez indiquer votre nom'
}
}
},
email: {
validators: {
notEmpty: {
message: 'aaVeuillez indiquer votre adresse e-mail'
},
regexp: {
regexp: '^[^@\\s]+@([^@\\s]+\\.)+[^@\\s]+$',
message: 'aaVeuillez indiquer une adresse e-mail valide'
}
}
},
message: {
validators: {
stringLength: {
min: 20,
max: 1000,
message:'aaVotre message doit faire plus de 20 caractères et moins de 1000.'
},
notEmpty: {
message: 'aaVeuillez indiquer votre message'
}
}
}
}}).on('success.form.bv', function (e) {
e.preventDefault();
$('button[name="submit"]').hide();
var bv = $(this).data('bootstrapValidator');
// Use Ajax to submit form data
$.post($(this).attr('action'), $(this).serialize(), function (result) {
if (result.status == 1) {
$('#error_message').hide();
$('.g-recaptcha').hide();
$('#success_message').slideDown({
opacity: "show"
}, "slow");
$('#contact_form').data('bootstrapValidator').resetForm()
} else {
$('button[name="submit"]').show();
$('#error_message').slideDown({
opacity: "show"
}, "slow")
}
}, 'json');
}
);
});
提交btn:
<button id="submit-btn" class="btn-upper btn-yellow btn" name="submit" type="submit" disabled><i class="fa fa-paper-plane-o" aria-hidden="true"></i> ENVOYER</button>
聯系頁面上的附加腳本:
<script type="text/javascript">
function recaptcha_callback(){
$('#submit-btn').removeAttr('disabled');
}
</script>
我的sendmessage.php:
<?php
require 'PHPMailer/PHPMailerAutoload.php';
$mail = new PHPMailer;
$mail->CharSet = 'utf-8';
$email_vars = array(
'message' => str_replace("\r\n", '<br />', $_POST['message']),
'first_name' => $_POST['first_name'],
'last_name' => $_POST['last_name'],
'phone' => $_POST['phone'],
'email' => $_POST['email'],
'organisation' => $_POST['organisation'],
'server' => $_SERVER['HTTP_REFERER'],
'agent' => $_SERVER ['HTTP_USER_AGENT'],
);
// CAPTCHA
function isValid()
{
try {
$url = 'https://www.google.com/recaptcha/api/siteverify';
$data = ['secret' => '6LtQ6_y',
'response' => $_POST['g-recaptcha-response'],
'remoteip' => $_SERVER['REMOTE_ADDR']];
$options = [
'http' => [
'header' => "Content-type: application/x-www-form-urlencoded\r\n",
'method' => 'POST',
'content' => http_build_query($data)
]
];
$context = stream_context_create($options);
$result = file_get_contents($url, false, $context);
return json_decode($result)->success;
}
catch (Exception $e) {
return null;
}
}
// RE-VALIDATION (first level done via bootsrap validator js)
function died($error) {
echo "We are very sorry, but there were error(s) found with the form you submitted. ";
echo "These errors appear below.<br /><br />";
echo $error."<br /><br />";
echo "Please go back and fix these errors.<br /><br />";
die();
}
// validation expected data exists
if(!isset($_POST['first_name']) ||
!isset($_POST['last_name']) ||
!isset($_POST['email']) ||
!isset($_POST['message'])) {
died('*** Fields not filled-in ***');
}
//Enable SMTP debugging.
$mail->SMTPDebug = false;
//Set PHPMailer to use SMTP.
$mail->isSMTP();
//Set SMTP host name
$mail->Host = "smtp.sendgrid.net";
//Set this to true if SMTP host requires authentication to send email
$mail->SMTPAuth = true;
//Provide username and password
$mail->Username = "fdsfs";
$mail->Password = "@pz7HQ";
//If SMTP requires TLS encryption then set it
$mail->SMTPSecure = "tls";
//Set TCP port to connect to
$mail->Port = 587;
$mail->FromName = $_POST['first_name'] . " " . $_POST['last_name'];
//To be anti-spam compliant
/* $mail->From = $_POST['email']; */
$mail->From = ('ghdsfds@gmail.com');
$mail->addReplyTo($_POST['email']);
$mail->addAddress("ghdsfds@outlook.com");
//CC and BCC
$mail->addCC("");
$mail->addBCC("");
$mail->isHTML(true);
$mail->Subject = "Nouveau message depuis XYZ";
$body = file_get_contents('emailtemplate.phtml');
if(isset($email_vars)){
foreach($email_vars as $k=>$v){
$body = str_replace('{'.strtoupper($k).'}', $v, $body);
}
}
$mail->MsgHTML($body);
$response = array();
if(isValid()) {
// send mail
if(!$mail->send()) {
$response = array('message'=>"Mailer Error: " . $mail->ErrorInfo, 'status'=> 0);
} else {
$response = array('message'=>"Message has been sent successfully", 'status'=> 1);
}
} else {
// handle error
$response = array('message' => 'Captcha was not valid');
}
/* send content type header */
header('Content-Type: application/json');
/* send response as json */
echo json_encode($response);
?>
下面是一個偽代碼,您共享的頁面的有點克隆,以及在多個事件( keyup
, change
, keypress
, blur
)上觸發的基本驗證檢查。
同樣,我們可以繼續為我們的需求添加自定義驗證 。
required = function(fields) { console.clear(); var valid = true; fields.each(function() { // iterate all var $this = $(this); if ((($this.is(':text') || $this.is('textarea')) && !$this.val())) { valid = false; } if ($this.is(":text") && $this.val().length < 3) { console.log('less than 2 characters..'); valid = false; } if ($(this).attr('id') == 'your_message' && ($this.val().length < 20 || $this.val().length > 1000)) { console.log('aaVotre message doit faire plus de 20 caractères et moins de 1000.'); valid = false; } }); return valid; } validateRealTime = function() { var fields = $("form :input"); fields.on('keyup change keypress blur', function() { if (required(fields)) { { $("#register").prop('disabled', false); } } else { { $("#register").prop('disabled', true); } } }); } validateRealTime();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <form> First name<br /> <input type="text" id="user_input" name="firstname" /><br /> Name <br /> <input type="name" id="name_input" name="name" /><br /> Email<br /> <input type="email" id="email_input" name="email" /><br /> <br/> Your Message <textarea name="your_message" id="your_message"></textarea> <br> <input type="submit" id="register" value="Submit" disabled="disabled" /> </form>
希望這對你有所幫助。 快樂的編碼!
命名提交按鈕提交似乎有問題http://bootstrapvalidator.votintsev.ru/getting-started/#name-conflict它可能導致了意外的行為
只需在表單中寫一個單獨的驗證
$("#contact_form").on('change', function () {
$("form").each(function(){
if ($(this).find(':input').val()== "")
$('#submit-btn').addClass('disabled');
});
})
實際上,您的代碼按預期工作,代碼中沒有錯誤。 但是在bootstrapValidator
你需要在success.form.bv
事件之前檢查每個字段的狀態,如下所述。
請在.success.form.bv
事件之前添加此事件,如下所述。
.on('status.field.bv', function(e, data) {
var $this = $(this);
var formIsValid = true;
$('.form-group', $this).each(function() {
formIsValid = formIsValid && $(this).hasClass('has-success');
});
$('#submit-btn', $this).attr('disabled', !formIsValid);
}).on('success.form.bv', function(e, data) {
如果它不起作用,請告訴我。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.