mathiasbynens / jquery-placeholder

A jQuery plugin that enables HTML5 placeholder behavior for browsers that aren’t trying hard enough yet
https://mths.be/placeholder
MIT License
3.98k stars 1.34k forks source link

Can't dynamically modify the placeholder text #281

Open RustyTheBoyRobot opened 8 years ago

RustyTheBoyRobot commented 8 years ago

placeholder version: 2.3.0 jQuery version: 1.10.2 Browsers: IE 7-9 (couldn't test 6)

Reproduction Steps:

  1. Open the demo page in IE 10: https://mathiasbynens.github.io/jquery-placeholder/
  2. In the Javascript Console, run this: $("[name=search]").attr("placeholder", "Changed!");. Notice that the first text box has the placeholder text of "Changed"
  3. Open the demo page in IE 9 or older
  4. In the Javascript Console, run this: $("[name=search]").attr("placeholder", "Changed!");. Notice that the first text box's placeholder text is unchanged.

This also means that the placeholder text will not get cleared out on focus, since the value does not match the placeholder attribute value.

If this functionality is outside of the scope of this plugin, so be it. I just didn't see anything in the documentation that says that you can't do this.

RustyTheBoyRobot commented 8 years ago

This seems to be working for me as a workaround:

    function changePlaceholderText(element, text)
    {
        var $element = $(element);
        var currentVal = $element.val();

        var needsInputFix = ($element.is("input") && !$.fn.placeholder.input);
        var needsTextAreaFix = ($element.is("textarea") && !$.fn.placeholder.textarea);

        $element.attr("placeholder", text);
        if (currentVal === "" && (needsInputFix || needsTextAreaFix))
        {
            $element[0].value = text;
        }
    }

It simply modifies the DOM element's value to match the new placeholder text so that the onfocus code will strip out the text correctly.

cailingling commented 8 years ago

I also encountered this problem, how to solve

myadzel commented 8 years ago

You can change placeholder value this way:

var currentInputValue = $element.val();
$element.attr("placeholder", "new placeholder value").val(currentInputValue);