It is always a better practice to define your events in the script section or a separate .js file.
You don't need to handle that in a .change()
event . You can check that in the .blur()
event itself..
HTML
<input type="text" class="input-text required-entry validate-value-eg"
id="city_field" name="city" value="e.g. Bristol, Yorkshire">
Pure Javascript
var elem = document.getElementById('city_field');
elem.addEventListener('focus', function() {
if (this.value == 'e.g. Bristol, Yorkshire') {
this.value = '';
}
});
elem.addEventListener('blur', function() {
if (this.value == 'e.g. Bristol, Yorkshire') {
RemoveClass(this, "newClass")
}
else if (this.value == '') {
this.value = 'e.g. Bristol, Yorkshire';
RemoveClass(this, "newClass")
}
else {
this.className += " newClass";
}
});
function RemoveClass(elem, newClass) {
elem.className = elem.className.replace(/(?:^|\s)newClass(?!\S)/g, '')
}
But you can achieve this with a loss lesser code by using other javascript frameworks. This will make your life a lot easier but it is always good if you start out with javascript.
jQuery
$(function() {
var $elem = $('#city_field');
$elem.val('e.g.Bristol, Yorkshire'); // Default value
$elem.on('focus', function() { // Focus event
if (this.value == 'e.g.Bristol, Yorkshire') {
this.value = '';
}
});
$elem.on('blur', function() { // Focus event
if (this.value == 'e.g.Bristol, Yorkshire') {
$(this).removeClass("newClass");
}
else if (this.value == '') {
this.value = 'e.g.Bristol, Yorkshire';
$(this).removeClass("newClass");
}
else {
$(this).addClass("newClass");
}
});
});