简体   繁体   中英

Replacing or Adding an onfocus & onblur function to a textbox within a jQuery function

I have a textbox which has a text value and onfocus and onblur functions attached which make the text disappear and appear when clicking on or off it...

The functions for onblur and onfocus attached to the textbox is...

function feedbackTextBoxFocus(textFieldObject, initialText) {
if (textFieldObject) {
    if (textFieldObject.value == initialText)
        textFieldObject.value = '';
}
}
function feedbackTextBoxBlur(textFieldObject, initialText) {
if (textFieldObject) {
    if (textFieldObject.value == '')
        textFieldObject.value = initialText;
}
}

The textbox is...

<asp:TextBox ID="TxtAskQuestionTitle" runat="server" CssClass="KBTopQuestionTitleTextbox" Text="Ask a question on this topic..." onblur="feedbackTextBoxBlur(this,'Ask a question on this topic...')" onfocus="feedbackTextBoxFocus(this,'Ask a question on this topic...')" />

What i want to do via a jquery method i have which makes a content area slide down when the textbox has been clicked on, is to change the text within the textbox and have the onblur and onfocus values change to "Provide a title for your question..."

$(function () {
$('.QuestionContentExpandClick').click(function () {

    /**** Slide the content div ****/
    var viewContent = $('#DivExpandQuestionContentArea');
    viewContent.slideDown('slow', function () {

        //  If logged in and sliding the content area down
        //  the title box message changes

        var titleTextbox = $('#TxtAskQuestionTitle');
        titleTextbox.val('Provide a title for your question...');
        //titleTextbox.attr('onfocus', feedbackTextBoxFocus(this,'Provide a title for your question...'));
        //titleTextbox.attr('onblur', feedbackTextBoxBlur(this, 'Provide a title for your question...'));

    });
});
});

As you can see i am able to change the text value within the textbox but cannot find a way to change the onblur and onfocus functions, can anyone help me with this? Many thanks in advance!

If you use parenthesis when putting a callback function, you are not passing reference, instead you are executing the function. Also, you just want to use the .focus() and .blur() functions. Try like so:

titleTextbox.focus(function() {
    feedbackTextBoxFocus(this,'Provide a title for your question...');
});
titleTextbox.blur(function() {
    feedbackTextBoxBlur(this, 'Provide a title for your question...');
});

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