I have a form where I am cloning the initial input fields as a template to allow the user to add as many options as they need to. Adding new fields works fine, but when attempting to remove them, the first one works as expected but all generated fields cannot be removed.
My knowledge of JS is very poor but I would assume that setting it to remove the parent should be the correct operation.
<script type="text/javascript">
$(function()
{
var template = $('#inventoryItems .inventory:first').clone(),
inventoryCount = 1;
var addInventory = function()
{
inventoryCount++;
var inventory = template.clone().find(':input').each(function()
{
var newId = this.id.substring(0, this.id.length-1) + inventoryCount;
$(this).prev().attr('for', newId); // update label for (assume prev sib is label)
this.name = this.id = newId; // update id and name (assume the same)
}).end() // back to .attendee
.attr('id', 'inv' + inventoryCount) // update attendee id
.appendTo('#inventoryItems > fieldset'); // add to fieldset
};
$('.btnAddInventory').click(addInventory); // attach event
});
$(function()
{
var removeInventory = function()
{
$(this).parent().remove();
};
$('.btnRemoveInventory').click(removeInventory); // attach event
});
</script>
HTML:
<div id="inventoryItems" class="inventoryItems" style="margin:0; padding:0;">
<fieldset style="width:62%; float:left; margin-left: 19%;">
<label>Inventory</label>
<div id="inv1" class="inventory">
<select name="invItem1" style="width:92%;">
<?php
$invItem_values = array("id", "name");
display_options_list($dp_conn, $invItem_values, "inventory", "id");
?>
</select>
<input class="btnRemoveInventory" type="button" style="background: url(images/icn_trash.png) no-repeat; cursor:pointer; border: none;">
</div>
</fieldset><div class="clear"></div>
<!-- Add Inventory Button -->
<div style="width:62%; margin:0; padding:0; float: right; margin-right: 19%">
<input class="btnAddInventory" type="button" value="Add Item" style="float: right;">
</div><div class="clear"></div>
</div>
Attaching events via click() (or any other shortcut event handler) only works with elements which are available on load of the page. Instead, because you are appending elements dynamically, you need to use a delegated event handler. Change this:
$('.btnRemoveInventory').click(removeInventory)
To this:
$('#inventoryItems').on('click', '.btnRemoveInventory', removeInventory)
This is attaching the event to the nearest static element, #inventoryItems, and then filters the events raised to see if the target matches .btnRemoveInventory.
Related
I am trying to use JQuery to update a data attribute after clicking on a button.
Please take a look at what I have tried below.
When I click on the div with class previous-wrapper, the whole block is well updated, and the data-nb-attribute get the correct value.
But, when I click on this div for the second time, data-nb-attribute gets the value NaN..
Is there another way to dynamically update and retrieve the value of this attribute?
$(function(){
$(document).on('click','.previous-wrapper',function(){
var get_nb = $(this).find('.previous');
get_nb = get_nb.data("nb");
get_nb = parseInt(get_nb)
//Dom to update
arr_left = $('<i/>', {
className: 'fa-solid fa-arrow-left'
});
previous = $('<div/>', {
className: 'previous',
'data-nb': get_nb-5,
html: "Previous"
});
//Question 2. How to append previous to arrow_left
$(".previous-wrapper").html(previous);
});
});
.previous-wrapper{
cursor: pointer;
background:red;
width:100px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="previous-wrapper">
<i class="fa-solid fa-arrow-left"></i>
<span class="previous" data-nb="100">Previous</span>
</div>
I would also like to know how to add multiple DOM created by JQuery.
You're overwriting the HTML with an invalid attribute of "classname" instead of "class", which means on the second interation $('.previous') won't match anything.
Corrected version of your code:
$(document).on('click', '.previous-wrapper', function() {
var get_nb = $(this).find('.previous');
get_nb = get_nb.data("nb");
get_nb = parseInt(get_nb)
//Dom to update
arr_left = $('<i/>', {
class: 'fa-solid fa-arrow-left'
});
previous = $('<div/>', {
class: 'previous',
'data-nb': get_nb - 5,
html: "Previous"
});
// including both elements at once:
$(".previous-wrapper").html([arr_left, previous]);
console.log($('.previous-wrapper').html())
});
.previous-wrapper {
cursor: pointer;
background: red;
width: 100px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="previous-wrapper">
<i class="fa-solid fa-arrow-left"></i>
<span class="previous" data-nb="100">Previous</span>
</div>
It would be much, much simpler, however, to simply update the one attribute you want to update, instead of rewriting all the HTML every click:
$(document).on('click', '.previous-wrapper', function() {
let el = $(this).find('.previous')
// update the data attribute using .attr() instead of .data() because jQuery handles .data internally; it's not reflected in the DOM
el.attr('data-nb', Number(el.attr('data-nb')) - 5);
console.log($('.previous-wrapper').html())
});
.previous-wrapper {
cursor: pointer;
background: red;
width: 100px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="previous-wrapper">
<i class="fa-solid fa-arrow-left"></i>
<span class="previous" data-nb="100">Previous</span>
</div>
I am new to HTML ,JavaScript and jQuery. I am currently doing a search box, when I start to type text on the search input the search list must appear and able to click the search list name and append it to search input, and close the search list and left with search input and current text that I clicked on the search list.
var $block = $('.no-results');
$(".personsMenu").hide();
$(".my-textbox").keyup(function() {
var textbox = document.getElementById("textboxEmp");
var val = $(this).val();
var isMatch = false;
var nameAp = document.getElementsByClassName("name12");
$(".personsMenu").show();
if (textbox.value == 0) {
$(".personsMenu").hide();
}
$(".personsMenu div").each(function() {
var content = $(this).html();
if ((content.toLowerCase().indexOf(val) == -1) && (content.toUpperCase().indexOf(val) == -1)) {
$(this).hide();
} else {
isMatch = true;
$(this).show();
}
});
$block.toggle(!isMatch);
});
function mySelect() {
$(".name12").appendTo($(".my-textbox"));
$(".personsMenu").hide();
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<div class="cover">
<div name="selected">
<i class="mdi-account-search mdi"></i><input class="my-textbox" id="textboxEmp" autofocus="autofocus" placeholder="search staff member" />
</div>
<div class="personsMenu">
<ul class="infor">
<div class="nm1" name="selected">
<li class="name12" onclick="mySelect()">Malubane Nyikiwe</li>
<li>nyikiwe.malubane#m-t.co.za</li>
</div>
<div class="no-results">no employee found by that name</div>
<div class="nm1" name="selected">
<li class="name12" onclick="mySelect()">Chamano Sydney</li>
<li>sydney.chamano#m-t.co.za</li>
</div>
<div class="nm1" name="selected">
<li class="name12" onclick="mySelect()">Diphofa Tumelo</li>
<li>tumelo.diphofa#m-t.co.za</li>
</div>
</ul>
</div>
</div>
There's several issues in your code which all need to be addressed:
You're using invalid HTML. ul elements can only contain li, not div. I'd suggest restructuring the HTML to use div containers to hold the information for each item in your list.
Use CSS to hide content which should not be visible when the page loads. This avoids the FOUC which can happen as JS only runs after the DOM is ready.
If you've included jQuery in the page, you may as well use it consistently to make your code more succinct.
Use the input method, not keyup, for listening to user input. input will also fire when the user copies content in to the field using the mouse for example, keyup won't.
Use unobtrusive event handlers, eg. jQuery's on() method, not inline onclick attributes. The latter is outdates and bad practice at it doesn't allow for good separation of concerns.
When searching text, equalise the cases of the search and target strings, don't search for both upper and lower versions.
Use text() to search for the content, not html().
To set the value of an input element use val(), not append(). The latter is for adding HTML/text content to an element, not setting its value property.
With all that said, the working code will look something like this:
var $noResults = $('.no-results');
var $names = $(".name12");
var $personsMenu = $('.personsMenu');
var $searchBox = $(".my-textbox").on('input', function() {
var value = $(this).val().trim().toUpperCase();
if (!value) {
$personsMenu.hide();
return;
}
var matches = $personsMenu.show().find('div').each(function() {
var content = $(this).text().toUpperCase();
$(this).toggle(content.indexOf(value) !== -1);
});
$noResults.toggle(matches.filter(':visible').length == 0);
});
$('.item').on('click', function() {
$searchBox.val($(this).find('.name12').text());
$personsMenu.hide();
});
.personsMenu,
.no-results {
display: none;
}
.item {
padding: 10px;
cursor: pointer;
}
.item:hover {
background-color: #CCC;
}
.item p {
margin: 0;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<div class="cover">
<div name="selected">
<i class="mdi-account-search mdi"></i>
<input class="my-textbox" id="textboxEmp" autofocus="autofocus" placeholder="search staff member" />
</div>
<div class="personsMenu">
<div class="no-results">no employee found by that name</div>
<div class="item">
<p class="name12">Malubane Nyikiwe</p>
<p class="email">nyikiwe.malubane#m-t.co.za</p>
</div>
<div class="item">
<p class="name12">Chamano Sydney</p>
<p class="email">sydney.chamano#m-t.co.za</p>
</div>
<div class="item">
<p class="name12">Diphofa Tumelo</p>
<p class="email">tumelo.diphofa#m-t.co.za</p>
</div>
</div>
</div>
The list was dynamically produced as follow;
function addItemsToList(name, surname, location, town, userid, email) {
var listEmployeesInfo=document.getElementById('mListHeader');
listEmployeesInfo.innerHTML='Province Retrieved: '+(location)+' | Town: '+(town);
var ul=document.getElementById('list');
var header=document.createElement('h2');
var _name=document.createElement('li');
var _surname=document.createElement('li');
var _userid=document.createElement('li');
var _email=document.createElement('li');
_name.innerHTML='Name : '+name;
_surname.innerHTML='Surname : '+surname;
_userid.innerHTML='User ID : '+userid;
_email.innerHTML='Email : '+email;
ul.append(header);
ul.appendChild(_name);
ul.appendChild(_surname);
ul.appendChild(_userid);
ul.appendChild(_email);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="column right" style="overflow-y: auto; height: 500px; " id="listDiv">
<h3 id="mListHeader" style="padding-left: 10px;">Employee List Viewed</h3><br>
<button id="btn-Update">Update</button>
<ul class="empList" id="list">
</ul>
</div>
How can I make li elements clicker-able? because I want to able to update name, surname, id and email of clicked group?
Use event delegation on the parent list
var ul = document.getElementById('list');
ul.addEventListener('click', function(evt) {
var tgt = evt.target;
if (tgt.matches('li')) {
console.log(tgt.textContent);
}
});
so you capture the click event on the bubbling phase with only one event handler, no matter if the list-items are already in the document or if they have been dynamically created.
As a side note you can't append a header as a child of a list (ul.append(header);)
I'm attempting to track events for all UI elements on a page. The page contains dynamically generated content and various frameworks / libraries. Initially I tracked elements through creating a css class "track" , then adding style "track" to tracked elements. elements are then tracked using :
$('.track').on('click', function() {
console.log('Div clicked' + this.id);
console.log(window.location.href);
console.log(new Date().getTime());
});
As content can be dynamically generated I wanted a method to track these elements also. So tried this using wildcard jQuery operator.
In this fiddle : https://jsfiddle.net/xx68trhg/37/ I'm attempting to track all elements using the jquery '*' selector.
Using jQuery '*' selector appears to fire the event for all elements of given type.
So for this case if is clicked all the click event is fired for all divs. But id is just available for div being clicked.
For the th element the click event is fired twice , what is reason for this ?
Can the source be modified that event is fired for just currently selected event ?
fiddle src :
$(document).ready(function() {
$('*').each(function(i, ele) {
$(this).addClass("tracked");
});
$('.tracked').on('click', function() {
console.log('Div clicked' + this.id);
console.log(window.location.href);
console.log(new Date().getTime());
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<!-- <div id="1" data-track="thisdiv">
Any clicks in here should be tracked
</div>
-->
<div id="1">
Any clicks in here should be tracked 1
</div>
<div id="2">
Any clicks in here should be tracked 2
</div>
<div id="3">
Any clicks in here should be tracked 3
</div>
<th id="th">tester</th>
You can try with:
$(document).ready(function() {
$("body > *").click(function(event) {
console.log(event.target.id);
});
});
$(document).ready(function() {
$("body > *").click(function(event) {
console.log(event.target.id);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="1">
Any clicks in here should be tracked 1
</div>
<div id="2">
Any clicks in here should be tracked 2
</div>
<div id="3">
Any clicks in here should be tracked 3
</div>
<table>
<tr>
<td>Cols 1</td>
<td id="td">Cols 2</td>
</tr>
</table>
<p id="th">tester</p>
You may want to use event delegation to target the elements you need. Advantage is that this also works for dynamically generated elements. See code for an example of this.
// method to add/set data-attribute and value
const nClicksInit = (element, n = "0") => element.setAttribute("data-nclicked", n);
// add data-attribute to all current divs (see css for usage)
// btw: we can't use the method directly (forEach(nClicksInit))
// because that would send the forEach iterator as the value of parameter n
document.querySelectorAll("div").forEach(elem => nClicksInit(elem));
// add a click handler to the document body. You only need one handler method
// (clickHandling) to handle all click events
document.querySelector('body').addEventListener('click', clickHandling);
function clickHandling(evt) {
// evt.target is the element the event is generated
// from. Now, let's detect what was clicked. If none of the
// conditions hereafter are met, this method does nothing.
const from = evt.target;
if (/^div$/i.test(from.nodeName)) {
// aha, it's a div, let's increment the number of detected
// clicks in data-attribute
nClicksInit(from, +from.getAttribute("data-nclicked") + 1);
}
if (from.id === "addDiv") {
// allright, it's button#addDiv, so add a div element
let newElement = document.createElement("div");
newElement.innerHTML = "My clicks are also tracked ;)";
const otherDivs = document.querySelectorAll("div");
otherDivs[otherDivs.length-1].after(newElement);
nClicksInit(newElement);
}
}
body {
font: 12px/15px normal verdana, arial;
margin: 2em;
}
div {
cursor:pointer;
}
div:hover {
color: red;
}
div:hover:before {
content: '['attr(data-nclicked)' click(s) detected] ';
color: green;
}
#addDiv:hover:after {
content: " and see what happens";
}
<div id="1">
Click me and see if clicks are tracked
</div>
<div id="2">
Click me and see if clicks are tracked
</div>
<div id="3">
Click me and see if clicks are tracked
</div>
<p>
<button id="addDiv">Add a div</button>
</p>
<h3 id="th">No events are tracked here, so clicking doesn't do anything</h3>
You can invoke the stopPropagation and the condition this === e.currentTarget to ensure invoke the handler function of the event source DOM.
And you must know the <th> tag must wrapped by <table>, otherwise it will not be rendered.
$(document).ready(function() {
$('*').each(function(i, ele) {
$(this).addClass("tracked");
});
$('.tracked').on('click', function(e) {
if (this === e.currentTarget) {
e.stopPropagation();
console.log('Div clicked' + this.id);
console.log(window.location.href);
console.log(new Date().getTime());
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<!-- <div id="1" data-track="thisdiv">
Any clicks in here should be tracked
</div>
-->
<div id="1">
Any clicks in here should be tracked 1
</div>
<div id="2">
Any clicks in here should be tracked 2
</div>
<div id="3">
Any clicks in here should be tracked 3
</div>
<table>
<th id="th">tester</th>
</table>
What I'm looking to do is remove the parenting div by ID after the button is clicked, to avoid closing all divs with the same class. In my actual code, the user is able to append multiple divs to the screen on button click, and each is assigned it's own ID. Each has a boostrap button up top that should close the parent div only instead of having to create 12 separate functions (the limit of div placement for the user).
HTML
<div class='some classes' id='box1'>
<span class='btn btn-primary'>Close this div</span>
</div>
<div class='some classes' id='box2'>
<span class='btn btn-primary'>Close this div</span>
</div>
CSS
#box {
width:200px;
height:200px;
background:black;
}
JS
$(document).ready(function(){
$('.btn').on('click',function(){
var getParentID = $('.btn').parent().attr('id');
$(getParentID).remove();
});
});
This is essentially all I was working with to try to get it to function. Any help is much appreciated!
Use $(this) instead of $('.btn') since you want to target the specific element
var getParentID = $(this).parent().attr('id');
Once the id is available use jquery id selector to target the element
$(document).ready(function() {
$('.btn').on('click', function() {
var getParentID = $(this).parent().attr('id');
$("#" + getParentID).remove();
});
});
#box {
width: 200px;
height: 200px;
background: black;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class='some classes' id='box1'>
<span class='btn btn-primary'>Close this div</span>
</div>
<div class='some classes' id='box2'>
<span class='btn btn-primary'>Close this div</span>
</div>
Note: The answer is specific to your question.Alternatively the parent div can be removed even without getting it's id
What you want to do is to skip the jQuery and do it in pure javascript.
var parent = child.parentElement;
parent.parentElement.removeChild(parent);