How to make click event work with dynamically generated html elements - javascript

When the add more link is clicked, a div is dynamically generated that adds an additional text input and a add more link. This dynamically inserted add more link doesn't respond to click event. Even though each dynamically inserted link has a unique id and the click event uses "delegated" binding through Jquery on() method, yet the dynamically inserted link does not work by adding more fields when clicked. Here is a jsbin and the whole code is below:
The Javascript:
<script type="text/javascript">
$(document).on("ready", function(){
return $(".add_people_filter").on("click", function(event){
event.preventDefault();
var time = new Date().getTime();
var dynamicallyCreatedDiv = document.createElement("div");
dynamicallyCreatedDiv.id = time;
var peopleFilterContainerDiv = $("#people_filter_container");
peopleFilterContainerDiv.append(dynamicallyCreatedDiv);
var getHtmlForDynamicDiv = $(".people_filter").html();
var theNewDiv = $(dynamicallyCreatedDiv);
theNewDiv.append(getHtmlForDynamicDiv);
var AddUniqueIdToLinK = time * 2;
var x = time * 3;
$(this).attr('id', AddUniqueIdToLinK);
theNewDiv.find("a:last").attr('id', x);
return theNewDiv;
});
});
</script>
The html:
<div id="people_filter_container">
<div class="people_filter" >
<input type="text" name="firstname" placeholder="add name" >
add more
<br> <br>
</div>
</div>

Change it for that :
return $("body").on("click",".add_people_filter", function(event)
{
...... YOUR CODE
});

Related

How to delete text box along with button in JavaScript

I have a button when user clicks the button it create the text box along with remove button
but all the text boxes created with same id how we can delete the text box when clicks respective remove button
here My Code:
<body>
<button type="button" id="URLbtn" onclick="Createinput()"> + Add URL</button>
<div id="TextAreaBtn"></div>
<script>
function Createinput() {
var newdiv=document.createElement("div");
newdiv.id="test"
var Inputele=document.createElement("input");
Inputele.type="text";
Inputele.id="URLtxt"
newdiv.appendChild(btnele);
var btnele=document.createElement("button");
btnele.id="rmvbtn"
btnele.type="button"
btnele.innerHTML="-"
btnele.onclick=RemoveUrlBox()
newdiv.appendChild(btnele);
var element = document.getElementById("TextAreaBtn");
element.appendChild(newdiv);
}
function RemoveUrlBox() {}
</script>
</body>
i am getting following output
if user click 2 remove button only remove the second textbox and button
You need to select the wrapping div. Easiest way is to use remove() and use closest. No need to use the id..... You also need to remember ids need to be unique.
function createInput() {
var newDiv = document.createElement("div");
newDiv.className = 'group';
var inputElem = document.createElement("input");
inputElem.type = "text";
newDiv.appendChild(inputElem);
var btnElem = document.createElement("button");
btnElem.type = "button";
btnElem.textContent = "-";
btnElem.addEventListener("click", removeUrlBox);
newDiv.appendChild(btnElem);
var element = document.getElementById("TextAreaBtn");
element.appendChild(newDiv);
}
function removeUrlBox() {
this.closest('.group').remove();
}
<button type="button" id="URLbtn" onclick="createInput()"> + Add URL</button>
<div id="TextAreaBtn"></div>
This should do the trick:
const txtarea=document.getElementById('TextAreaBtn');
document.getElementById('URLbtn').onclick=()=>txtarea.innerHTML+=
'<div><input type="text" class="URLtxt"><button class="rmvbtn">-</button></div>';
txtarea.onclick=ev=>ev.target.className==="rmvbtn"&&ev.target.parentNode.remove()
<button type="button" id="URLbtn"> + Add URL</button>
<div id="TextAreaBtn"></div>
I replaced your id attributes with class attributes, as these don't need to be unique.
I reduced your script by using innerHTML instead of laboriously putting elements together with createElement(). This is a matter of opinion as both methods have their advantages.
I also used delegated event listener attachment for the removal buttons. This way you can get away with a single event listener on div.TextAreaBtn. The attached funcion will only trigger any action if the clicked element has class "rmvbtn".
Change
btnele.onclick=RemoveUrlBox()
to
btnele.addEventListener('click', function (e) {
// `this` is the button that was clicked no matter about the id
// `this.parentNode` is the div you want to remove
const nodeToRemove = this.parentNode;
nodeToRemove.parentNode.removeChild(nodeToRemove);
});

can javascript version of print be inserted inside the code of a Div?

I have a form that adds and subtracts a smaller form when user clicks on add or subtract users button.
what I want to do is add a +1 every time the user hits the add button to a ID tag inside the div tag.. confusing yes I know
say this is the original tag:
<div id="formwrap" class="test" name="test">im a form in this formwrap</div>
now say the user clicks on a add button and a new form will pop up below the current form and using a print or echo version of javascript this would be the new code created for the div using .append(html) or something along those lines too this:
<div id="formwrap" class="test" name="test">im a form in this formwrap</div>
<div id="formwrap" class="test2" name="test2">im a form in this formwrap</div>
and so on as u can see next the 2 would change to a 3 if someone where to click the add button
<div id="formwrap" class="test(+1 code would go here)" name="test(+1 code would go here)">im a form in this formwrap</div>
So before I code is this even possible? I want to be able to style the smaller form differently and I want the phpmailer to be able get retrieve all the data depending on how many clicks they do. and adding a +1 too each of the tags would do both goals.
It is possible using data attributes.
See: https://developer.mozilla.org/en-US/docs/Learn/HTML/Howto/Use_data_attributes
You would do something like this
var count = 0
var formwrap = document.getElementById('formwrap');
formwrap.dataset.name = "aName" + count
// increment count on click
You can use jquery for this when user click on add button you have to increment the value of count like this ...
var count = 0;
$("button").on("click", function () {
var html = '<div id="formwrap'+count+'" class="test'+count+'"
name="test'+count+'">im a form in this formwrap</div>';
count++;
$(div).append(html);
});
this way you can do this.
//Create a private counter var
const counter = (function() {
var formCount = 0;
return {
value: () => formCount,
increment: () => ++formCount
}
})();
//A function that will generate a "form" element
const ID_PREFIX = 'formwrap_';
const generateFormEl = () => {
let el = document.createElement('div');
el.setAttribute('id', `${ID_PREFIX}${counter.increment()}`);
el.setAttribute('class', 'test');
el.setAttribute('name', 'test');
el.appendChild(document.createTextNode(`ID: ${el.getAttribute('id')}`));
return el;
};
//Store your DOM elements in some vars
const forms = document.querySelector('#forms');
const btn = document.querySelector('[type="button"]');
//Add a form element to the DOM on click
btn.addEventListener('click', () => {
const form = generateFormEl();
forms.appendChild(form);
});
<div id="container">
<input type="button" value="Add a form" />
<div id="forms"></div>
</div>

Saving only the first word of a paragraph in a javascript variable

I am trying to store a paragraph in a javascript variable. I have multiple buttons inside a table, each one of the buttons has a different value, the value of each button is a small text paragraph. When i click a button a save the current buttons value in a javascript variable called 'input'.
When a button is clicked i also load an html form called "contactForm" and i display the buttons value inside that form.
The functionality works fine, the problem though is that when i save the value of the button in the ('input') js variable it saves only the first word of the paragraph, is there a way to fix this?
<html>
<div id="contactForm" >
<p><h4><i>First Choose the clients and then the file which will be uploaded in order to proced</i></h4></2>
<hr>
<input type="text" id="someInput" name="someInput"></input>
<hr>
</div>
<script>
var input; //prepare var to save contact name/ PLACE outside document ready
$(function() {
// contact form animations
$('button[id="contactbutton"]').click(function() {
input = $(this).val(); //set var input to value of the pressed button
document.getElementById("someInput").value = input;
$('#contactForm').fadeToggle();
})
$(document).mouseup(function (e) {
var container = $("#contactForm");
if (!container.is(e.target) // if the target of the click isn't the container...
&& container.has(e.target).length === 0) // ... nor a descendant of the container
{
container.fadeOut();
}
});
});
</script>
<html>
It's simple and it works... I just didn't include the additional jQuery that you've written, as for getting the first word from a paragraph, it does do that though.
<div id="contactForm" >
<p>First Choose the clients and then the file which will be uploaded in order to proced</p>
<hr>
<input type="text" id="someInput" name="someInput">
<hr>
</div>
<br>...
<br>
<h4>Demo</h4>
<button id ="contactbutton">Click Me</button>
<script>
/**
* #description the purpose of this function is to demonstrate how to
* get the first word of a paragraph, sentence, etc.
*/
!function() {
var btn = document.querySelector('button[id="contactbutton"]');
btn.addEventListener("click", function(){
// get the paragraph tag text
var para = document.querySelector("#contactForm p").textContent;
console.log(para);
// break the paragraph into an arraywor each word seperated by a space
// index 0 = first element in the array
var word = para.split(" ")[0];
console.log(word);
// another example
var inp = document.querySelector("input#someInput");
var inpVal = inp.value;
console.log(inpVal);
var word2 = inpVal.split(" ")[0];
console.log(word2);
});
}();
</script>

HTML list, Adding JQuery to cross selected item.

I have a little app that adds items to a list. The items appear with a button next to them, I want to be able to press that button to add a (text-decoration: line-through). I have tried a few different things but nothing seems to work (the Javascript to add items, delete the last item, add classes to the new li elements, etc. All that works fine, my problem is only with the JQuery part, more comments on the code itself).
HTML
<html>
<body>
<h1> Shopping List </h1>
<button id="add"> Add </button>
<input type="text" id="input" placeholder="Enter Items"> </input>
<button id="remove"> Remove Last </button>
<ul id="list">
</ul>
</body>
</html>
Js/Jq:
document.getElementById("add").addEventListener('click', function() {
var check = document.createElement("button");
var input = document.getElementById("input").value;
var newEl = document.createElement("li");
var newText = document.createTextNode(input);
var buttonText = document.createTextNode("Check");
newEl.className = "liEl";
newEl.appendChild(newText);
newEl.appendChild(check);
check.setAttribute("class", "checked");
check.appendChild(buttonText);
/* Problem starts here */
$("button.checked").on('click', function() {
$('li.liEl').css('text-decoration: line-through');
/* It should get the button with the class "checked" and on click, make the li elements with class "liEl" to have that css... */
}
);
var position = document.getElementsByTagName("ul")[0];
position.appendChild(newEl);
document.getElementById("input").value = "";
document.getElementById('input').onkeypress = function(e) {
if (e.keyCode == 13) {
document.getElementById('add').click(); /* adds an event listener to the submit text, keyCode 13 equals the enter key so when it's pressed it presses the add button. */
}
}
});
/* Delete last item function: */
document.getElementById("remove").addEventListener('click', function() {
var els = document.getElementsByTagName("li");
var removeEl = els[els.length - 1]; // <-- fetching last el, If els is an array, it has indices from 0 to els.length - 1. 0 is the first, els.length - 1 is the last index.
var containerEl = removeEl.parentNode;
containerEl.removeChild(removeEl);
});
Use style like $('li.liEl').css('text-decoration','line-through');
Your jQuery css function is wrong, you need to provide two parameter to set css value (see this: css-property-name-value).
Your selector syntax ($('li.liEl')) is not right, it would return all <li> element, not the one the clicked button is located.
You can use this: $(this).parent().css('text-decoration', 'line-through');.
Your code contain some bug, the last added button would not trigger the function. It is because your click function is added before the new element added to DOM. And it would cause your click function to be triggered multiple time for earlier added button.
Here's the snippet for fixed code. Since you already using jQuery, I change several native java script native element query and event handler whith jquery syntax.
$(function () {
$("#add").click(function(evt) {
var input = $('#input').val();
var check = $('<button class="checked">Check</button>');
var newEl = $('<li class="liEl"></li>');
newEl.append(input);
newEl.append(check);
$(check).click(function(evt) {
$(this).parent().css('text-decoration', 'line-through');
});
$('#list').append(newEl);
$('#input').val('');
});
$('#remove').click(function(evt) {
var lastEl = $('li.liEl').last();
lastEl.remove();
});
$('#input').keypress(function(evt) {
if (evt.keyCode === 13) {
$("#add").click();
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<body>
<h1> Shopping List </h1>
<button id="add"> Add </button>
<input type="text" id="input" placeholder="Enter Items" />
<button id="remove"> Remove Last </button>
<ul id="list"></ul>
</body>

Changing a dynamically created label's text with keyup() issue

I am creating a form dynamically and therefore edit the form elements’ properties. When attempting to change the label, assigning an auto-generated id works fine but when changing this label using the generated id, the function or keyup() from jQuery keeps calling all the previously created label id(s). this means when i want to edit one label, it ends up editing every label.
HTML
<input type="text" id="change-label"><br><br>
<button id="add-button">add label</button>
<div id="add-label"></div>
JavaScript/jQuery
$('#add-button').click(function(){
var div = document.createElement('div');
var textLabel = document.createElement('label');
var labelNode = document.createTextNode('untitled');
textLabel.appendChild(labelNode);
textLabel.id = autoIdClosure();
$('#change-label').val('untitled');
div.appendChild(textLabel);
$('#add-label').append(div);
});
var autoIdClosure = (function(){
var counter = 0;
var labelId = "textInputLabel";
return function(){
counter += 1;
var id = labelId + counter;
editLabelWrapper(id)
return id;
}
})();
function editLabelWrapper(id){
function editLabel(){
var value = $(this).val();
$("#"+id).text(value);
}
$("#change-label").keyup(editLabel).keyup();
}
I’ve already found an alternative using onkeyup="$('#'+globaID).text($(this).val());", but I need to understand what I was doing wrong so I can learn from it.
JSFiddle
I think you are overthinking the matter...
Instead of using an unique id, rather use classes, makes it easier to handle.
So change <div id="add-label"></div> to <div class="add-label"></div>
Then what you want to do is, when a value is given in #change-label you want it in the last div.add-label.
So the function will become this:
$("#change-label").on('keyup', function() {
$('.add-label:last').text( $(this).val() );
});
Next what you want to do is bind a function to #add-button. Once it gets clicked, we want to add a new div.add-label after the last one. And empty the #change-label. You can do that by using this function:
$('#add-button').on('click', function() {
$('.add-label:last').after('<div class="add-label"></div>');
$('#change-label').val('');
});
Updated Fiddle

Categories

Resources