How can do I enable onclick to clear an input field? Jquery
$('<p><input type="text" class = "class-'+ (++i) +'" onclick="'(+ this.value = ''; +)'" value="Enter Choice #' + i + '"/&g开发者_运维技巧t;</p>')
I'm not sure if this is the correct syntax or not, but whatever I am using is not working. ANy help? Thanks
HTML:
<input type="text" class="class-1" value="Enter Choice #1">
<input type="text" class="class-2" value="Enter Choice #2">
JQUERY:
$(document).ready(function() {
$('input[class^="class-"]').focus(function() {
var $input = $(this);
if($input.val() == $input.data('default_val') || !$input.data('default_val')) {
$input.data('default_val', $input.val());
$input.val('');
}
});
$('input[class^="class-"]').blur(function() {
var $input = $(this);
if ($input.val() == '') $input.val($input.data('default_val'));
});
});
Above code clear the value when the textfields gets focus and adds the default value when textfield is empty on lost focus (blur).
Updated fiddle: http://jsfiddle.net/K3Sx7/4/
EDIT: updated code to conform question.
Add an id to your input field:
<input id="myinput"...
Then add this code in your $(document).ready(...
call:
$('#myinput') // get element whose id is 'myinput'
.click(function() { // bind a click handler
$(this).val('') // clear field
.unbind('click'); // unbind click handler to avoid field being cleared again
})
I think you can do it without jQuery try this
<p><input type="text" class = "class-1" onclick="this.value='';" value="Enter Choice # 1"/></p>
To do it inline like that, you need to keep the this.value=''
as part of the string:
$('<p><input type="text" class = "class-'+ (++i) +'" onclick="this.value=\'\'" value="Enter Choice #' + i + '"/></p>');
Notice the " onclick="this.value=\'\'"
, where the single quotes are escaped to keep the main string from being terminated.
Here's a working example for you.
var i = 0;
$('<input type="text" class="class-'+ ++i +'" value="Enter Choice #' + i + '"/>')
.click(function(){
this.value = '';
})
.wrap('<p />')
.parent()
.appendTo('#container');
http://jsfiddle.net/jruddell/FVqjQ/
精彩评论