I have a block of list element which I need to add when "Add" button is clicked.
HTML:
<li>
<div><h3 >User name sss updated this.
<input type="button" value="X" class="delete"/></br></h3>
</div>
SOME TEXT HERE
</li>
jQuery:
$(".delete").click(function(){
$(this).closest("li").slideUp();
});
$("#addPost").click(function(){
var inData = '<li><div><h3>User name sss updated this.<input type="button" value="X" class="delete"></input></br></h3></div>';
$("#midContent ul").append(inData+'Sarthak</li>');
});
This block has a delete button and a jQuery function attached to it.
If the block already exist on the page, its working fine.
But, when I add this block using jQuery append, the block is rendered rightly, but delete functionality does not work on newly added block.
Where I am going wrong?
Also, what will be the better way to add this block than hardcoding in JS code? (just by referring the element already on page by using id or class)
You need to delegate events for dynamically created DOM nodes. You can delegate to the parent div, or the document itself.
$(document).on('click', '.delete', function(e) {
//your code here
});
The second argument in the click handler is the selector for which you are attaching the click handler.
Further reading: http://learn.jquery.com/events/event-delegation/
Try to use the event .on('click',function(){}) on dynamically created elements.
$(".delete").on('click',function(){
$(this).closest("li").slideUp();
});
$("#addPost").on('click',function(){
var inData = '<li><div><h3>User name sss updated this.<input type="button" value="X" class="delete"></input></br></h3></div>';
$("#midContent ul").append(inData+'Sarthak</li>');
});
Also, why create a variable when you could append the code directly?
Related
help me out with this code, I am trying to assign a class to the clicked button's child element but when I fire a click event on any one of the button that class is assigned to all buttons child elements.I have written the jquery code for it mentioned below which works, but it works when i double click on one of the buttons and also the javascript code works in console but not in my js, html files i have the js block of code in $(document).ready(function(){}); function. I need help!
Html Code:
<div class="interact-Box">
<button class="p-emote"><i class="fas fa-thumb"></i></button>
<button class="p-emote"><i class="fas fa-thumb"></i></button>
<button class="p-emote"><i class="fas fa-thumb"></i></button>
<button class="p-emote"><i class="fas fa-thumb"></i></button>
</div>
Javascript Code:
$(.p-emote).on('click', ()=>{
var c = $(this).children('i');
$(c).toggleClass('interacted');
});
Use the event target (the event being the click, the target being the specific element that was clicked) by passing the event object into the callback.
$('.p-emote').on('click', (event)=>{
var c = $(event.target).children('i');
$(c).toggleClass('interacted');
});
EDIT: other answer rightly points out that you need quotes around the selector name ('.p-remote')
https://api.jquery.com/event.target/
You are missing single quotes around your selector and also don't use arrow function as it changes the way you are referencing $(this) into the window object. If you switch it back to something like the code below, you will see your children. Cheers.
$('.p-emote').on('click', function () {
var c = $(this).children('i');
console.log($(this).children('i'));
$(c).toggleClass('interacted');
});
I am creating a responsive data table that adds a row each time I click on a add button that is in the end of the row. And the add button turns into a delete button. Here's the code I made
For the Table:
<table id="invoice_table_data">
<tr id="last_row">
<td contenteditable id="item_name"></td>
<td contenteditable id="item_code"></td>
<td contenteditable id="description"></td>
<td>
<button type="button" name="btn_add" id="btn_add" class="btn btn-xs btn-success">+</button>
</td>
</tr>
</table>
When for adding is clicked:
$("#btn_add").click(function() {
$("#invoice_table_data").append('<tr id="myTableRow'+'" ><td id="item_name'+n+'">'+item_name+'</td><td id="item_code'+n+'"> '+item_code+'</td><td id="description'+n+'">'+description+'</td><td><button type="button" name="delete_" id="delete_" data-idx="'+n+'">x</button></td></tr>');
n+=1;
And my delete function:
$('#delete_').click( function () {
var nb=$(this).data('idx');
$("#last_row"+nb).remove();
});
However when I click on delete nothing seems to happen. Can anybody help?
Identifiers in HTML must be unique, So create the element using CSS class. then Class Selecctor can be used.
Change script to render HTML as
<button type="button" class="delete_">x</button>
Currently what you are using is called a "direct" binding which will only attach to element that exist on the page at the time your code makes the event binding call.
Use .on() method with Event Delegation approach while generating elements dynamically. So change your code to
$("#invoice_table_data").on('click', ".delete_", function(){
$(this).closest('tr').remove();
});
var n = 1;
$("#btn_add").click(function() {
$("#invoice_table_data").append('<tr><td>item_name' + n + '</td><td><button type="button" class="delete_" data-idx="' + n + '">x</button></td></tr>');
n += 1;
});
$("#invoice_table_data").on('click', ".delete_", function() {
$(this).closest('tr').remove();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table id="invoice_table_data">
<tr id="last_row">
<td id="item_name"></td>
<td>
<button type="button" name="btn_add" id="btn_add" class="btn btn-xs btn-success">+</button>
</td>
</tr>
</table>
Use attribute selector and event delegation
$(document).on('click', "[id^='delete_']", function () {
var nb=$(this).data('idx');
$("#last_row"+nb).remove();
});
Try this :
$('document').on('click', '#delete_', function () {
var nb=$(this).data('idx');
$("#last_row"+nb).remove();
});
You need to use on method, since your delete button not yet been exists.
You have two separate problems.
Problem 1
You can't have the same id multiple times on the page. That's just a basic rule of HTML. You can only use it once. If you use the same id more than once, only the first time will be counted.
Solution
If you want to be able to target multiple elements, use classes, or target a single parent and grab it's children using element.firstElementChild
Problem 2
When you write .click, you are telling the browser to watch for when a user clicks on the element that you are targeting.
However, that element has to exist when the page first loads. That is because the lines of Javascript are only parsed once by the browser. It reads through your code, and if the element you want to click on doesn't exist right then, your code is skipped.
Solution
So what you have to do to address this is to add the event listener, the .click, onto an element which isn't dynamic. Remember that every click event gets passed up the chain, from the inner most element that the user clicked on, to that element's parent, to the next parent, and so on until it reaches the body element. So if you add a .click onto the parent of your list, it'll be attached correctly.
Using jQuery, it would be something like:
$('#invoice_table_data').on('click', 'button.delete', function(event){
//run code here
});
Change your script which is dynamically adding the delete button to give the button a class name of btnDelete or something similar.
$("#btn_add").click(function() {
$("#invoice_table_data").append('<tr id="myTableRow'+'" ><td id="item_name'+n+'">'
+item_name+'</td><td id="item_code'+n+'"> '
+item_code+'</td><td id="description'+n+'">'
+description+'</td><td><button type="button" class="btnDelete" name="delete_" id="delete_" data-idx="'+n+'">x</button></td></tr>');
n+=1;
});
Then the script for your delete button is:
$("body").on("click", ".btnDelete", function (e) {
var rowToDelete = $(this).closest("tr");
rowToDelete.remove();
});
http://codepen.io/ailinmcc666/pen/ZBgXBZ
so what I'm triying to achieve is that I want one element to append some other elements to div and change its ID attribute (or something similar).
i have tried something like this
$('#add3').click(function(){
$('#add3').attr("id", "add4");
$('.third_row1').append('something to append');
});
and also tried something like this:
$('#add').click(function(){
var vari = $("<div id='add2'>add another user</div>");
$('#add').remove();
$('.third_row1').append(vari);
$('.third_row1').append('something to append');
});
so clicking one button (like second example) has no effect on third, fourth ... n click
same thing with the second example
thanks in advance for help
UPD
ok, so here's how I generate selects which I want to append
<jsp:useBean id="obj1" class="com.Users" scope="page"/>
<div class="third_row1">
<select name="mySelect1" id="mySelect1">
<c:forEach var="item1" items="${obj1.items}">
<option>${item1}</option>
</c:forEach>
</select>
</div>
all I want to do is to add same select, but with different ids and names
Since elements IDs are changed dynamically, you should use delegated event handlers with .on().
For example:
$(document).on("click", "#add3", function() {
$('#add3').attr("id", "add4");
$('.third_row1').append('something to append');
});
If all these elements (#add, #add3) are inside page static element, it will be better to use this element instead of document for perfomance:
$("static_element_selector").on("click", "#add3", function() {
And just to note: since this inside event handler points to clicked DOM element, you can use this.id = "add4" instead of $('#add3').attr("id", "add4");. It is shorter and works slightly faster.
I am working on an Ajax Live Search. My goal: When you click on one of the suggested results, the result shall be inserted into the search field. For example, when you enter "ros" into the input field and you want to look for roses and roses is a result suggested to you, then I want roses to show up in the search field on click.
<!-- Lets assume that up to this point the user has typed "ros"
into the following field -->
<input id="search" type="text">
<!-- ... then roses is a suggested result, with "ros" being highlighted -->
<ul id="results">
<li class="result">
<a>
<b class="highlight">ros</b>"es"</p>
</a>
</ul>
Here is the jQuery code that I have come up with so far, but it won't work:
$('#results a').click(function() {
var selection = $(this).html();
$('#search').val(selection);
});
Anyone has detected the error?
seems to be case of event delegation:
$('#results').on('click', 'a', function() {
what i see you have some dynamically generated links in the list as if user searches for something. if this is the case then you have to delegate the event to the closest static parent which is in your case is #results because an event is not bound to dynamically generated elements as they were not available when you bound the event.
Also there is a notice as you have a closing tag of </p> which doesn't have a opening tag. also if you want to place the text of the clicked element then you don't have to use .html(), you can use .text() method instead.
Yout HTML is invalid. You have a closing </p> without an opening one inside your <a> tag
Firstly I don't think you should simply use $(this).html() as it will include the html-tags, and you probably don't want that inserted.
But I think the reason you can't get it to work (I'm assuming absolutely nothing happens) is because you set the listener before the results are loaded, and hence they aren't bound to the links. Use $('#results').on('click', 'a', function(){}) to bind events "up front".
$('#results a').click(function() {
var selection = $(this).text();
$('#search').val((selection.replace("\"", "")).replace("\"", ""));
});
I have created a label element. I need to add onclick event to that...
function a(me) {
var d=document.createElement("label");
d.id=me.id;
d.onClick="a(10)";
d.innerHTML="welcome";
document.body.appendChild(d);
}
HTML:
<label id="1" onclick="a(this)">aa</label>
<label id="2" onclick="a(this)">bb</label>
<label id="3" onclick="a(this)">aa</label>
actually what happens is when i click the any of three labels in html. another label is created and displays welcome. now when i click the newly created label "welcome" it does not display anything...... that is the onclick event added to newly created label is not working ....... any suggestion.................
You need to set d.onclick=function(){a(1);};, note that the case matters here (not "onClick").
[Edit]
Based on your comments and updated questions I've created a jsFiddle to demonstrate how you might turn your code into something that works.
d.setAttribute('onclick', 'alert(\'hello\');');
For creating an attribute to a HTML tag, sometimes we have to add this:
yourTag.src
yourTag.src = 'http://lolxd.com/404.png'
But there are special attributes, and them have diferents ways for editing:
yourTag.classList
yourTag.className
And there is the onclick attribute, wichwe can use it like this:
// The first way
obj.onclick = function () { alert('lalala') }
// With the Event Listener
obj.addEventListener('click', function () { alert('lalala') }, false)
// Or, a text-render way
obj.setAttribute('onclick', 'alert(`lalala`)')
I recomend you the Event Listener way, but try all :D