Reputation: 3920
I have the following simple Jquery:
<script type="text/javascript">
$(document).ready(function(){
$(document).one('focus', 'input', function() {
$(this).val('');
});
});
</script>
<input type="text" value="Default 1" />
<input type="text" value="Default 2" />
<input type="text" value="Default 3" />
<input type="text" value="Default 4" />
<input type="text" value="Default 5" />
The above code will lead to running the focus function only once for all elements.
How to make it run the function once per each input element? Example:
Click the second element, run once. Click the first element, run once. And so on...
Upvotes: 0
Views: 121
Reputation: 29889
The accepted answer works, but I'm guessing what you're really trying to do is use a placeholder
:
<input type="text" placeholder="Default 1" />
<input type="text" placeholder="Default 2" />
In browsers that support placeholder, you'll get some startup text that clears on focus without taking the performance hit of using javascript. In unsupported browsers, you can use a polyfill to accomplish what you're trying to do anyway.
Also, the .each()
function can be used to do something on every element returned by the selector.
$(function(){
placeholderPolyfill();
});
function placeholderPolyfill() {
if (!placeholderIsSupported()) {
$("input[placeholder]").each(function() {
this.value = this.placeholder;
$(this).one('focus', function() {
this.value = '';
});
});
}
}
function placeholderIsSupported() {
var test = document.createElement('input');
return ('placeholder' in test);
}
Upvotes: 0
Reputation: 144659
You can use the not
selector:
$(document).on('focus', 'input:not(.focused)', function() {
$(this).addClass('focused').val('');
});
Upvotes: 1