Hi, I have a form with a name and an email address. I want a simple icon to appear to the right of the form if the user types anything in the field, even one character. If there is anything present in the field, I want the success icon to appear. If the user advances to the next field with no input, I want the fail icon to appear. Does anyone know some super simple javascript to do this? Everything Im finding is way too advanced and too feature rich.
How about:
var field = document.getElementById('myFormField');
var icon = document.getElementById('myIcon');
field.onchange = function(){
icon.src = this.value ? 'success.png' : 'fail.png';
};
(I haven't yet tested this)
Basically, it says: whenever the text field is changed by the user, check to see the value
of the field. If the field has not been filled in, then the value
will be false
. The src
property of the icon is then changed accordingly.
For other types of form field (e.g. selects), you may need a different property than value
. But if you're using jQuery, you can simply use .val().
You might want to add a more sophisticated check - e.g. if the value
contains only whitespace.
1) First off, install jquery and include it on your site. Minified it's tiny, and it allows for much easier javascript.
2) My assumed html is:
<input type="text" name="name" id="edit-name" class='text-field' />
<img src='something' id='edit-name-succeed' style="display: none;" />
<img src='something' id='edit-name-fail' style="display: none;" />
<input type="text" name="email" id="edit-email' class='text-field' />
<img src='something' id='edit-email-succeed' style="display: none;" />
<img src='something' id='edit-email-fail' style="display: none;" />
3) My javascript would then be:
$('input.text-field').change(function() {
if ($(this).text()) {
$('#' + $(this).attr('id') + '-fail').hide();
$('#' + $(this).attr('id') + '-succeed').show();
}
});
$('input.text-field').blur(function() {
if (!($(this).text())) {
$('#' + $(this).attr('id') + '-fail').show();
$('#' + $(this).attr('id') + '-succeed').hide();
}
});