Problem adding inputs to panel using javascript - javascript

My problem is that the button stops working for the following panels. I guess it's an id problem, but I have no idea how to fix it (I know very little about javascript)
Html:
<div class="card-body">
<button id="Addpanel">Add panel</button>
</div>
My scripts:
<script>
$(function() {
$('#Addpanel').click(function(){
var newDiv = $('<div class="panel-default"><br /><div class="form-control"><input type="text" id="fieldnum" name="fieldnum" value="">Fill number<a type="button" id="filldetails" class="btn" onclick="addFields()">Add</a></div><div id="container" class="form-control" />'
);
$(".card-body").append(newDiv);
});
});
</script>
Second:
<script type='text/javascript'>
function addFields(){
var number = document.getElementById("fieldnum").value;
var container = document.getElementById("container");
while (container.hasChildNodes()) {
container.removeChild(container.lastChild);
}
for (i=0;i<number;i++){
var input = document.createElement("input");
input.type = "text";
input.name = "input" + (i+1);
input.className = "form-control";
container.appendChild(input);
}
}
</script>

You Should use like this:
$(function () {
var count = 0;
$('#Addpanel').click(function () {
var newDiv = $('<div class="panel-default"><br /><div class="form-control"><input type="text" id="fieldnum' + count + '" name="fieldnum" value="">Fill number<a type="button" id="filldetails' + count + '" class="btn" onclick="addFields()">Add</a></div><div id="container' + count + '" class="form-control" />');
$(".card-body").append(newDiv);
count++;
});
});

Related

Create array from Dynamic table

How can I create an array from this table/form? The onclick function formData() from the dynamic table only returns a concatenated string. I need to create an associative array in JSON using the 'device' variable as key, however I'll settle for any sort of array at all. Clearly, I'm not very good at this...
function createInputTable()
{
var num_rows = document.getElementById('rows').value;
var tableName = document.getElementById('conn_input_device').value;
var column_number = 2;
var tdefine = '<form id="form"><table id="table" border = "1">\n';
var theader = '<tr><th>No</th><th>Input</th><th>Output</th></tr>\n';
var caption = '<caption><input id="device" value ="' + tableName + '" /></caption>';
var tbody = '';
var tfooter = '</table>';
var createNewDevice = '<button onclick="formData();">Form Data</button></form>'
var i = 0;
for (var i= 0; i < num_rows; i++)
{
tbody += '<tr><td>' + (i+1) + '</td><td><input class="cell" id="i'+ i + '" type = "text"/></td>';
tbody += '<td><input class="cell" id="o'+ i + '" type="text"/></td></tr>\n';
}
document.getElementById('wrapper').innerHTML = caption + tdefine + theader + tbody + tfooter + createNewDevice;
}
function formData()
{
var cellData = document.getElementById("form");
//var device = document.getElementById('device').value;
//var j;
var obj = [];
for(j=0; j< cellData.length; j++)
{
obj += cellData[j].value;
}
var json = JSON.stringify(obj);
alert (json);
//document.getElementById('result').innerHTML = json;
}
<form id="tableGen" name="table_gen">
<label>Connecting device: <input type = "text" name = "conn_input_device" id = "conn_input_device"/></label><br />
<label>Number of inputs: <input type="text" name="rows" id="rows"/></label><br />
<input name="generate" type="button" value="Create Input Table!" onclick='createInputTable();'/>
</form>
<div id="wrapper"></div>
1) This my answer how do this on VueJS and jQuery
2) Vanilla js - CODEPEN - DEMO
// Get DOM elements
const $el = [
'#tmpl',
'#user-count',
'#people-count',
'#form-items',
'#btn-add',
'#form',
].reduce((res, item) => {
const method = item.startsWith('#')
? 'querySelector'
: 'querySelectorAll'
const key = item
.replace(/\W/ig, ' ').trim()
.replace(/\s+\w/g, v => v.trim().toUpperCase())
res[key] = document[method](item)
return res
}, {})
// Variable for dynamic template
const tmpl = $el.tmpl.innerHTML.trim()
// Click on Add new button
$el.btnAdd.addEventListener('click', () => {
const peopleCount = +$el.peopleCount.value
const html = Array(peopleCount)
.fill(tmpl)
.join('')
$el.formItems.insertAdjacentHTML('beforeend', html)
})
// Submit form
$el.form.addEventListener('submit', e => {
e.preventDefault()
alert('Submit form by ajax or remove this method for default behavior')
})
// Add form click (it's need for dynamic handler on child elements)
$el.form.addEventListener('click', e => {
// Delete behaviors
if (e.target.classList.contains('btn-del') && confirm('Are you sure?')) {
e.target.closest('.row').remove()
}
})
<div id="app">
<div>
<div>
<button id="btn-add">Add new user</button>
<label>Number of People:</label>
<input type="number" id="people-count" value="1" min="1">
</div>
<form id="form">
<div id="form-items" data-empty="Users list is empty"></div>
<button>Send</button>
</form>
</div>
</div>
<script type="text/x-template" id="tmpl">
<div class="row">
<label>
Name:
<input class="people" name="name[]">
</label>
<label>
Surname:
<input class="people" name="surname[]">
</label>
<label>
Email:
<input type="email" class="people" name="email[]">
</label>
<button class="btn-del">Delete</button>
</div>
</script>
<style>
.people {
width: 80px;
}
#form-items:empty + button {
display: none;
}
#form-items:empty:before {
content: attr(data-empty);
display: block;
}
</style>
I have edited your code,
function createInputTable()
{
var num_rows = document.getElementById('rows').value;
var tableName = document.getElementById('conn_input_device').value;
var column_number = 2;
var tdefine = '<form id="form"><table id="table" border = "1">\n';
var theader = '<tr><th>No</th><th>Input</th><th>Output</th></tr>\n';
var caption = '<caption><input id="device" value ="' + tableName + '" /></caption>';
var tbody = '';
var tfooter = '</table>';
var createNewDevice = '<button onclick="formData();">Form Data</button></form>'
var i = 0;
for (var i= 0; i < num_rows; i++)
{
tbody += '<tr><td>' + (i+1) + '</td><td><input class="cell" id="i'+ i + '" type = "text"/></td>';
tbody += '<td><input class="cell" id="o'+ i + '" type="text"/></td></tr>\n';
}
document.getElementById('wrapper').innerHTML = caption + tdefine + theader + tbody + tfooter + createNewDevice;
}
function formData()
{
var cellData = document.getElementsByTagName("tr");
var obj = [];
for(var i=0;i<cellData.length-1;i++){
obj.push(document.getElementById("i"+i).value);
obj.push(document.getElementById("o"+i).value);
}
alert(JSON.stringify(obj));
}
<form id="tableGen" name="table_gen">
<label>Connecting device: <input type = "text" name = "conn_input_device" id = "conn_input_device"/></label><br />
<label>Number of inputs: <input type="text" name="rows" id="rows"/></label><br />
<input name="generate" type="button" value="Create Input Table!" onclick='createInputTable();'/>
</form>
<div id="wrapper"></div>

Multiple files Uploader jQuery

I am trying to add multiple file uploading functionality to a my website. Basically I have a button "add files" which triggers and appends a input fields of file type which can be used to upload a document.
Both on change and click events are not triggered. Thanks
files = $('.button-container');
fileSerialNumber = 1;
var addFileInputBtn = $('<button class="add-file">+ Add file</button><br><br>')
files.append(addFileInputBtn)
addFileInputBtn.click(function (event) {
event.preventDefault();
addFileInputBtn.text("+ Add another file")
var fileBoxContainer = $('<div class="fileBoxContainer"/><br>')
var fileNameLabel = $('<label style="margin-left: 20px;" for="namefile' + fileSerialNumber + '"> Name: </label>');
var fileName = $('<input class="file-name" name="namefile' + fileSerialNumber + '" type="text"></input>');
var rmButton = $("<button class='remove-button' style='color:grey;'><i class='fa fa-times-circle' aria-hidden='true'></i></button>");
var fileInput = $('<input class="file-input" name="file' + fileSerialNumber + '" type="file"></input>')
fileBoxContainer.append(fileInput);
fileBoxContainer.append(fileNameLabel);
fileBoxContainer.append(fileName);
fileBoxContainer.append(rmButton);
files.append(fileBoxContainer);
debugger
fileInput.on('change', function () {
debugger
var fName = this.value
fName = fName.replace(/.*[\/\\]/, '');
fileName.val(fName);
});
rmButton.click(function (event) {
event.preventDefault();
fileBoxContainer.remove();
});
fileSerialNumber += 1;
})
$('.remove-button').click(function (event) {
event.preventDefault();
$('.fileBoxContainer').remove();
});
<html>
<head>
<script src="https://use.fontawesome.com/f65531ab46.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
</head>
<body>
<form class="button-container">
</form>
</body>
</html>

JS - How to add three inputs, get the text from them and show the text in another subpage

I have a problem with adding three input text fields after I put one button.
I'd like to have three new input fields after i push the button "Add author" - these inputs would be: 1. name 2. surname 3. initial. Everyone new input needs to have a different id in order to take the text from the inputs and show it in the new subpage which has to show up right after I push the button "Make the order".
<!DOCTYPE HTML>
<html lang='en'>
<head>
<meta charset='utf-8'>
<link rel='stylesheet' href='css/style.css'>
<script type="text/javascript">
window.onload = Load;
function Load()
{
document.getElementById('add_input').onclick = AddElement;
}
function AddElement()
{
var element = document.createElement('input');
var element2 = document.createElement('input');
var element3 = document.createElement('input');
element.setAttribute('type', 'text');
element.setAttribute('type', 'text');
element.setAttribute('type', 'text');
var number = 0;
var amount = document.forms['add_file'].elements.length;
for (var i = 0; i < ilosc; i++ )
{
if (document.forms['add_file'].elements[i].type == 'text')
{
number += 1;
}
}
element.setAttribute('name', 'file-'+(liczba+1));
element.setAttribute('nazwisko', 'file-'+(liczba+1));
element.style.display = "block";
element.style.margin= "2px";
document.forms['add_file'].appendChild(element);
}
</script>
<!--making order -->
<script>
function getText(){
var publisher = document.getElementById("publisher");
var year = document.getElementById("year");
var div = document.getElementById("readyorder")
div.innerHTML = "("+surname.value+" "+year.value+","+" "+"s."+" "+page.value+")";
}
</script>
</head>
<body>
<div class='container'>
<!-- header -->
<header>
<img src="images/header.jpg" alt=""/>
</header>
<input type="text" name="file-1" />
<input type="text" name="surname-1" />
<input type="submit" value="Add author" id="add_input" />
<form name="add_file" enctype="multipart/form-data" method="post">
</form>
Author's Surname<br>
<input type="text" id="surname"><br>
Page number<br>
<input type="text" id="page"><br>
Year<br>
<input type="text" id="year"><br/>
<input type="submit" value="Make the order" onclick="getText()" /> <br/><br/>
<div id="readyorder"></div><br/>
</body>
</html>
Store your id globaly and increase on each addition.
While Creating your node set their id value using setAttribute
element1.setAttribute('id', 'surname' + number);
Also Create a button while adding textbox's which let you know current order.
var button = document.createElement('input');
Add onclick attribute to call javascript function
button.setAttribute('onclick', 'getText(' + number + ')');
window.onload = Load;
var number = 0;
function Load()
{
document.getElementById('add_input').onclick = AddElement;
}
function AddElement()
{
var element1 = document.createElement('input');
var element2 = document.createElement('input');
var element3 = document.createElement('input');
var label1 = document.createElement('label');
var label2 = document.createElement('label');
var label3 = document.createElement('label');
var button = document.createElement('input');
label1.innerHTML = "</br>Author's Surname " + number + "</br>";
element1.setAttribute('type', 'text');
element1.setAttribute('id', 'surname' + number);
element1.setAttribute('placeholder', 'Surname...');
label1.appendChild(element1);
label2.innerHTML = '</br>Page number ' + number + '</br>';
element2.setAttribute('type', 'text');
element2.setAttribute('id', 'page' + number);
element2.setAttribute('placeholder', 'Page...');
label2.appendChild(element2);
label3.innerHTML = '</br>Year ' + number + '</br>';
element3.setAttribute('type', 'text');
element3.setAttribute('id', 'year' + number);
element3.setAttribute('placeholder', 'Year...');
label3.appendChild(element3);
button.setAttribute('onclick', 'getText(' + number + ')');
button.setAttribute('type', 'button');
button.setAttribute('value', 'Button ' + number);
document.forms['add_file'].appendChild(label1);
document.forms['add_file'].appendChild(label2);
document.forms['add_file'].appendChild(label3);
document.forms['add_file'].appendChild(button);
number++;
}
function getText(id)
{
var surname = document.getElementById("surname" + id);
var page = document.getElementById("page" + id);
var year = document.getElementById("year" + id);
var div = document.getElementById("readyorder")
div.innerHTML = "("+surname.value+" "+year.value+","+" "+"s."+" "+page.value+")";
}
<input type="text" name="file-1" />
<input type="text" name="surname-1" />
<input type="submit" value="Add author" id="add_input" />
<form name="add_file" enctype="multipart/form-data" method="post">
</form>
<hr>
<div id="readyorder"></div><br/>

Problems with Jquery .on()

I'm attempting to use .on() to add a text field when a dynamically created button is clicked. However, for whatever reason, I can't seem to get it working. Anyone see what's wrong? Thanks for any help and sorry if it's something obvious (I'm afraid that it might be but I just can't see it).
$('#the-basics input.typeahead').keyup(function() {
var prs = $(this).val().split(' ');
if (!$("#the-basics span.newEntityButtons").length) {
var $newEntity = $('<span class="newEntityButtons">' + '</span>');
$newEntity.appendTo($("#the-basics"));
var $newPerson = $('<input type="button" value="New Person" id="addpersonbutton" class="newHolder newPerson" />');
$newPerson.appendTo($("span.newEntityButtons"));
}
});
$('div#example').on('click', '#addpersonbutton', function() {
var epo = new Date().getTime();
var theelement = '<span class="nested-fields person">' +
'<input id="stockholder_people_attributes_' + epo + '_fname" name="stockholder[people_attributes][' + epo + '][fname]" value="' + prs[0] + '">' +
'<a class="glyphicon glyphicon-trash remove_fields existing" href="#"></a>' +
'</span>';
$('div.new_person.new_fields').prepend(theelement);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="example">
<div id="the-basics">
<input class="typeahead">
</div>
<div class="new_person new_fields">
</div>
</div>
Changes I made
► Declared variable prs as a global variable
► Remove # from the New Person button's id.
Working Demo
var prs = '';
$('#the-basics input.typeahead').keyup(function() {
prs = $(this).val().split(' ');
if (!$("#the-basics span.newEntityButtons").length) {
var $newEntity = $('<span class="newEntityButtons">' + '</span>');
$newEntity.appendTo($("#the-basics"));
var $newPerson = $('<input type="button" value="New Person" id="addpersonbutton" class="newHolder newPerson" />');
$newPerson.appendTo($("span.newEntityButtons"));
}
});
$('div#example').on('click', '#addpersonbutton', function() {
var epo = new Date().getTime();
var theelement = '<span class="nested-fields person">' +
'<input id="stockholder_people_attributes_' + epo + '_fname" name="stockholder[people_attributes][' + epo + '][fname]" value="' + prs[0] + '">' +
'<a class="glyphicon glyphicon-trash remove_fields existing" href="#"></a>' +
'</span>';
$('div.new_person.new_fields').prepend(theelement);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="example">
<div id="the-basics">
<input class="typeahead">
</div>
<div class="new_person new_fields">
</div>
</div>
Remove # from the New Person button's id.
var $newPerson = $('<input type="button" value="New Person" id="addpersonbutton" class="newHolder newPerson" />');
Declare prs outside the click event like following.
var prs;
$('#the-basics input.typeahead').keyup(function () {
prs = $(this).val().split(' ');
if (!$("#the-basics span.newEntityButtons").length) {
var $newEntity = $('<span class="newEntityButtons">' + '</span>');
$newEntity.appendTo($("#the-basics"));
var $newPerson = $('<input type="button" value="New Person" id="addpersonbutton" class="newHolder newPerson" />');
$newPerson.appendTo($("span.newEntityButtons"));
}
});
var prs = $(this).val().split(' ');
is not a global variable, and inaccessible inside $('div#example').on('click', '#addpersonbutton', function() { so duplicate it inside your second function
EDIT: to make it clear:
$('#the-basics input.typeahead').keyup(function() {
var prs = $(this).val().split(' ');
if (!$("#the-basics span.newEntityButtons").length) {
var $newEntity = $('<span class="newEntityButtons">' + '</span>');
$newEntity.appendTo($("#the-basics"));
var $newPerson = $('<input type="button" value="New Person" id="addpersonbutton" class="newHolder newPerson" />');
$newPerson.appendTo($("span.newEntityButtons"));
}
});
$('div#example').on('click', '#addpersonbutton', function() {
var prs = $(this).val().split(' ');
var epo = new Date().getTime();
var theelement = '<span class="nested-fields person">' +
'<input id="stockholder_people_attributes_' + epo + '_fname" name="stockholder[people_attributes][' + epo + '][fname]" value="' + prs[0] + '">' +
'<a class="glyphicon glyphicon-trash remove_fields existing" href="#"></a>' +
'</span>';
$('div.new_person.new_fields').prepend(theelement);
});

Get content of a DIV using JavaScript

I have two DIV's called DIV1 and DIV2 and DIV1 consists of dynamic content and DIV2 is empty. I need content of DIV1 to be displayed in DIV2. How can I do it.
I coded in below manner which is not working. Anybody please correct it.
<script type="text/javascript">
var MyDiv1 = Document.getElementById('DIV1');
var MyDiv2 = Document.getElementById('Div2');
MyDiv2.innerHTML = MyDiv2;
</script>
<body>
<div id="DIV1">
// Some content goes here.
</div>
<div id="DIV2">
</div>
</body>
(1) Your <script> tag should be placed before the closing </body> tag. Your JavaScript is trying to manipulate HTML elements that haven't been loaded into the DOM yet.
(2) Your assignment of HTML content looks jumbled.
(3) Be consistent with the case in your element ID, i.e. 'DIV2' vs 'Div2'
(4) User lower case for 'document' object (credit: ThatOtherPerson)
<body>
<div id="DIV1">
// Some content goes here.
</div>
<div id="DIV2">
</div>
<script type="text/javascript">
var MyDiv1 = document.getElementById('DIV1');
var MyDiv2 = document.getElementById('DIV2');
MyDiv2.innerHTML = MyDiv1.innerHTML;
</script>
</body>
You need to set Div2 to Div1's innerHTML. Also, JavaScript is case sensitive - in your HTML, the id Div2 is DIV2. Also, you should use document, not Document:
var MyDiv1 = document.getElementById('DIV1');
var MyDiv2 = document.getElementById('DIV2');
MyDiv2.innerHTML = MyDiv1.innerHTML;
Here is a JSFiddle: http://jsfiddle.net/gFN6r/.
Right now you're setting the innerHTML to an entire div element; you want to set it to just the innerHTML. Also, I think you want MyDiv2.innerHTML = MyDiv 1 .innerHTML. Also, I think the argument to document.getElementById is case sensitive. You were passing Div2 when you wanted DIV2
var MyDiv1 = Document.getElementById('DIV1');
var MyDiv2 = Document.getElementById('DIV2');
MyDiv2.innerHTML = MyDiv1.innerHTML;
Also, this code will run before your DOM is ready. You can either put this script at the bottom of your body like paislee said, or put it in your body's onload function
<body onload="loadFunction()">
and then
function loadFunction(){
var MyDiv1 = Document.getElementById('DIV1');
var MyDiv2 = Document.getElementById('DIV2');
MyDiv2.innerHTML = MyDiv1.innerHTML;
}
simply you can use jquery plugin to get/set the content of the div.
var divContent = $('#'DIV1).html(); $('#'DIV2).html(divContent );
for this you need to include jquery library.
function add_more() {
var text_count = document.getElementById('text_count').value;
var div_cmp = document.getElementById('div_cmp');
var values = div_cmp.innnerHTML;
var count = parseInt(text_count);
divContent = '';
for (i = 1; i <= count; i++) {
var cmp_text = document.getElementById('cmp_name_' + i).value;
var cmp_textarea = document.getElementById('cmp_remark_' + i).value;
divContent += '<div id="div_cmp_' + i + '">' +
'<input type="text" align="top" name="cmp_name[]" id="cmp_name_' + i + '" value="' + cmp_text + '" >' +
'<textarea rows="1" cols="20" name="cmp_remark[]" id="cmp_remark_' + i + '">' + cmp_textarea + '</textarea>' +
'</div>';
}
var newCount = count + 1;
if (document.getElementById('div_cmp_' + newCount) == null) {
var newText = '<div id="div_cmp_' + newCount + '">' +
'<input type="text" align="top" name="cmp_name[]" id="cmp_name_' + newCount + '" value="" >' +
'<textarea rows="1" cols="20" name="cmp_remark[]" id="cmp_remark_' + newCount + '" ></textarea>' +
'</div>';
//content = div_cmp.innerHTML;
div_cmp.innerHTML = divContent + newText;
} else {
document.getElementById('div_cmp_' + newCount).innerHTML = '<input type="text" align="top" name="cmp_name[]" id="cmp_name_' + newCount + '" value="" >' +
'<textarea rows="1" cols="20" name="cmp_remark[]" id="cmp_remark_' + newCount + '" ></textarea>';
}
document.getElementById('text_count').value = newCount;
}

Categories