Reputation: 1233
Here is one I just had come up and the solution baffled me and no search here at SO revealed anything.
Standard input field:
<input type="input" name="fName" placeholder="Your First Name">
But let us say I would like to update the placeholder text when somebody clicks on the field or when the field is onfocus via pressing the Tab key.
So it would become:
<input type="input" name="fName" placeholder="Your First Name Goes Here">
Just a very basic example of what it would do, by adding the "Goes Here" to the placeholder text.
Doable? Even possible to modify placeholder? Unknown to me.
If so and it is possible via pure JS or via jQuery, I would be entertained in seeing how.
Upvotes: 2
Views: 3576
Reputation: 10867
Here's a JS answer. I tend to dislike JQuery.
var myInpt = document.getElementsByTagName('input');
var key;
for(key in myInpt)
{
myInpt[key].addEventListener('click', updateInpt, true);
}
function updateInput(evt)
{
this.inpt = evt.srcElement;
var plchldrText = this.inpt.getAttribute('placeholder');
this.inpt.setAttribute('placeholder', plchldrText + ' Goes Here');
}
Of course, this attaches the click event to every input element on your page, as well as every time you click it, it adds the string ' Goes Here'. Haha. If you want to do it this way, maybe you should add an id to the input and collect it in JS that way. Just a thought and a simple example! Hope it helps!
Upvotes: 0
Reputation: 999
To do it in pure JS, you should use addEventListener()
to get the click/focus event and setAttribute()
to set the placeholder attribute.
var elem = document.getElementsByName("fName")[0];
function appendPlaceholder () {
elem.setAttribute ("placeholder", "Your First Name Goes Here");
}
elem.addEventListener("click", appendPlaceholder);
elem.addEventListener("focus", appendPlaceholder);
elem.addEventListener("blur", function () {
elem.setAttribute ("placeholder", "Your First Name");
});
Upvotes: 0
Reputation: 1537
This should do it (edit:added blur reset):
$('input[name=fName]').on("click focus",function(){
$(this).attr("placeholder","Your First Name Goes Here");
}).on("blur",function(){
$(this).attr("placeholder","Your First Name");
});
Updated Fiddle: http://jsfiddle.net/6tb8v/1/
Upvotes: 4