Search code examples
jqueryinputplaceholderreplacewith

jQuery: Replace attr value placeholder with user input from text input


Using .replaceWith() and .val() I was able to replace the title but when trying to access the placeholder .attr() of the input, I am unable to replace it. Here is what I have:

<p class="title">Title</p>
<p><input class="placeholder" type="text" placeholder="Placeholder" disabled /></p>
<p><input class="newText" type="text" /></p>
<p><input class="newPlaceholder" type="text" /></p>
<p><input type="button" class="button" title="button" /></p>

$("input.button").click(function(){
    var newText = $("input.newText").val();
    $("p.title").replaceWith(newText);

    var newPlaceholder = $("input.newPlaceholder").val();
    $("input.placeholder").attr("placeholder").replaceWith(newPlaceholder);
});

JSFiddle


Solution

  • .replaceWith() isn't used to set properties of HTML elements. You want to use .prop():

    Get the value of a property for the first element in the set of matched elements or set one or more properties for every matched element

    To set the placeholder property of your text box, you can use .prop() like this:

    var newPlaceholder = $("input.newPlaceholder").val();
    $("input.placeholder").prop("placeholder", newPlaceholder);
    

    I've updated your JSFiddle to show an example.