how to dynamically add input elements one below the other in javascript - javascript

I have following code. The input textboxes are getting generated. Only the thing is i wanted them to be added one below the other. Here is my code:
$('.pl').on('click',function(){
var hiddenInput = document.createElement("input");
var hiddenButton = document.createElement("button");
var hiddenTextNode = document.createTextNode("Delete");
$(this).after(hiddenInput);
hiddenButton.appendChild(hiddenTextNode);
$(this).after(hiddenButton);
$(this).write("<p>hi</p>");
c=c+1;
document.getElementById("h").value = c;
hiddenInput.name = 'text'+c;
hiddenInput.class = 'form-control add-polls-container';
hiddenInput.placeholder = 'Enter Poll Option';
});

you just refer
jQuery find last input and append
$(this).after(hiddenInput); Here $(this) means click bind element so its append textbox to click element

Related

The value of input is not being assigned to a div

I want to get the text from the text area (id= getText), and than assign its value to the new div that I have created but the value is not being saved inside that new div.. I have tried many times but the value of the input is not saved and there is not change in when I click the button
let getText = document.getElementById("getText"); // this is textarea
let select = document.getElementById("selectBtn"); //this is button
//this is another div
let result = document.getElementById("result");
let new_p = document.createElement("div"); //creating element
new_p.innerHTML = "";
result.appendChild(new_p); // adding into resut div
//getting inner text of the input
let value = new_p.innerText;
//adding an event listener
select.addEventListener("click", function(e) {
e.preventDefault();
new_p.innerHTML = value;
//it does not works and the value is not saved
})
let getText = document.getElementById("getText"); // this is textarea
let select = document.getElementById("selectBtn"); //this is button
//this is another div
let result = document.getElementById("result");
let new_p = document.createElement("div"); //creating element
new_p.innerHTML = getText.value;
result.appendChild(new_p); // adding into resut div
//getting inner text of the input
let value = new_p.innerText;
//adding an event listener
select.addEventListener("click", function(e) {
e.preventDefault();
new_p.innerHTML = getText.value;
console.log(value)
//it does not works and the value is not saved
})
Replace new_p.innerHTML = ""; for
new_p.innerHTML = getText.value
and inside of click event,
new_p.innerHTML = getText.value;
Moving forward, try to use online code editors,
to post your code, Since it might be easier for anyone to assist you, Be aware to remove any personal info from the code.
Here is a fiddle with your code https://jsfiddle.net/k8b24n3q/12/
The reason was not working, was because you were setting on click event an undefined value.

Why does deleting this element with a non-unique ID delete the one I want?

Pardon the bad title, it's hard to explain. If you know how to phrase it better, please comment and I will update as soon as I can.
So, I was messing around with a random generator site (perchance.org) and writing my own HTML/Javascript to make my generator work. It has a behavior that is what I want, but that shouldn't be happening according to my knowledge of HTML.
Let me explain with a minimal example.
The example code here is to produce a simple page that has a button.
This button should generate <input>s with <button>s next to them, attached with similar ID's.
The button, when clicked, deletes the <input> and <button>.
Here is a snippet to show you the code/let you reproduce the results:
<html>
<head>
<script>
var current_id = 0;
function add_input () {
var list = document.getElementById("list");
var input = document.createElement("input");
var delete_button = document.createElement("button");
var br = document.createElement("br");
input.id = "input_" + current_id;
delete_button.id = "button_" + current_id;
br.id = "br_" + current_id;
input.value = input.id;
delete_button.textContent = "Delete";
delete_button.onclick = function () {
delete_input(this.id.slice(7)) //To get the numerical ID
}
list.appendChild(input);
list.appendChild(delete_button);
list.appendChild(br);
current_id++;
}
function delete_input (id) {
var input = document.getElementById("input_"+id);
var button = document.getElementById("button_"+id);
var br = document.getElementById("br_"+id);
input.remove();
button.remove();
br.remove();
current_id--;
}
</script>
</head>
<body>
<div id="list">
</div>
<button onclick="add_input()">Add</button>
</body>
</html>
When you add two inputs, then delete the first, and add one more, it leaves you with two inputs using the same ID. It also leaves you with two buttons with the same ID. And yet, both buttons delete their intended target.
Why?
You really should delegate - here I wrap in a div that can be removed in one go
You can rename each input to have incremented IDs but just letting the cnt run, gives you unique IDs
let cnt = 0;
function add_input() {
var list = document.getElementById("list");
var div = document.createElement("div");
var input = document.createElement("input");
var delete_button = document.createElement("button");
var br = document.createElement("br");
input.id = "input_" + (cnt++)// list.querySelectorAll("div").length
input.value = input.id;
delete_button.textContent = "Delete";
delete_button.classList.add("delete")
div.appendChild(input);
div.appendChild(delete_button);
div.appendChild(br);
list.appendChild(div);
}
window.addEventListener("load", function() {
document.getElementById("list").addEventListener("click", function(e) {
const tgt = e.target;
if (tgt.classList.contains("delete")) tgt.closest("div").remove();
})
})
<div id="list">
</div>
<button onclick="add_input()">Add</button>
I changed your code to be more effective.
I'm not using IDs as they aren't adding any benefit instead making it more complex.
Instead I target the element via the event handler and an argument.
I also wrap each set of inputs/buttons in a div so I can just remove that div and it will remove all of the children.
function add_input() {
var list = document.getElementById("list");
var input = document.createElement("input");
var delete_button = document.createElement("button");
var br = document.createElement("br");
delete_button.textContent = "Delete";
delete_button.onclick = function(e) {
e.target.parentNode.remove();
}
var div = document.createElement("div");
div.appendChild(input);
div.appendChild(delete_button);
div.appendChild(br);
list.appendChild(div)
}
<div id="list">
</div>
<button onclick="add_input()">Add</button>

DOM: Delete newly created 'article' element with newly created delete button within onclick event?

I have one section element that contains one article element. Also, I have one input button with 'onclick' event. Whenever this event fired, a new article element appended to the section element with unique id.
The newArticle element contains a label, text box and a delete button. All these three elements get created within the on-click event.
document.getElementById("addRow").onclick = function () {
var newCustomerlbl = document.createElement("label");
newCustomerlbl.innerHTML = "Cutomer Name: ";
var newCustomertxt = document.createElement("input");
newCustomertxt.setAttribute("type", "text");
var delBtn = document.createElement("input");
delBtn.setAttribute("type", "button");
delBtn.setAttribute("value", "Delete");
delBtn.setAttribute("id", "btnDelete");
var newArticle = document.createElement("article");
newArticle.appendChild(newCustomerlbl);
newArticle.appendChild(newCustomertxt);
newArticle.appendChild(delBtn);
var customerSection = document.getElementById("customerRecords");
var customerArticles = customerSection.getElementsByTagName("article");
for (var i = 0; i < customerArticles.length; i++) {
var lastDigit = i + 1;
var newArticleValue = "article" + lastDigit;
newArticle.setAttribute("id", newArticleValue);
}
customerSection.appendChild(newArticle);
}
Now what I want is whenever user click upon the newly created appended delete button, only that particular article get deleted without effecting the rest of articles.
Here is the my jsFiddle code.
If you don't want to use jQuery you can add event listeners to your buttons:
delBtn.addEventListener('click', function () {
this.parentElement.remove();
}, false);
https://jsfiddle.net/3nq1v5e1/
You need to bind an event listener on the newly created delete button. Your example code about using $(this) suggest that you are using JQuery, but then again in the rest of the code you are not using any JQuery?
If you are using JQuery, things get real simple, just add something like
$(document).on('click','.btnDelete', function(){
$(this).closest('article').remove();
});
(and remember to give the deletebutton a CLASS rather than ID, as there will be multiple delete buttons).
If you are NOT using JQuery, you need to add the event listener EVERY TIME a new delete button is created
newArticle.appendChild(delBtn);
delBtn.onclick = function(.....
etc.

Button onclick only checkes the first appended checkbox

With the script below I append 3 elements when the append button is clicked.
a checkbox
input text field
delete button
For now, when the delete button is clicked the checkbox is checked,
but when I append another (let's call it a group) three items, the script doesn't work.
Can anybody explain how I can link the elements in some sort of way.
So that every time I click the append button the elements are linked to the elements that were created at the same time the same on click.
Thank you so much in advance
<html>
<head>
<script language="Javascript">
function append()
{
var cb = document.createElement("input");
cb.type = "checkbox";
cb.id = "id"
cb.checked = false;
var textfield = document.createElement("input");
var delbtn = document.createElement("input");
delbtn.type = "button";
delbtn.value = "remove";
delbtn.onclick= function(){remove()}
document.getElementById('append').appendChild(cb);
document.getElementById('append').appendChild(textfield);
document.getElementById('append').appendChild(delbtn);
}
function remove()
{
id.checked = true;
}
</script>
</head>
<body>
<div id="append"></div>
<input type="button" value="append" onClick="javascript:append()"/>
</body>
</html>
Each time you append a new checkbox, you're running
cb.id = "id"
This is problematic, since elements should have unique ids.
Also, you're referencing the element by its id in the global scope:
id.checked = true;
You should use the standard document.getElementById() instead.

Get innerHTML value from dynamically generated textbox (in javascript)

I'm using JavaScript to dynamically generate a dialogue box (it's a div element), containing a textbox and a submit button. I plan on submitting the value in the textbox to another page using AJAX.
My problem is that I can generate my textbox just fine, but I can't get the value from it. innerHTML comes back blank every time. I'm not sure what I'm doing wrong.
// Generate dialogue box using div
function create_div_dynamic()
{
//Create the div element
dv = document.createElement('div');
//unique tags
var unique_div_id = 'mydiv' + Math.random() * .3245;
var unique_textbox_id = 'mytext' + Math.random() * .3245;
//Set div id
dv.setAttribute('id',unique_div_id);
//Set div style
dv.style.position = 'absolute';
dv.style.left = '100 px';
dv.style.top = '100 px';
dv.style.width = '500px';
dv.style.height = '100px';
dv.style.padding = '7px';
dv.style.backgroundColor = '#fdfdf1';
dv.style.border = '1px solid #CCCCCC';
dv.style.fontFamily = 'Trebuchet MS';
dv.style.fontSize = '13px';
//Create textbox element
txt = document.createElement('input');
txt.setAttribute('id',unique_textbox_id);
txt.setAttribute('type','text');
txt.style.marginRight = '10px';
//Add textbox element to div
dv.appendChild(txt)
//Add the div to the document
document.body.appendChild(dv);
dv.innerHTML += '<input type="button" id="mysubmit" value="Read Textbox" onclick="javascript:alert(\'' + document.getElementById(unique_textbox_id).innerHTML + '\');" />';
}
Textarea elements don't have an innerHTML property. Just read the value property like you would with any other form element.
document.getElementById(unique_textbox_id).value
The input type="text" fields have no innerHTML, they are usually represented as self-closing tags.
Use the value attribute instead:
document.getElementById(unique_textbox_id).value
I have to create the div element, add it to the document, and THEN add the children (textbox and submit button).
No, you don't in general have to do that. What was causing your problem was this:
...'onclick="javascript:alert(\'' + document.getElementById(unique_textbox_id).innerHTML + '\');" />';
That access to document.getElementById().innerHTML is occurring at the time you create the string, that is during the execution of create_div_dynamic(), not when the button is pressed. At that point, the field has just been created and has no .value. (It also has no .innerHTML, but then it never will as it's an input element.)
Your revised code uses a proper JavaScript function which is called at onclick time, and fixes the property to value, so that's OK. This approach also doesn't die when there are apostrophes or backslashes in the value string.
dv.innerHTML += '<input ...
This serialises all the content in ‘dv’ to HTML text, then adds the string, and parses all the HTML back into DOM objects. This is really inefficient, and in the process you lose all JavaScript properties on the object, including event handlers and listeners.
“innerHTML+=” is always a mistake. Never use it.
txt.setAttribute('id',unique_textbox_id);
Don't use setAttribute(), it doesn't work for certain attributes under IE. Instead use the more readable DOM-HTML properties:
txt.type= 'text';
txt.id= unique_textbox_id;
For others in my boat, I want to show the solution. It turns out that I was adding elements in the wrong order.
I have to create the div element, add it to the document, and THEN add the children (textbox and submit button).
//DIV
dv = document.createElement('div');
dv.setAttribute('id',unique_div_id);
dv.style.position = 'absolute';
dv.style.left = xx + 'px';
dv.style.top = yy + 'px';
dv.style.width = '500px';
dv.style.height = '20px';
dv.style.padding = '7px';
dv.style.backgroundColor = '#fdfdf1';
dv.style.border = '1px solid #CCCCCC';
dv.style.fontFamily = 'Trebuchet MS';
dv.style.fontSize = '13px';
//Add div element to body
document.body.appendChild(dv);
//TEXTBOX
txt = document.createElement('input');
txt.setAttribute('id',unique_textbox_id);
txt.setAttribute('type','text');
txt.style.marginRight = '10px';
//Add textbox to div element
document.getElementById('mydiv').appendChild(txt);
var sbt = document.createElement('input');
sbt.setAttribute('id','mysubmit');
sbt.setAttribute('type','submit');
sbt.setAttribute('value','GO');
sbt.onclick = function() { alert(document.getElementById('mytext').value); };
//Add submit to div element
document.getElementById('mydiv').appendChild(sbt);
Once this is done, and I use the .value, all goes well.
$cid =$_REQUEST['cid'];
$name =addslashes($_REQUEST['name']);
$email =$_REQUEST['email'];
$comments =$_REQUEST['comments'];
$comment_type=$_REQUEST['type'];
$gstatus =(isset($_REQUEST['gstatus'])) ? $_REQUEST['gstatus'] : 'no';
$user_type =(!empty($_SESSION['user_id'])) ? 'author' : 'user';

Categories

Resources