Search code examples
javascripthtmlforms

How to get the text from a input field then set it as a placeholder for a different input field?


I am making a form builder. I would like for the user to be able to set the the placeholder text of an input field by typing what they would like it to be in a different input field.

So far I have tried this:

HTML:

    <label>Title</label>
    <input type="text" id="Title" class="form-control" placeholder="">
    <div class="row">
        <div class="col">
            <label>Placeholder</label>
            <input type="text" id="PlaceHolder" class="form-control form-control-sm">
        </div>
        <div class="col">
            <button type="button" onclick="Confirm()" class="btn btn-primary btn-sm">Confirm</button>
        </div>
    </div>

JavaScript:

    function Confirm() {
    var x = document.getElementById("Title");
    var y = document.getElementById("PlaceHolder");
    x.setAttribute("placeholder", y.innerText);
    console.log(x.innerText);
    }

However, the placeholder value for the first input field doesn't change and the console.log returns an empty space.


Solution

  • There are two problems with your code: You switched x and y - and you need to use value instead of innerText

    function Confirm() {
      var x = document.getElementById("Title");
      var y = document.getElementById("PlaceHolder");
      y.setAttribute("placeholder", x.value);
    }
    <label>Title</label>
    <input type="text" id="Title" class="form-control" placeholder="">
    <div class="row">
        <div class="col">
            <label>Placeholder</label>
            <input type="text" id="PlaceHolder" class="form-control form-control-sm">
        </div>
        <div class="col">
            <button type="button" onclick="Confirm()" class="btn btn-primary btn-sm">Confirm</button>
        </div>
    </div>