Reputation: 5985
I have a few pages that have long forms on them. Some of these forms are pre-populated and if there is a pre-populated field at the top of the form, I use autofocus to automatically allow the user to start typing in that field.
in addition to these fields, I will occasionally have "notes" pop up next to the field to give more guidance as to what they are typing in. These notes only come up when the user is focused on the input field.
Here is the code to show the field next to the input on focus:
$('input[type="text"]').focus(function(){
var hasCont = $(this).parent().siblings('.cont-note').length;
if(hasCont == 1){
$(this).parent().siblings('.cont-note').fadeIn(400);
}
});
This, unfortunately does not work with html input's autofocus. I want to avoid using jQuery to focus on a field, I would rather use html (for ease of modification)
My goal is: IF there is a note next to an input field that has autofocus, show the note.
Any suggestions?
Upvotes: 1
Views: 435
Reputation: 5048
Why not use the .attr() function? You give your input field an extra attribute called noteID and on focus you use the .attr() function to get the ID. Now you can select without having to go hunting around the DOM.
$('.hasNote').focus(function() {
var noteID = $(this).attr("noteID");
$('#' + noteID).fadeIn(400);
};
<input type="text" class="hasNote" id="whatever" noteID="same as the note id" />
<note id="noteID">
Obviously I am just using the ID here, change <note
to whatever element you need.
Upvotes: 0
Reputation: 318302
You could filter the elements based on wether or not they have the autofocus property, and then trigger a focus event to get the focus event handler to trigger etc. but only one element can have focus, so maybe using first() would be a good idea ?
$('input[type="text"]').focus(function(){
var hasCont = $(this).parent().siblings('.cont-note').length;
if(hasCont == 1){
$(this).parent().siblings('.cont-note').fadeIn(400);
}
});
$('input[type="text"]').filter(function() {
return $(this).prop('autofocus');
}).first().trigger('focus');
Upvotes: 3