Change placeholder text with jquery also auto

I use the placeholder attribute to show some info in the input field. To support this in IE I use jquery. The code works in IE. However, depending on what a user selects in a dropdown list, the value of the placeholder in certain input fields needs to change as well and here is the problem.

Adjusting the value in the placeholder attribute doesn't automatically change the value of the input field.

The code I use is this to determine the value of the input field is:

if(!$.support.placeholder) { 
    var active = document.activeElement;
    $('input[type=text], textarea').focus(function () {
        if ($(this).attr('placeholder') != '' && $(this).val() == $(this).attr('placeholder')) {
            $(this).val('').removeClass('hasPlaceholder');
        }
    }).blur(function () {
        if ($(this).attr('placeholder') != '' && ($(this).val() == '' || $(this).val() == $(this).attr('placeholder'))) {
            $(this).val($(this).attr('placeholder')).addClass('hasPlaceholder');
        }
    });

And when I want to change the attribute text I do in a function called SetPlaceholderText:

$("#affected-input-field").attr("placeholder", "New placeholder text");

However this does not resolve my problem.

Basically what I want to do is:

<input id="affected-input-field" value="Old placeholder text" placeholder="Old placeholder text" />

PSEUDO CODE:

if($('#dropdown').val() == '1') {
    $(#affected-input-field).SetPLaceholderText("New Placeholder text...");
}

And from the moment that code is run the text that is visible in the input field is the new value:

<input id="affected-input-field" value="New placeholder text" placeholder="New placeholder text" />

BUT only if the input field is empty and not already filled in.

I'm wondering, does the code of https://github.com/mathiasbynens/jquery-placeholder help me with this? Because from what I see, that code contains a function to change the value of the placeholder.


Problem solved, stupid mistake, in IE developer tools I didn't look at the console. There I saw that a variable wasn't correctly defined... epic facepalm.

To be more precise: My extension function for jQuery to change the placeholder text had a line:

$(this).addClass(placeHolderStylingClass);

But the variable placeHolderStylingClass was not set in the function, this was a stupid copy/paste mistake from my setPlaceholder function.

链接地址: http://www.djcxy.com/p/70572.html

上一篇: 是否有可能拥有“永久”占位符?

下一篇: 使用jquery更改占位符文本也是自动的