user7933742
user7933742

Reputation:

How to construct <input> in javascript with custom placeholder

Custom placeholders can be constructed along with text areas in Javascript like this:

var custom_placeholder = "hello";

html = '<textarea class="form-control">' + custom_placeholder + '</textarea>';

However, I cannot figure out how to do this for input tags. Below does not work. The custom placeholder appears outside the input box. So how can this be done?

html += '<input type="text"/>' + custom_placeholder;

The following syntax is not allowed as well.

html += '<input type="text">' + custom_placeholder + '</input>';

Upvotes: 0

Views: 939

Answers (3)

Slam
Slam

Reputation: 14

Just use html input's placeholder attribute to set placeholder text:

let html,customPlaceholder;
html += '<input type="text" placeholder="' + customPlaceholder + '" />'

Or, if what you are looking for is actually a preset value (that the user will have to delete to enter their own input), use html's value attribute:

let html,customPlaceholder;
html += '<input type="text" value="' + customPlaceholder + '" />'

Upvotes: -1

cнŝdk
cнŝdk

Reputation: 32145

All you need is to concatenate the placeholderattribute within your String, like this:

html += '<input type="text" placeholder="' + custom_placeholder + '"/>';

Demo:

This is a working snippet:

var html = "";
var custom_placeholder = "A Text input";

html += '<input type="text" placeholder="' + custom_placeholder + '"/>';

document.body.innerHTML = html;

Note:

  • You better create the elements dynamically and append their attributes using JavaScript.
  • You don't need </input> for inputs in HTML, just add a / before closing your input tag.
  • Also make sure the custom_placeholder variable doesn't contain special characters such as " or '.

Upvotes: 1

Badacadabra
Badacadabra

Reputation: 8497

Vanilla JS

var txt = 'Hello',
    input = document.createElement('input');
    
input.setAttribute('type', 'text');
input.setAttribute('placeholder', txt);

document.body.appendChild(input);

jQuery

var txt = 'Hello';

$('body').append('<input type="text">');
$('input').attr('placeholder', txt);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

Upvotes: 1

Related Questions