patternjavascriptMinor
Handing focusing and unfocusing of multiple form fields
Viewed 0 times
handingunfocusingfieldsmultipleandformfocusing
Problem
Here is a link to my problem
I've been trying to simplify this code, but because of my limited javascript knowledge I haven't been able to achieve this. I'm almost 100% sure that this could be written in much simpler - DRY form.
$('#name').focus(function() {
if ($(this).val() == 'Full Name*')
$(this).val('');
}).blur(function() {
if($(this).val() == '')
$(this).val('Full Name*');
});
$('#email').focus(function() {
if ($(this).val() == 'Email Address*')
$(this).val('');
}).blur(function() {
if($(this).val() == '')
$(this).val('Email Address*');
});
$('#subject').focus(function() {
if ($(this).val() == 'Subject*')
$(this).val('');
}).blur(function() {
if($(this).val() == '')
$(this).val('Subject*');
});
$('#msg').focus(function() {
if ($(this).val() == 'Your Message*')
$(this).val('');
}).blur(function() {
if($(this).val() == '')
$(this).val('Your Message*');
});I've been trying to simplify this code, but because of my limited javascript knowledge I haven't been able to achieve this. I'm almost 100% sure that this could be written in much simpler - DRY form.
Solution
Use a custom date attribue, lets say
And then use 1 event for all!
A fiddle: http://jsfiddle.net/odpu5gbn/
placeholder on your inputs, and then give them a common class as well:And then use 1 event for all!
$(".required").focus(function() {
var placeholder = $(this).data("placeholder");
if (this.value == placeholder) this.value = "";
}).blur(function() {
if (this.value == "") this.value = $(this).data("placeholder");
}).blur(); //trigger on loadA fiddle: http://jsfiddle.net/odpu5gbn/
Code Snippets
<input type="text" id="email" data-placeholder="Email Address" class="required" />
<input type="text" id="name" data-placeholder="Full Name" class="required" />
<input type="text" id="subject" data-placeholder="Subject" class="required" />
<input type="text" id="msg" data-placeholder="Your Message" class="required" />$(".required").focus(function() {
var placeholder = $(this).data("placeholder");
if (this.value == placeholder) this.value = "";
}).blur(function() {
if (this.value == "") this.value = $(this).data("placeholder");
}).blur(); //trigger on loadContext
StackExchange Code Review Q#67734, answer score: 3
Revisions (0)
No revisions yet.