Reputation:
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
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
Reputation: 32145
All you need is to concatenate the placeholder
attribute 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:
</input>
for inputs in HTML, just add a /
before closing your input tag.custom_placeholder
variable doesn't contain special characters such as "
or '
.Upvotes: 1
Reputation: 8497
var txt = 'Hello',
input = document.createElement('input');
input.setAttribute('type', 'text');
input.setAttribute('placeholder', txt);
document.body.appendChild(input);
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