how to add text boxes dynamically without losing values of previous textboxes? - javascript

i am using innerHTML to add text boxes dynamically. The code sample is as follows:
<html>
<head>
<script type="text/javascript" >
var i=0;
function add()
{
var tag = "<input type='text' name='" + i + "' /> <br/>";
document.getElementById("y").innerHTML += tag;
i++;
}
</script>
</head>
<body>
<input type="button" id="x" value="Add" onclick="add();" />
<div id="y"></div>
</body>
</html
Are there any ways to add text boxes dynamically without losing values of previous text box when a new text box is added?
Similar question has been posted, but there are no answers :(
What if I want to add textbox in this situation:
function add() {
var element='<li class="ie7fix" style="width:620px;"><div class="m_elementwrapper" style="float:left;"><label class="fieldlabel" style="width:106px;float:left;padding-top:3px;" for="p1f4"><span><span class="pspan arial" style="text-align:right;font-size:14px;"><span class="ispan" xml:space="preserve"></span></span></span></label><div style="float:left;width:475px;" class="m_elementwrapper"><input type="text" style="font-family:Arial, Helvetica, sans-serif;font-size:14px;width:244px;max-width:244px;" name="' + i + '" class="fieldcontent"><div class="fielderror"></div></div></div><div style="clear:both;font-size:0;"></div></li>';
document.getElementById("addskills").innerHTML += element;
i++;
}

Yes, through DOM Manipulation:
function add() {
var tag = document.createElement('input'); // Create a `input` element,
tag.setAttribute('type', 'text'); // Set it's `type` attribute,
tag.setAttribute('name', i); // Set it's `name` attribute,
var br = document.createElement('br'); // Create a `br` element,
var y = document.getElementById("y"); // "Get" the `y` element,
y.appendChild(tag); // Append the input to `y`,
y.appendChild(br); // Append the br to `y`.
i++;
}
This doesn't trigger the browser's DOM parser like a innerHTML does, leaving everything intact.
(innerHTML forces the browser to re-parse the entire DOM, because anything could be added with innerHTML, so the browser can't predict anything, in contrast to adding a node to a element.)
Now, to add this:
<li class="ie7fix" style="width:620px;">
<div class="m_elementwrapper" style="float:left;">
<label class="fieldlabel" style="width:106px;float:left;padding-top:3px;" for="p1f4">
<span>
<span class="pspan arial" style="text-align:right;font-size:14px;">
<span class="ispan" xml:space="preserve">
</span>
</span>
</span>
</label>
<div style="float:left;width:475px;" class="m_elementwrapper">
<input type="text" style="font-family:Arial, Helvetica, sans-serif;font-size:14px;width:244px;max-width:244px;" name="' + i + '" class="fieldcontent">
<div class="fielderror">
</div>
</div>
</div>
<div style="clear:both;font-size:0;">
</div>
</li>
You'll need:
function add() {
// Create elements
var d1 = c('div'), s1 = c('span'), ip = c('input'),
d2 = c('div'), s2 = c('span'), li = c('li'),
d3 = c('div'), s3 = c('span'), la = c('label'),
d4 = c('div');
// You can "chain" `appendChild`.
// `li.appendChild(d1).appendChild(la);` is the same as `li.appendChild(d1); d1.appendChild(la);`
li.appendChild(d1).appendChild(la).appendChild(s1).appendChild(s2).appendChild(s3);
d1.appendChild(d2).appendChild(ip);
d2.appendChild(d3);
li.appendChild(d4);
setAttributes(
[li, d1, la, s2, s3, d2, ip, d3, d4],
[
{'class':"ie7fix", 'style':"width:620px;" },
{'class':"m_elementwrapper", 'style':"float:left;" },
{'class':"fieldlabel", 'style':"width:106px;float:left;padding-top:3px;", 'for':"p1f4" },
{'class':"pspan arial", 'style':"text-align:right;font-size:14px;" },
{'class':"ispan", 'xml:space':"preserve" },
{'class':"m_elementwrapper", 'style':"float:left;width:475px;" },
{'class':"fieldcontent", 'type':"text", 'style':"font-family:Arial, Helvetica, sans-serif;font-size:14px;width:244px;max-width:244px;", 'name':''+i},
{'class':"fielderror" },
{'style':"clear:both;font-size:0;" }
]
);
var br = document.createElement('br'); // Create a `br` element,
var y = document.getElementById("y"); // "Get" the `y` element,
y.appendChild(li); // Append the input to `y`,
y.appendChild(br); // Append the br to `y`.
i++;
}
// Apply a array of attributes objects {key:value,key:value} to a array of DOM elements.
function setAttributes(elements, attributes){
var el = elements.length,
al = attributes.length;
if(el === al){
for(var n = 0; n < el; n++){
var e = elements[n],
a = attributes[n];
for(var key in a){
e.setAttribute(key, a[key]);
}
}
}else{
console.error("Elements length " + el + " does not match Attributes length " + al);
}
}
// Alias for shorter code.
function c(type){
return document.createElement(type);
};

use jquery library
<html>
<head>
<script src='jquery.js' type="text/javascript"></script>
<script type="text/javascript" >
var i=0;
function add()
{
var tag = "<input type='text' name='" + i + "' /> <br/>";
var div_content=$('#y').append(tag);
i++;
}
</script>
</head>
<body>
<input type="button" id="x" value="Add" onclick="add();" />
<div id="y"></div>
</body>
</html>

I've got round this before by reading all of the values into an array before replacing the innerHTML and then writing them back again afterwards. This way you can write whatever you like into the div. Following works on all browsers that I have tried:
<html>
<head>
<script type="text/javascript" >
var i=0;
function add() {
if(i>0) {
values=new Array();
for(z=0;z<i;z++) {
values.push(document.getElementById(z).value);
}
}
var tag = '<input type="text" name="' + i + '" id="' + i + '" /> <br/>';
document.getElementById("y").innerHTML += tag;
if(i>0) {
for(z=0;z<i;z++) {
document.getElementById(z).value=values[z];
}
}
i++;
}
</script>
</head>
<body>
<input type="button" id="x" value="Add" onclick="add();" />
<div id="y"></div>
</body>
</html>

Related

JS: change "var y = UNDEFINED" for "var y= blank space" with if

I have a table generated from a textarea filled by users, but some of the time, a cell stays empty (and that's all right).
The thing is that the .innerHTML of that cell is also my var y in a script and when that cell is empty (therefore, undefined), my var y becomes UNDEFINED too (the value, not a string), which makes my whole script fail.
Here's a snippet to show the problem:
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</head>
<body><center>
</center></body>
<!--------- script that generates my table from text areas -->
<script>
function generateTable() {
$('#excel_table1').html("");
var n=1;
var rows=[];
var lng=0;
var maxligne=0;
$('textarea').each(function(){
var data = $(this).val();
if (data !=''){
var rowData = data.split("\n");
rows[n] = rowData;
lng = rowData.length;
if(lng > maxligne)
{
maxligne=lng
}
n++;
}
}
)
var table = $('<table />');
k=0;
while (k < maxligne) {
var row = $('<tr />');
for(var i = 1; i < rows.length; i++)
{
var singleRow = rows[i];
if(singleRow[k]!= undefined){
row.append('<td>'+singleRow[k]+'</td>')
} else {
row.append('<td></td>')
}
}
table.append(row);
k++;
}
$('#excel_table1').append(table);
}
</script>
<textarea placeholder="data 2 Here" name="data1" style="width:100px;height:40px;"></textarea>
<textarea placeholder="data 2 Here" name="data2" style="width:200px;height:40px;"></textarea>
<textarea placeholder="fild not required" name="data3" style="width:200px;height:40px;"></textarea>
<br>
<input id=bouton1 type="button" onclick="javascript:generateTable()" value="GenerateTable"/>
<div id="excel_table1"></div>
<!--------- script that get the data from cells to show it in <H2> -->
<script type="text/javascript">
function buttonTEST()
{
$('#displayCell').html("");
var x = document.getElementById('excel_table1').getElementsByTagName('tr')[0].cells[1].innerHTML;
var y = document.getElementById('excel_table1').getElementsByTagName('tr')[0].cells[2].innerHTML;
if (y === undefined) {
y = " ";
}
document.getElementById('displayCell').innerHTML = x +" "+ y;
}
</script>
<br/><br/>
<h2 id="displayCell"></h2>
<br/><br/>
<input id="Button2" type="button" onclick="buttonTEST()" value="TEST ME"/>
As you can see, if you generate a table with only to columns (which is supposed/needs to happen sometimes), we get this error from the console because we're trying to get "innerHTML" from a undefined:
index.html:120 Uncaught TypeError: Cannot read property 'innerHTML' of undefined
A little specification: When that cell is=undefined , I need it to stay undefined, I only want to change the fact that my var y also becomes undefined.
So I thought that changing the value of var y (and not the value of that cell, otherwise, the 3rd column, supposed to be empty, would be created just because of an blank space) to a blank space would resolve the problem, but I don't seem to get it right (write it in a correct manner).
Any ideas?
Try
var x = document.getElementById('excel_table1').rows[0].cells[0].innerHTML;
var y = document.getElementById('excel_table1').rows[0].cells[1].innerHTML;
using rows instead of getElementsByTagName is cleaner.
Also note that the indexes for cells start from zero not 1, you probably only have 2 cells in your first row, but .cells[2].innerHTML tries to get the innerHTML of the 3rd cell which does not exist.
As others have pointed out, you're already using jQuery, so the easiest way to get the cell contents is to use a css selector to find the cells using the $ function, then call .html() to get the contents. A direct conversion of your current code to this approach could be:
var x = $('#excel_table1 tr:nth-child(1) td:nth-child(2)').html();
var y = $('#excel_table1 tr:nth-child(1) td:nth-child(3)').html();
This works in a way so that the $ function returns a jQuery object, which is essentially a set of elements, which can potentially be empty. Most jQuery functions are then designed to fail gracefully when called on an empty set. For instance, html will return undefined when invoked on an empty set, but it will not fail.
Note that it is not very robust to use the selector above, as it is obviously sensitive to the placement of the cells. It would be more maintainable to assign a class attribute to the cells that describes their content, and then select on that, e.g. something like
var name = $("#excel_table1 tr:nth-child(1) td.name").html()
So here's the answer that worked for me:
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</head>
<body><center>
</center></body>
<!--------- script that generates my table from text areas -->
<script>
function generateTable() {
$('#excel_table1').html("");
var n=1;
var rows=[];
var lng=0;
var maxligne=0;
$('textarea').each(function(){
var data = $(this).val();
if (data !=''){
var rowData = data.split("\n");
rows[n] = rowData;
lng = rowData.length;
if(lng > maxligne)
{
maxligne=lng
}
n++;
}
}
)
var table = $('<table />');
k=0;
while (k < maxligne) {
var row = $('<tr />');
for(var i = 1; i < rows.length; i++)
{
var singleRow = rows[i];
if(singleRow[k]!= undefined){
row.append('<td>'+singleRow[k]+'</td>')
} else {
row.append('<td></td>')
}
}
table.append(row);
k++;
}
$('#excel_table1').append(table);
}
</script>
<textarea placeholder="data 2 Here" name="data1" style="width:100px;height:40px;"></textarea>
<textarea placeholder="data 2 Here" name="data2" style="width:200px;height:40px;"></textarea>
<textarea placeholder="fild not required" name="data3" style="width:200px;height:40px;"></textarea>
<br>
<input id=bouton1 type="button" onclick="javascript:generateTable()" value="GenerateTable"/>
<div id="excel_table1"></div>
<!--------- script that get the data from cells to show it in <H2> -->
<script type="text/javascript">
function buttonTEST()
{
$('#displayCell').html("");
var x = $('#excel_table1 tr:nth-child(1) td:nth-child(2)').html();
var y = $('#excel_table1 tr:nth-child(1) td:nth-child(3)').html();
if (y ===undefined)
{document.getElementById('displayCell').innerHTML = x ;}
else
{document.getElementById('displayCell').innerHTML = x +" "+ y;}
}
</script>
<br/><br/>
<h2 id="displayCell"></h2>
<br/><br/>
<input id="Button2" type="button" onclick="buttonTEST()" value="TEST ME"/>

How to assign Multiple line html code as a value to a javascript variable?

This my code..
<!DOCTYPE html>
<html>
<head>
<script>
function generate(){
document.getElementById("show").style.display = "block";
var name = document.getElementById("name").value;
var school_name = document.getElementById("school_name ").value;
var school_site= document.getElementById("school_site ").value;
var content= "<h2>Student Details:</h2>"+"/n"+
"<div align='justify'>
<p>"+name+"is studing in "+school_name+"</p>"+"/n"+
"<p>Visit site: <a href='http://"+school_site+"'>http://"+school_site+"</a></p></div>";
document.getElementById("displayarea").innerHTML = content;
}
</script>
</head>
<body>
Privacy Policy Page
<p>Name:</br> <input type="text" name="name" id="name"></p>
<p>School Website:</br> <input type="text" name="school_site" id="school_site"></p>
<p>School Name:</br> <input type="text" name="school_name" id="school_name"></p>
<button id="click" onclick="generate()">Generate</button>
<div style="display:none" id="show">
<div style="height:200px; width:540px; overflow:auto;" id="displayarea">
</body>
</html>
"content" is the javascript variable.
I need to assign HTML code as value for "content" variable,
And i also need to add some Javascript variable inside the HTML
code,
How to add javascript variable in html Hypertext link?
There are many ways to achieve this. For a simple use-case, you can use an array of string to perform work and at the end you can join with "" or "\n".
var template = [
"<h2>Student Details:</h2>",
"<div align='justify'><p>"+name+"is studing in "+school_name+"</p>",
"<p>Visit site: <a href='http://"+school_site+"'>http://"+school_site+"</a></p></div>"
].join("<br/>");
For more complex case, I will say use jquery or Plain JavaScript method. As given below.
function generate(){
document.getElementById("show").style.display = "block";
var name = document.getElementById("name").value;
var school_name = document.getElementById("school_name").value;
var school_site= document.getElementById("school_site").value;
//jQuery:
var node = $('<div></div>')
.hide()
.append($('<table></table>')
.attr({ cellSpacing : 0 })
.addClass("text")
);
//Plain JavaScript
var h2 = document.createElement("h2");
h2.textContent = "Student Details:";
var div = document.createElement("div");
var p1 = document.createElement("p");
p1.textContent = name+"is studing in "+school_name;
var p2 = document.createElement("p");
p2.textContent = "Visit site: ";
div.appendChild(p1);
div.appendChild(p2);
//add attribute node
var node = document.getElementById("div1");
var a = document.createAttribute("my_attrib");
a.value = "newVal";
node.setAttributeNode(a);
//Once done return as string
return div.outerHTML;
}
You have extra space in id in school_name and school_site`.
So it is not being recognized and you are getting exception. Also your syntax to concatenate string is also incorrect.
var school_name = document.getElementById("school_name").value;
var school_site= document.getElementById("school_site").value;
Your full javascript code would be like this
<script>
function generate(){
document.getElementById("show").style.display = "block";
var name = document.getElementById("name").value;
var school_name = document.getElementById("school_name").value;
var school_site= document.getElementById("school_site").value;
var content= "<h2>Student Details:</h2>"+"/n"+
"<div align='justify'>"+
"<p>"+name+"is studing in "+school_name+"</p>"+"/n"+
"<p>Visit site: <a href='http://"+school_site+"'>http://"+school_site+"</a></p>";
document.getElementById("displayarea").innerHTML = content;
}
</script>
You can write a string on multiple lines using template literals, i.e. using the character " ` ".
You can easily integrate variables using ${yourVar} in the template literal
Example:
let lit = "literal";
var content = `This string
uses a template ${lit}`;
console.log(content);
Note: this is an ES6 feature, aka the not so new JavaScript that is not yet fully supported by browsers. To make this code compatible with older browsers, use a transpiler like babel
You have to use <br> instead of '/n' while assigning to javascript variable.
The problem as I see it is you have hit enter in the mid of string and you have extra space in the id selector.
Don't hit enter or use tilt ` to declare string instead of quotes.
<!DOCTYPE html>
<html>
<head>
<script>
function generate() {
document.getElementById("show").style.display = "block";
var name = document.getElementById("name").value;
var school_name = document.getElementById("school_name").value;
var school_site = document.getElementById("school_site").value;
var content = "<h2>Student Details:</h2>" +
"<div align='justify'><p>" + name + "is studing in " + school_name + "</p>" +
"<p>Visit site: <a href='http://" + school_site + "'>http://" + school_site + "</a></p></div>";
document.getElementById("displayarea").innerHTML = content;
}
</script>
</head>
<body>
Privacy Policy Page
<p>Name:</br>
<input type="text" name="name" id="name">
</p>
<p>School Website:</br>
<input type="text" name="school_site" id="school_site">
</p>
<p>School Name:</br>
<input type="text" name="school_name" id="school_name">
</p>
<button id="click" onclick="generate()">Generate</button>
<div style="display:none" id="show">
<div style="height:200px; width:540px; overflow:auto;" id="displayarea">
</body>
</html>
Suggestion : No need to use /n for new line, h2 is block element no need of break too.

How can I run a function when a radio is selected and I click a button?

I've created this simple code that I'll use to store in the user's browser, so, I'd like to know how can I run a function when there's a selected radio and when I click the delete button, using JS or JQuery. Any help is appreciated.
Thanks in advance.
check it on liveweave
P.S.: Your browser should have WebStorage support
var taskCounter = 1 + Number(localStorage.getItem("count"));
var name = "de"+ taskCounter;
for(var i=1;i<taskCounter;i++){
var temp = "de" + i;
document.writeln("<br/>"+'<input type="radio" name="rad" value="'+localStorage.getItem(temp)+'" /> <label>'+localStorage.getItem(temp)+'</lable>');
}
function saveItUp(){
var desc = $('#descrip').val();
alert(desc);
// Store
localStorage.setItem(name, desc);
localStorage.setItem("count", taskCounter);
// Retrieve
console.log(localStorage.getItem(name));
console.log(localStorage.getItem("count"));
}
//This is where I'm trying to do that, I know selected doesn't exist, but I put it just for a better comprehension
function deleteItUp(){
$('input:radio').selected(function(){
if (this.checked) {
alert(this.value);
}
});
}
<html>
<head>
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.min.js"></script>
</head>
<body>
<div id="main">
<label>Task</label> <textarea id="descrip"></textarea>
<button onclick="saveItUp();" id="save">Save it</button>
<button onclick="deleteItUp();" id="delete">Delete</button>
</div>
</body>
</html>
I have edited your snippet. Use $('input[type="radio"]').prop('checked') to see whether the radio button is checked. You will need to modify the selector to get the appropriate radio button if there are multiple on the page.
var taskCounter = 1 + Number(localStorage.getItem("count"));
var name = "de" + taskCounter;
for (var i = 1; i < taskCounter; i++) {
var temp = "de" + i;
document.writeln("<br/>" + '<input type="radio" name="rad" value="' + localStorage.getItem(temp) + '" /> <label>' + localStorage.getItem(temp) + '</lable>');
}
function saveItUp() {
var desc = $('#descrip').val();
alert(desc);
// Store
localStorage.setItem(name, desc);
localStorage.setItem("count", taskCounter);
// Retrieve
console.log(localStorage.getItem(name));
console.log(localStorage.getItem("count"));
}
//This is where I'm trying to do that, I know selected doesn't exist, but I put it just for a better comprehension
function deleteItUp() {
if ($('input[type="radio"]').prop('checked')) {
alert('Deleting!');
} else {
alert('Delete radio not checked!');
}
}
<html>
<head>
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.min.js"></script>
</head>
<body>
<div id="main">
<label>Task</label>
<textarea id="descrip"></textarea>
<button onclick="saveItUp();" id="save">Save it</button>
<button onclick="deleteItUp();" id="delete">Delete</button>
<input type="radio">Check to delete
</div>
</body>
</html>
I've been trying other ways to achieve it, and I found a nice way that gave me the expected result, thank all of you who tried to help me.
var taskCounter = 1 + Number(localStorage.getItem("count"));
var name = "de" + taskCounter;
for (var i = 1; i < taskCounter; i++) {
var temp = "de" + i;
document.writeln("<br/>" + '<input type="radio" name="rad" value="' + temp + '" /> <label>' + 'Code: ' + temp + ' | Value: ' + localStorage.getItem(temp) + '</lable>');
}
function saveItUp() {
var desc = $('#descrip').val();
alert(desc);
// Store
localStorage.setItem(name, desc);
localStorage.setItem("count", taskCounter);
// Retrieve
console.log(localStorage.getItem(name));
console.log(localStorage.getItem("count"));
}
var selectedRadioId = 0;
$('input:radio').change(function() {
if (this.checked) {
selectedRadioId = this.value;
}
});
function deleteItUp() {
if (selectedRadioId !== 0) {
alert('Deleting!');
} else {
alert("Radio hasn't been checked!");
}
}
<html>
<head>
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.min.js"></script>
</head>
<body>
<div id="main">
<label>Task</label>
<textarea id="descrip"></textarea>
<button onclick="saveItUp();" id="save">Save it</button>
<button onclick="deleteItUp();" id="delete">Delete</button>
</div>
</body>
</html>
You are talking about firing an event when a radio button is checked and then calling a callback function: https://api.jquery.com/checked-selector/

Changing html tags with line break Jquery / Javascript

I have a page where the User enters a structure tags in and he converts tables to structure "ul" "li".
<!DOCTYPE html>
<html lang="en" xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta charset="utf-8" />
<title>Beta style</title>
<script type='text/javascript' src='http://code.jquery.com/jquery-1.8.3.js'></script>
<script>
function gerador() {
var code = $('textarea[name=message]').val();
/* prevent the creation of multiple output-blocks if someone clicks on the submit-button more than once */
if ($('#output').length < 1) {
$("body").append('<h2>Output</h2><textarea id="output" rows="10" cols="100"></textarea>');
}
/* replace all the things you want */
code = code.replace(/\<table>/g, "<ul>");
code = code.replace(/\<\/table>/g, "</ul>");
code = code.replace(/\<td>/g, "<li>");
code = code.replace(/\<\/td>/g, "</li>");
code = code.replace(/\<tr>/g, "");
code = code.replace(/\<\/tr>/g, "");
code = code.replace(/\TEXT/g, "<label>TEXT</label>");
/* output the new code */
$('#output').val(code);
}
</script>
</head>
<body>
<h2>Input</h2>
<textarea name="message" id="input" rows="10" cols="100"></textarea>
<input type="button" value="Submit" onclick="gerador();" />
</body>
</html>
What I'm trying is to replace all that you have is so
<ul>
<li>
<label>TEXT:<label>
</li>
<li>
<input type="text" value="" />
</li>
</ul>
for
<ul>
<li>
<label>TEXT:<label>
<input type="text" value="" />
</li>
</ul>
ie replace the tag by and ../> by . The problem that exists is that as line breaks indentation, the jquery code does not work.
code = code.replace("</label> \r\n </li>", "</label>");
code = code.replace("<li> \r\n <input>", "<input>");
Thanks!!
Matching HTML with regular expressions is not that wise. It is better to build it off the DOM instead. Using map() you can build the string pretty easy.
var htmlStr = '<table><tr><td><label>XXX</label></td><td><input type="text"/></td></tr><tr><td><label>YYY</label></td><td><input type="text"/></td></tr></table>';
var lis = $(htmlStr).find("tr").map(function () { //loop through the tabel rows
var cellContents = $(this).find("td").map(function () { //find the cells and loop through
return $(this).html(); //get the elements inside of the cells
}).get().join(""); //map results in an array, get it and make it a string
return "<li>" + cellContents + "</li>"; //return the li with the cell contents
}).get().join(""); //take the li array and make it a sting
var yourUL = "<ul>" + lis + "</ul>"; //build your ul with the lis
If you want indenting, you just have to add it when you build the strings.
var lis = $(htmlStr).find("tr").map(function () {
var cellContents = $(this).find("td").map(function () {
return "\t\t" + $(this).html();
}).get().join("\n");
return "\t<li>\n" + cellContents + "\n\t</li>";
}).get().join("\n");
var yourUL = "<ul>\n" + lis + "\n</ul>";
JSFiddle: http://jsfiddle.net/GD8Yu/

jQuery, appending HTML string not working

When using the code below I am unable to add the HTML string to the innerHTML of the target HTMLElement. What am I doing wrong? Is there a better way to do this?
<html>
<head>
<title>Add HTML input with jQuery</title>
<!--
* This code is meant to include the jQuery library v.1.9.1
* from Google API
-->
<script src='http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js' type='text/javascript'></script>
<script>
$('document').ready(function(){
$('#add').click(function(){
var src = $('#src'); // alert(src);
var trgt = $('#src'); // alert(trgt);
var x = null;
var child = null;
var str = null;
if(null != src.val()){
alert(1);
x = trgt.children().length;
str = '<input type="text" name="array[]" id="index' + x + '" value="' + src.val() + '" />';
trgt.html().append(str);
src.val() = null;
}else{
alert('src value is emppty');
}
});
});
</script>
</head>
<body>
<div id="box">
<label></label> <input type="text" name="src" id="src" value="" /> <button id="add">+</button>
<div id="trgt">
</div>
</div>
</body>
</html>
var trgt = $('#src'); ... Your source and target selectors are the same.
This var trgt = $('#trgt') is not the only problem I noticed.
There is trgt.html().append(str); which should be trgt.append(str);.
And then src.val() = null;, are you trying to reset the <input> value? You can simply do it with src.val('');
See this jsfiddle.

Categories

Resources