我在我的网站上有注册表单,使用 jquery 我将默认值附加到,并在 onFocus/blur 中相应地隐藏和显示默认值。
我的问题是,当提交表单并使用 php 验证踢回错误时,我无法在字段中显示发布的值。 javascript 似乎覆盖了在输入值中使用 php 回显的已发布数据。
当我在发布表单后查看页面源代码时,我发现在输入的值中我确实具有发布的值,即我想要显示的值。示例:
<input type="text" name="first_name" value="Harry" />
PHP 已经完成了将发布的数据回显到我的输入值中的工作。然后 Javascript 对其进行更改,以便用户不再看到他们的名字(本例中为 Harry),而是再次看到默认的 jquery 附加“名字”。
即使我在输入中有值,也会发生这种情况。
如何修改我的 Javascript 以记录我的输入值而不是覆盖它?
这是目前的代码:
$(document).ready(function() {
$('input[name=first_name]').val('First name');
$('input[name=last_name]').val('Last name');
$('input[name=email_address]').val('Email address');
// cache references to the input elements into variables
var passwordField = $('input[name=password]');
var emailField = $('input[name=email_address]');
var firstnameField = $('input[name=first_name]');
var lastnameField = $('input[name=last_name]');
// get the default value for the fields
var emailFieldDefault = emailField.val();
var firstnameFieldDefault = firstnameField.val();
var lastnameFieldDefault = lastnameField.val();
// add a password placeholder field to the html
passwordField.after('<input id="passwordPlaceholder" type="text" value="Password" autocomplete="off" />');
var passwordPlaceholder = $('#passwordPlaceholder');
// show the placeholder with the prompt text and hide the actual password field
passwordPlaceholder.show();
passwordField.hide();
// when focus is placed on the placeholder hide the placeholder and show the actual password field
passwordPlaceholder.focus(function() {
passwordPlaceholder.hide();
passwordField.show();
passwordField.focus();
});
// and vice versa: hide the actual password field if no password has yet been entered
passwordField.blur(function() {
if(passwordField.val() == '') {
passwordPlaceholder.show();
passwordField.hide();
}
});
// when focus goes to and moves away from the fields, reset it to blank or restore the default depending if a value is entered
emailField.focus(function() {
if(emailField.val() == emailFieldDefault) {
emailField.val('');
}
});
emailField.blur(function() {
if(emailField.val() == '') {
emailField.val(emailFieldDefault);
}
});
firstnameField.focus(function() {
if(firstnameField.val() == firstnameFieldDefault) {
firstnameField.val('');
}
});
firstnameField.blur(function() {
if(firstnameField.val() == '') {
firstnameField.val(firstnameFieldDefault);
}
});
lastnameField.focus(function() {
if(lastnameField.val() == lastnameFieldDefault) {
lastnameField.val('');
}
});
lastnameField.blur(function() {
if(lastnameField.val() == '') {
lastnameField.val(lastnameFieldDefault);
}
});
});
最佳答案
$('input[name=first_name]').val('First name');
这无条件地将那个元素的值设置为 First Name
。它不是“仅在值为空时才设置值”,而是“将值设置为 First Name,无论其中包含什么”。
你需要这样的东西来保存里面的东西:
if ($('input[name=first_name]').val() == '') {
$('input[name=first_name]').val('First name');
}
相反,它只会在字段开始为空时重置该字段的值。
关于php - Jquery 附加输入值 - 验证后不显示输入的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8153429/