PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0
Showing posts with label dom-manipulation. Show all posts
Showing posts with label dom-manipulation. Show all posts

Tuesday, November 8, 2022

[FIXED] How to pass data onclick event in dynamically created row in table by for loop in JQuery?

 November 08, 2022     dom, dom-manipulation, html, javascript, jquery     No comments   

Issue

I have an array of objects like

const array = [{id:1,name:'a'},{id:2,name:'b'},{id:3,name:'c'}]

The HTML snippet is

<table id="NameTable">
  <thead>
    <tr>
          <th>Name</th>
     </tr>
   </thead>
   <tbody>
   </tbody>
</table>

Now I am populating the table from the array data (above given) dynamically.

array.foreach(person=> {
$("NameTable tbody").append(`<tr><td>   ${person.name} </td></tr>` )

It works properly and data is loaded in table. Now I want to call a function on row click by passing argument of person for example. i want this function to be called on row click

function call(personObj){
   console.log(personObj)
}

Now this function should be called on each row click and only relevant data should be passed to call function. How can I get this through JQuery


Solution

To achieve your goal you can use jQuery's data() method to store each object as a reference to the td you create. You can then retrieve it from the td when it's clicked. Something like this:

const array = [{ id: 1, name: 'a'}, { id: 2, name: 'b' }, { id: 3, name: 'c' }]
const $table = $('#NameTable');

array.forEach(person => {
  const $tr = $('<tr />');
  const $nameTd = $('<td />').text(person.name).data('person', person).appendTo($tr);
  $table.find('tbody').append($tr);
});

$table.on('click', 'td', e => { 
  const $td = $(e.currentTarget);
  const personObj = $td.data('person');
  console.log(personObj);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.1/jquery.min.js"></script>
<table id="NameTable">
  <thead>
    <tr>
      <th>Name</th>
    </tr>
  </thead>
  <tbody></tbody>
</table>



Answered By - Rory McCrossan
Answer Checked By - Terry (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Saturday, October 15, 2022

[FIXED] How to append "delete button" to EVERY list item that is newly created in JS?

 October 15, 2022     dom, dom-events, dom-manipulation, event-handling, javascript     No comments   

Issue

Shopping List exercise using JS DOM. My full code: https://codepen.io/lil_a/pen/BaQKvqZ?editors=0110

I have to add a new "Delete" button to every newly created list item. I managed to do that, but it only appends the button I created to the last list item, not other newly added items too. How to do it so there's a new delete button for every list item?

I've searched through similar questions, but generally, the codes were different from mine and I'd have to redo it all. Is there a way to do it with my code?

HTML

    <h1>Shopping List</h1>
    <p id="first">Get it done today</p>
    <input id="userinput" type="text" placeholder="enter items">
    <button id="enter">Enter</button>
    <ul id = "list">
        <li>Notebook<button class="btn">Delete</button></li><br>
        <li>Jello<button class="btn">Delete</button></li><br>
        <li>Spinach<button class="btn">Delete</button></li><br>
        <li>Rice<button class="btn">Delete</button></li><br>
        <li>Birthday Cake<button class="btn">Delete</button></li><br>
        <li>Candles<button class="btn">Delete</button></li><br>
    </ul>

JS

function createListElement() {
    var li = document.createElement("li");
    li.appendChild(document.createTextNode(input.value));
    ul.appendChild(li).addEventListener("click", toggleList); 
    //append and toggle on and off new list items
    input.value = "";
    ul>li.appendChild(deleteButton).addEventListener("click", removeItem); 
    //append "delete button" to newly added "li"
}

var elements = document.getElementsByClassName("btn");
    for (var i = 0; i < elements.length; i++){
    elements[i].addEventListener("click", removeItem);
}
  
function removeItem(){
this.parentNode.remove();
}  

var deleteButton = document.createElement("button");
deleteButton.setAttribute("class", "btn");
deleteButton.appendChild(document.createTextNode("Delete"));

Solution

Hi You just need to move the delete button code inside your createListElement() function

See I have attached your code see below...

var button = document.getElementById("enter");
var input = document.getElementById("userinput");
var ul = document.querySelector("ul");
var list = document.querySelectorAll('ul>li');



function inputLength() {
    return input.value.length;
}

function createListElement() {
  /*Your delete button code MOVED HERE*/
  var deleteButton = document.createElement("button");
  deleteButton.setAttribute("class", "btn");
  deleteButton.appendChild(document.createTextNode("Delete"));
  /*end*/
    var li = document.createElement("li");
    li.appendChild(document.createTextNode(input.value));
    ul.appendChild(li).addEventListener("click", toggleList); //append and toggle on and off new list items
    input.value = "";
  ul>li.appendChild(deleteButton).addEventListener("click", removeItem); //append "delete button" to newly added "li"
}


function addListAfterClick() {
    if (inputLength() > 0) {
        createListElement();
    }
}

function addListAfterKeypress(event) {
    if (inputLength() > 0 && event.keyCode === 13) {
        createListElement();
    }
}



button.addEventListener("click", addListAfterClick);

input.addEventListener("keypress", addListAfterKeypress);


//Toggle list item on and off when clicked on 
var list = document.querySelectorAll('ul>li');
for (var i = 0; i < list.length; i++) {
list[i].addEventListener("click", toggleList);
}
function toggleList() {
  event.target.classList.toggle("done"); //or this.classList.toggle("done");
}

                      
//Delete list item by clicking on the delete button next to it
var elements = document.getElementsByClassName("btn");
for (var i = 0; i < elements.length; i++){
  elements[i].addEventListener("click", removeItem);
}
  
function removeItem(){
this.parentNode.remove();
}       

//3. BONUS: When adding a new list item, it automatically adds the delete button next to it hint: be sure to check if new items are clickable too!
.coolTitle {
  text-align: center;
  font-family: 'Oswald', Helvetica, sans-serif;
  font-size: 40px;
  transform: skewY(-10deg);
  letter-spacing: 4px;
  word-spacing: -8px;
  color: tomato;
  text-shadow: 
    -1px -1px 0 firebrick,
    -2px -2px 0 firebrick,
    -3px -3px 0 firebrick,
    -4px -4px 0 firebrick,
    -5px -5px 0 firebrick,
    -6px -6px 0 firebrick,
    -7px -7px 0 firebrick,
    -8px -8px 0 firebrick,
    -30px 20px 40px dimgrey;
}

.done {
  text-decoration: line-through;
}

.btn {
  display: inline;
  border-color: white;
  margin-left: 15px;
  border-radius: 5px;
}
 <h1>Shopping List</h1>
    <p id="first">Get it done today</p>
    <input id="userinput" type="text" placeholder="enter items">
    <button id="enter">Enter</button>
    <ul id = "list">
        <li>Notebook<button class="btn">Delete</button></li><br>
        <li>Jello<button class="btn">Delete</button></li><br>
        <li>Spinach<button class="btn">Delete</button></li><br>
        <li>Rice<button class="btn">Delete</button></li><br>
        <li>Birthday Cake<button class="btn">Delete</button></li><br>
        <li>Candles<button class="btn">Delete</button></li><br>
    </ul>



Answered By - John
Answer Checked By - Gilberto Lyons (PHPFixing Admin)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Friday, October 14, 2022

[FIXED] How do I clear the contents of a div without innerHTML = "";

 October 14, 2022     dom, dom-manipulation, html, javascript     No comments   

Issue

I have a div that is filled by JS created DOM elements,

I want the div to be cleared upon the JS function repeating, however I have heard that using document.getElementById('elName').innerHTML = ""; is not a good idea,

What is a valid alternative to doing this to clear the div's contents?


Solution

If you have jQuery then:

$('#elName').empty();

Otherwise:

var node = document.getElementById('elName');
while (node.hasChildNodes()) {
    node.removeChild(node.firstChild);
}


Answered By - Alnitak
Answer Checked By - Candace Johnson (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Older Posts Home
View mobile version

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
All Comments
Atom
All Comments

Copyright © PHPFixing