Reputation: 615
I have one image, when I am clicking on that image, I am getting one textbox and a button. By clicking on button, I want to put that textbox values in separate spans inside a div with id demo. Ho I can do that using javascript only?
Here is the function in which I was trying the same(I am trying so lots of error must be there)
function addTag(){
var text = document.getElementById('title').value;
//console.log(text);
var demoid = document.getElementById('demo');
console.log(demoid);
var spa = document.createElement('span');
spa.id = text;
spa.appendChild(demoid);
var text = text+' , ';
spa.innerHTML = text;
console.log(spa.id);
jQuery("#form_panel").hide();
jQuery("#someID").hide();
console.log("in addTag");
}
Upvotes: 10
Views: 36748
Reputation: 597
You better use jQuery.
You can use $.add() or $.append() functions.
Visit https://api.jquery.com/append/ for more information.
Hope this will help you!!
Upvotes: 1
Reputation: 31
Using the Javascript functions createElement()
and appendChild()
will work for you.
Upvotes: 2
Reputation: 20141
To create a span element in javascript:
var newSpan = document.createElement('span');
Add it to the DOM tree in the right place, say inside the 'demo' div:
document.getElementById('demo').appendChild(newSpan);
So a textbox in a span in that div:
var newTextbox = document.createElement('input');
newTextbox.type = 'textbox';
var newSpan = document.createElement('span');
var demodiv = document.getElementById('demo');
newSpan.appendChild(newTextbox);
demodiv.appendChild(newSpan);
console.log(demodiv.innerHTML);
Console yields:
<span><input type=\"textbox\"></span>
The alternative is to construct a complete chunk of HTML (performance may vary):
document.getElementById('demo').innerHTML += "<span><input type='textbox'></span>";
-- Edit after seeing your code --
It looks like you are doing spanElement.appendChild(divElement)
, but that is attempting to insert the div inside the span. You want to insert the span into the div, so you need divElement.appendChild(spanElement)
.
Upvotes: 12
Reputation: 20740
Try like following using jQuery:
$('button').on('click',function (e) {
$('#demo').append('<span>'+$('textbox').val()+'</span>');
});
Upvotes: 6