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>';
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>
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 '.
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 + '" />'
Related
I want to give a name to my dynamically created textbox on a specific event.
I have written the following code where the function GenerateTextBox returns the name of the textbox and the value "". The textbox is generated by but the name does not get assigned.
This is to use the name as a reference to the textbox in another php file.
Jquery code for generating textbox:
function GenerateTextbox(value,name1) {
return '<input name = "'+ name1 + '" type="text" value = "' + value + '" /> ';
}
Calling the function:
$("#t11, #t12").click(function(){
var div = $("<div />");
div.html(GenerateTextbox("", c1));
$("#TextBoxContainer").append(div);
});
The php output file is showing the error that c1 is an undefined index...
How do I solve this problem?
Change c1 to "c1". c1 refers to a variable named c1 (which you have not defined) whereas "c1" refers to a String.
div.html(GenerateTextbox("", "c1"));
Working Code:
function GenerateTextbox(value,name1) {
return '<input name = "'+ name1 + '" type="text" value = "' + value + '" />';
}
$("#t11, #t12").click(function(){
var div = $("<div>");
div.html(GenerateTextbox("", "c1"));
$("#TextBoxContainer").append(div);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="t11">Create Textbox</button>
<div id="TextBoxContainer"></div>
I'm trying to dynamically generate a form after an ajax request. Below is the relevant code sample :
for (var i in response.responseJSON[0].fields) {
var field = response.responseJSON[0].fields[i];
$('#properties_form').append('<label for=' + i + '>' + i + '</label>' +
'<input id=' + i + ' value=' + field + '>');
}
My problem is that, when var i and var field are strings with blank spaces like "Hello world", my label and inputs will be like <label id="Hello" world=""> and <input value="Hello" world="">. However, the label text will be displayed correctly i.e. <label>Hello world</label>.
I've no idea what kind of sorcery that is, but I'll be very grateful for any help. Thanks in advance.
There's a much more robust way of doing this.
for (var i in response.responseJSON[0].fields) {
var field = response.responseJSON[0].fields[i];
$('#properties_form')
.append($('<label>').attr('for', i).text(i))
.append($('<input>').attr('id', i).val(field));
}
You won't have to worry about the content of the strings as jQuery and the DOM will handle it for you. Not to mention this is much easier to read.
Use " to enclose the attributes.
$('#properties_form')
.append('<label for="' + i + '">' + i + '</label>' +
'<input id="' + i + '" value="' + field + '">');
EDIT
This will break for the cases where the value for i is something like This "works". Best solution is to append as jQuery or JS objects rather than using HTML string just like Daniel's answer.
Following snippet contains the correct fix for this. Updated based on the answer from Daniel.
i = 'Hello "World"';
field = 'Hello "World"s';
$('#properties_form')
.append($('<label>').attr('for', i).text(i))
.append($('<input>').attr('id', i).val(field));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="properties_form"></div>
I have a written a javascript which will return the value in the variable, in the title property.
It is not returning the values with spaces, when i execute the below code it is returning the last value as 'ashok' instead of 'ashok sensiple'
var ltenantName = 'Sensiple,new-tenant-001,tenant-new,Tenant_1208,ashok sensiple';
var ltenantNameLength = '<div style="cursor:Pointer" title='
+ ltenantName
+'>'
+ ltenantName.split(',').length
+'</div>';
return ltenantNameLength;
HTML attribute values containing spaces must be quoted.
You are generating the title attribute without quotes around the value.
Your code:
var ltenantName = 'Sensiple,new-tenant-001,tenant-new,Tenant_1208,ashok sensiple';
var ltenantNameLength = '<div style="cursor:Pointer" title='
+ ltenantName
+'>'
+ ltenantName.split(',').length
+'</div>';
document.body.appendChild(document.createTextNode(ltenantNameLength));
As you can see sensiple is a new attribute and not part of the value of the title attribute.
Add quotes:
var ltenantName = 'Sensiple,new-tenant-001,tenant-new,Tenant_1208,ashok sensiple';
var ltenantNameLength = '<div style="cursor:Pointer" title="'
+ ltenantName
+'">'
+ ltenantName.split(',').length
+'</div>';
document.body.appendChild(document.createTextNode(ltenantNameLength));
Better yet, don't try to mash strings together in JS to make HTML:
var ltenantName = 'Sensiple,new-tenant-001,tenant-new,Tenant_1208,ashok sensiple';
var ltenantNameLength = document.createElement('div');
// This normally indicates a link. If you want a link, why not use <a>?
ltenantNameLength.style.cursor = "pointer";
ltenantNameLength.title = ltenantName;
ltenantNameLength.appendChild(
document.createTextNode(
ltenantName.split(',').length
)
);
document.body.appendChild(ltenantNameLength);
I added textbox value as Baker's Basket, Pune, Maharashtra, Indiasd but on click event in textbox it only shows Baker's
I want to display whole text Baker's Basket, Pune, Maharashtra, Indiasd in the textbox.
JS FIDDLE EXAMPLE
// Try to Enter text given bellow
//Baker's Basket, Pune, Maharashtra, Indiasd
$("#clk").on('click', function () {
$("#cnt_div").empty();
var getTxt = $("#txt_n").val();
var addContent = "<input type='text' value=" + getTxt + " />";
$("#cnt_div").append(addContent);
});
without editng addContent variable
Edited:
JS FIDDLE SAMPLE TWO
$("#clk").on('click', function () {
var gData1 = $("#txt_1").val();
var gData2 = $("#txt_2").val();
var gData3 = $("#txt_3").val();
var cnt_1 = "<span class='lbl_normal_mode'>" + gData1 + "</span><input class='txt_edit_mode' value=" + gData1 + " type='text'/>";
var cnt_2 = "<span class='lbl_normal_mode'>" + gData2 + "</span><input class='txt_edit_mode' value=" + gData2 + " type='text'/>";
var cnt_3 = "<span class='lbl_normal_mode'>" + gData3 + "</span><input class='txt_edit_mode' value=" + gData3 + " type='text'/>";
var content_Data = "<div class='chunk_div_holder'><div style='float:left:width:100%'>" + cnt_1 + "</div><div style='float:left:width:100%'>" + cnt_2 + "</div><div style='float:left:width:100%'>" + cnt_3 + "</div></div>";
$(".dynmic_cntt").append(content_Data);
});
You should better append the element and its properties dynamically as an object:
$('<input>', {
type: 'text',
value: $("#txt_n").val()
}).appendTo($("#cnt_div").empty());
This will solve the problem of extra spaces (no quotes for value=Baker's Basket), wrong string escape (if the value will have quotes) for value attribute and other caveats.
N.B.: There is no textbox type for <input> element. It should be text instead.
DEMO: http://jsfiddle.net/ZyMCk/11/
Add the field in two stages:
add the field as you are already
set the value of the field using .val()
It is because you aren't escaping ' single quote.
Instead you can replace
this line
var addContent="<input type='textbox' value='"+getTxt+"' />";
with
var addContent=$("<input type='textbox' />").val(getTxt);
or
var addContent="<input type='textbox' value=\""+getTxt+"\" />";
Value attribute should enclose in quotes. In your case, its better to use double quotes, because Baker's Basket, Pune, Maharashtra, Indiasd already have a single quote in it.
$("#clk").on('click',function(){
$("#cnt_div").empty();
var getTxt=$("#txt_n").val();
var addContent="<input type='textbox' value=\""+getTxt+"\" />";
$("#cnt_div").append(addContent);
});
Fiddle
Edit
$("#clk").on('click',function(){
$("#cnt_div").empty();
var getTxt=$("#txt_n").val();
var addContent=$("<input/>",{type:"text",value:getTxt});
$("#cnt_div").append(addContent);
});
Updated fiddle
change "+getTxt+" to '"+getTxt+"'
fiddle
OR
change "+getTxt+" to \""+getTxt+"\"
Heres a better way of doing this...
var addContent=$("<input type='textbox' />").val(getTxt);
http://jsfiddle.net/ZyMCk/9/
Basically, if creating an element to append to the DOM your better off doing this as a jQuery object. This way we can take advantage of methods such as val() for adding the value.
UPDATE
Ive simplified things a bit for you...
JSFIDDLE: http://jsfiddle.net/ZyMCk/22/
$("#clk").on('click', function () {
$('.dynmic_cntt').empty();
$('.form-text').each(function(){
var $div = $('<div style="float:left:width:100%;"></div>');
var $span = $('<span class="lbl_normal_mode">'+ $(this).val() +'</span><input class="txt_edit_mode" value="'+$(this).val() +'" type="text"/>');
$('.dynmic_cntt').append( $div.append( $span ) );
});
});
I've got a problem with another dojo enabled form that I am working on. A user can enter details onto the page by entering the data using a dialog box, which in turn updates the database and then displays the user data entered on to the form.
Each element added consist of 2 x Validation Text boxes 1 x FilteringSelect. When it's added to the page they are added as simply text boxes.
I've tried just adding as standard strings but that means the dojo.parse() does not run on the code. I've also tried programmatically adding the elements but that just displays the element object as a string to the page. So far I have:
var xhrArgs = {
url: url,
handleAs: "text",
preventCache: true,
load: function(data){
var idResult = parseInt(data);
if(idResult > 0){
var divStr = '<div id="employ_' + idResult + '" style="float:left;width:100%;">' +
'<table width="300">' +
'<tr>' +
'<td height="29"><Strong>' +
'<input type="text" dojoType="dijit.form.ValidationTextBox ' +
'change="markEmploymentForUpdate(); ' +
'id="cmpy_'+ idResult +'" '+
'required="true" ' +
'promptMessage="Please enter a valid company name" ' +
'invalidMessage="please enter a valid company name" ' +
'trim="true"' +
'value="'+ companyname +'"/>' +
'</td>' +
'<td height="29"><input dojoType="dijit.form.FilteringSelect" store="rolestore" searchAttr="name" name="role" onchange="markEmploymentForUpdate();" id="roleInput_'+ idResult +'" value="'+ jobrole +'" ></td>' +
'<td height="29">' +
'<input type="text" dojoType="dijit.form.ValidationTextBox" onchange="markEmploymentForUpdate();"' +
'id="jtitle_'+ idResult + '"' +
'required="true"' +
'promptMessage="Please enter your job title"' +
'invalidMessage="Please enter your job title"' +
'value="'+ jobtitle + '"/>' +
'</td>' +
'<td height="29"><img src="/images/site/msg/small/msg-remove-small.png" border="0" onmouseover="this.style.cursor=\'pointer\';" onclick="removeEmployer(\'employ_'+ idResult +'\', '+ idResult +')" /></td>' +
'</tr>' +
'</table>' +
'</div>';
dijit.byId('companydetails').hide();
dijit.byId('employername').setValue('');
dijit.byId('jobtitle').setValue('');
dijit.byId('jobrole').setValue('');
dojo.byId('data-table').innerHTML += divStr;
dojo.byId('companydetails').hide();
}else{
dojo.byId('add-error').innerHTML = '<div class="error">Unable to process your request. Please try again.</div>';
}
}
};
var deferred = dojo.xhrGet(xhrArgs);
This is displaying text boxes as the dojo.parse isn't running on this. If I replace the ValidationTextBox with:
var textbox = new dijit.form.ValidationTextBox({
id:"cmpy_" + idResult,
required:true,
trim:true,
"change":"markEmploymentForUpdate();",
promptMessage:"Please enter a valid company name",
value:companyname
});
I just get the object printed to the page.
Any ideas how I can added this to my page and maintain the dojo component rather than it defaulting to a text box?
Many thanks.
dojo.parser.parse(dojo.byId('data-table')); after you set it's innerHTML