简体   繁体   中英

How to set onblur and onfocus string for placeholder when using jQuery

I have tried to update my html dynamically and it is working so far that the textarea is being added to the page but the onblur and onfocus behaviour that I have defined aren't due I think to the inclusion of double quotations on the onblur and onfocus properties. My code is as follows:

$('#answerList').append('<li><div class="row"><div class="eight columns"><textarea id="answerText" name="answerText" placeholder="Your answer here..."  onfocus="this.placeholder = """ onblur="this.placeholder = "Your answer here...""></textarea></div><div class="four columns"><input type="checkbox" name="correctCheckbox" id="correctAnswerCheckbox' + answerPosition + '" value="' + answerPosition + '"/><label for="correctAnswerCheckbox' + answerPosition + '">Correct Answer</label></div></div></li>');

When just coding the HTML normally I use the following:

<textarea id="questionText" name="questionText" placeholder="Your question here..." onfocus="this.placeholder = ''" onblur="this.placeholder = 'Your question here...'"></textarea>

How can I fix the javascript so these properties work

""(Doubles quotes) cant escape the ''(Single Quotes). but where as the single Quotes can escape the double quotes.

In your case, i guess if you still need to want to escape single quote specified inside double quote then use a backward slash ().

<textarea id="questionText" name="questionText" placeholder="Your question here..." onfocus="this.placeholder = \'\'" onblur="this.placeholder =\ 'Your question here...\'"></textarea>

Happy Coding :)

If I have understood your problem this string might help you.

'<textarea id="questionText" name="questionText" placeholder="Your question here..." onfocus="this.placeholder = \'\'" onblur="this.placeholder = Your question here..."></textarea>'

Fiddle http://jsfiddle.net/aD38E/

You're correct that the inclusion of consecutive double-quotes is the issue. The simple fix is to escape the double-quotes with a backslash, like so:

onfocus="this.placeholder = \"\""

or

onblur="this.placeholder = \"Your answer here...\""

Here's a working JSFiddle: http://jsfiddle.net/ud36Y/

Or you can use this code:

$('input[type="text"]').focus(function () {
    $(this).data('placeholder', $(this).attr('placeholder'))
        .attr('placeholder', '');
}).blur(function () {
    $(this).attr('placeholder', $(this).data('placeholder'));
});

// $('textarea') or $('input[type="email"]')

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