简体   繁体   中英

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 + '"/></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
     })

我想你可以不用jQuery就能做到这一点

<p><input type="text" class = "class-1" onclick="this.value='';" value="Enter Choice # 1"/></p>
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/

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM