jquery saving non-writable value to variable?
hey guys, i wonder how I could solve this in the best way: I have a form which holds the current date as value.
<form class="form" method="post" action="">
<input type="text" value="<?php echo date("m.d.y"); ?>"/>
</form>
I wonder how I could save this value with jquery and return it to the field once it's blurred. Imagine the following case. 1.) the field holds the current date. 2.) the user deletes the input value and enters a new value. 3.) the user decides to delete this value again and clicks outside the field. then it's blurred and it should hold the original value (the date).
var cv = '';
$('inpu开发者_StackOverflowt').focus(function() {
cv = $(this).val();
});
$('input').blur(function() {
if ( $(this).val() == '' ) {
$(this).val(cv);
}
});
What's the best way to solve this? How could I solve this?
The blur/focus behavior you’re describing sounds like the placeholder
attribute in HTML. Example:
<input type="text" placeholder="e.g. John Doe">
So in your case, all you have to do is use placeholder
instead of value
:
<input type="text" placeholder="<?php echo date("m.d.y"); ?>">
You can also use them both:
<input type="text" value="<?php echo date("m.d.y"); ?>" placeholder="<?php echo date("m.d.y"); ?>">
This way, the current date will be entered when the page is loaded, but when the field is cleared and then blurred, the current date will re-appear as placeholder text.
(Note that you should really use <input type=date>
for date inputs, but this has nothing to do with your question.)
@placeholder
works in the latest stable Chrome, Safari, Opera, and Firefox 4.
For browsers who don’t support this attribute natively, you could use JavaScript.
If you’re using jQuery, you could consider using my placeholder plugin for jQuery, which is the most robust solution I’ve seen. Here’s a demo page: http://mathiasbynens.be/demo/placeholder
I would save the original value on focus
, but then the page is loaded (onready
):
var cv;
$(function() {
cv = $("input").val();
});
精彩评论