我在我的網站上有註冊表單,使用jquery將默認值附加到,並且onFocus/blur默認值隱藏並相應地顯示。jquery添加輸入值 - 驗證後不顯示輸入值
我的問題是,當表單被提交,並已使用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);
}
});
});
只是一個小建議,你可以使用「defaultValue」js屬性來獲取控件的前一個/默認值。 http://www.w3schools.com/jsref/prop_text_defaultvalue.asp –