I have a file selector that populates a div with a thumbnail based on the file. Now I have multiple buttons and divs that contain the same class names. What I am using for each time the primary button is selected is, var thisButton = $(event.target); which translates to:
var appendThis = thisButton.closest('.insurance').find(".attachmentCont");
appendThis.append('<div class="singleImg"><img src="'+attachment.url+'" width="100px"/><input type="hidden" class="fileURL" value="'+attachment.id+'"/><span class="removeImg remove"> X </span></div>');
$(".removeImg").bind('click', function(){
$(this).parent().remove();
});
The appenThis equals the button which is within a div containing another div attachmentCont Both the button and div are within a parent div which is div.insurance There are multiple div.insurance containers. My issue is when using thisButton.closest('.insurance').find(".attachmentCont"); it always focuses on the .attachmentCont div that was first selected. So if I selected section 1, the image populates. If I select section 2, section 1 still gets that image when the div.attachmentCont within section 2 should of gotten the append() too.
Suggestions or Thoughts?
HTML EXAMPLE:
<div class="notes-section insurance">
<span><b>General </b></span><textarea style="width:97%;" rows="5" cols="50" class="insurance-description fields contractor_insurance_description" placeholder="...."></textarea>
<input type="date" class="expiration-date" placeholder="Expiration Date">
<br>
<span>Your</span>
<div class="attachmentCont">
</div>
<br>
<input type="button" class="upload_image_button" value="Attach Documents" style="width:150px;">
</div>
Here was the issue:
My blindness did not see that the function that contains the selected button was not in any way associated with the function that appended the data. Because of this all I had to do was move my var thisButton outside into the parent class.
Thank you everyone for you're time.
Solutions:
var thisButton
$('.upload_image_button').on('click', function( event ){
thisButton = $(event.target);
event.preventDefault();
});
....
function...({
var appendThis = thisButton.closest('.insurance').find(".attachmentCont");
appendThis.append('<div class="singleImg"><img src="'+attachment.url+'" width="100px"/><input type="hidden" class="fileURL" value="'+attachment.id+'"/><span class="removeImg remove"> X </span></div>');
$(".removeImg").bind('click', function(){
$(this).parent().remove();
});
});
Related
This question already has answers here:
Event binding on dynamically created elements?
(23 answers)
Closed 6 years ago.
i have a table for enter name and details. i have create new fields from a button but i can't remove anyone of my create except original one.
i try increase span class name for help to delete but nothing.Please help me to get it solve. Thanks in advance..
My original data table
<span class="source">
<span id="sprtdiv" class="tab1">
<table width="90%" border="1">
<tr><td><input type="text" class="yuzdeyetmis" name="partname[]" value="" id="pname" placeholder="Name" /><div id="tab1" class="yuzdeotuz"> DELETE </div></td></tr>
<tr><td><textarea rows="3" name="partdetay[]" id="pdetay" placeholder="Detail"></textarea></td></tr>
</table>
</span>
</span>
<input type="button" id="add_more_part" class="upload" value="Add New Record"/>
and i want to add and remove new data parts
$(".yuzdeotuz").click(function(){
var strtab = $(this).attr('id');
alert(strtab );
$("."+strtab).remove();
});
// To add new bolum stream source field dynamically, on click of "Add More Source" button
$('#add_more_part').click(function() {
var tabcount = $('.yuzdeotuz').length;
if (tabcount == 1 || tabcount != 1)
{
tabcount++;
mytab = "tab"+tabcount;
}
$(".source").append('<span id="sprtdiv" class='+mytab+'><table width="90%" border="1"><tr><td><input type="text" class="yuzdeyetmis" name="partname[]" value="" id="pname" placeholder="Name" /><div id='+mytab+' class="yuzdeotuz"> DELETE </div></td></tr><tr><td><textarea rows="3" name="partdetay[]" id="pdetay" placeholder="Detail"></textarea></td></tr></table> </span>');
});
For my working codes https://jsfiddle.net/c71Lmkeh/2/`
This isn't elegant. I added this function (had to add it to Window - apparently it's a jsFiddle thing.)
window.deleteRecord = function(deleteButton) {
var deleteButtonRow = $(deleteButton).closest("tr");
var textAreaRow = deleteButtonRow.next("tr");
deleteButtonRow.remove();
textAreaRow.remove();
}
Then to the "delete" div I added
onclick = "deleteRecord(this);"
It would be a little easier if the elements weren't spread across table rows, because that means having to delete both table rows. It's more common now just to use divs, so all of the elements for one record would be inside the one div, and you just delete that.
So in this case I'm deleting the row that the "delete" div is in and the next row.
if you need to add events in to elements inserted in to the DOM, you need to use the .on() function. Check this link and it will solve your problem
Is this what you're looking for?
Demo + Source code
JavaScript:
$(".add").on("click", function() {
var newDiv = $("<div class='details'><div class='inputs'><input type='text' class='input1'/><br/><br/><input type='text' class='input2'/></div><div class='button'><a href='#' class='delete'>Delete</a></div><br/></div>")
$(".source").append(newDiv);
$(newDiv).on("click", "a", function() {
$(newDiv).remove();
});
});
I have a div structured this way:
<div class="sez-form ripart">
<table class="inc_prev"></table>
<div class="previsioni">A</div>
</div>
In table "inc_prev" I have a button that allows you to add another group of these. So by hitting the button you will get a structure like this:
<div class="sez-form ripart">
<table class="inc_prev"></table>
<div class="previsioni">A</div>
</div>
<div class="sez-form ripart">
<table class="inc_prev"></table>
<div class="previsioni">B</div>
</div>
Each "inc_prev" table has this html:
<table class="inc_prev">
<tbody>
<tr>
<td><label>Mese: </label><select id="mese[]" name="mese[]"></td>
<td><label>Anno: </label><select id="anno[]" name="anno[]"></td>
<td><label>Percentuale: </label><input class="importo" type="text" name="percent[]" maxlength="14" size="15" value="">%</td>
<td><img class="addRow" src="../images/plus.png"></td>
</tr>
</tbody>
</table>
This is my JS:
$(document).on('blur','.importo',function(){
var input_value = $(this).val();
var azione =$('#azione').val();
if ($(this).closest('.sez-form').find('.previsioni').length) {
$('.previsioni').load('bp/ripart_prev.php?perc='+input_value+'&id='+azione);
}else{
console.log('qui');
$(this).closest('.sez-form').append('<div class="previsioni"></div>');
$('.previsioni').load('bp/ripart_prev.php?perc='+input_value+'&id='+azione);
}
});
It appends the "previsioni" div if it's not there or update it loading content from DB. In the starting situation it works fine: previsioni div is added or updated in the right way. If I hit the plus button and add the second block when this JS gets triggered both the "previsioni" div get updated with the same content.
So my question is: "how do I change my JS so that when executed only the target "previsioni" is updated?" So if I blur the second "importo" only it's "previsioni" (B) gets updated? I am already using closest as mentioned here but this is not preventing the other previsioni to be updated too
Problem is $('.previsioni') will select all the existing elements with the class. You need to reuse the relationship to target the specific div. Here in the code snippet I have cached the $(this).closest('.sez-form').find('.previsioni') in an object.
Read inline comments
$(document).on('blur','.importo',function(){
var input_value = $(this).val();
var azione =$('#azione').val();
//Use the relationship again to traverse and cache it in a vraible the content
var previsioni = $(this).closest('.sez-form').find('.previsioni');
//If exist
if (previsioni.length) {
previsioni.load('bp/ripart_prev.php?perc='+input_value+'&id='+azione)
}else{
console.log('qui');
//Create div using JQuery
var div = $('<div class="previsioni"></div>');
//Load the content
div.load('bp/ripart_prev.php?perc='+input_value+'&id='+azione)
//Append the data
$(this).closest('.sez-form').append(div);
}
});
I have a radio group which is contains 2 radio buttons. This radio group created after an Ajax response. I want to get the value of the checked radio button but i am unable to do this. Here is my implementation, any help would be appriciated.
HTML:
Yes<input class='radioInput' id='g1Positive' type='radio' name='g1' value='YES'/>
No<input class='radioInput' id='g1Negative' type='radio' name='g1' value='NO'/>
JS:
$('#resultTable').on("click", ".editForm2", function(){
var isIengStuWork = $('input:radio[name=g1]:checked').val();
});
Hopefully this simple Fiddle is the answer
As you didn't post the html I just display the value in a div when a button is clicked
Html
<input [value][2]="first" type="radio" name="foo">First
<input value="second" type="radio" name="foo">Second
<input value="third" type="radio" name="foo">Third
<button id="show">Show</button>
<div id="result"></div>
JS
$("#show").click(function() {
var value = $('input[name=foo]:checked').val();
$('#result').html(value);
});
UPDATE
After your comment I wonder if you're element with id "resultTable" would be a dynamically loaded one as the radio buttons. In that case that binding wouldn't work.
You should be reference there an already existing element in the DOM, a static element let's say. Although you could still be dynamically loading the element with class "editForm2"
More information on http://api.jquery.com/on/
That would be something like this
$('#staticParentElement').on('click', '#dynamicChildElement', function(){ //whatever });
I have created this updated Fiddle. In it I mimic the ajax addition of elements to the DOM by displaying a button that adds content
In the first case I just add the content inside the table to an existing container, to which I bind the click event of the "show" button
So we add the radio buttons and the show button to a static #staticTable
<div id="staticTable"></div> <br/>
<button id="addStatic">Add dynamic content into static Table</button><br/>
$("#addStatic").click(function() {
$('#staticTable').append("Dynamic content into static table<br/>Yes<input class='radioInput' id='g1Positive' type='radio' name='g1' value='YES'/>No<input class='radioInput' id='g1Negative' type='radio' name='g1' value='NO'/><button class='show'>Show</button>");
});
And then we are able to bind the show button click like this
$("#staticTable").on('click', '.show', function() {
var value = $(':radio[name=g1]:checked').val();
$('#staticResult').html(value);
});
This works
But if we were adding to the DOM the "container" we are binding to, it wouldn't work. In the fiddle for example we inject a #dynamicTable inside a div
<div id="ContainerForDynamicTable"></div><br/>
<button id="addDynamic">Add dynamic Table</button><br/><br/>
$("#addDynamic").click(function() {
$('#ContainerForDynamicTable').append("Dynamic table<br/><div id='dynamicTable'>Yes<input class='radioInput' id='g1Positive'type='radio' name='g1' value='YES'/>No<input class='radioInput' id='g1Negative' type='radio'name='g1' value='NO'/></div><button class='show'>Show</button>");
});
and we try to bind the show button click selecting that #dynamicTable
$("#dynamicTable").on('click', '.show', function() {
var value = $(':radio[name=g1]:checked').val();
$('#dynamicResult').html(value);
});
This doesn't work
Notice that for making the last one we should find a static parent of the .show button, in this case the closest in the upwards tree would be #ContainerForDynamicTable (you can even go up until document although it would be more costly to find later the .show button)
Try this:
$('#resultTable').on("click", ".editForm2", function(){
var checked_ele = $('input[type="radio"][name="g1"]:checked');
$(checked_ele).each(function(){
// do stuff here
});
});
I did a form on which you can click a + button and add clones... The div inside has 3 elements - a span, a textbox and the button.
I clone like this:
<script>
var actorcount = 1;
$(document).ready(function(){
$(document.getElementById("btexp1")).click(function(){
var $div = $('div[id^="actordiv"]:last');
var id= Number( $div[0].id.match(/\d+/g) ) + 1;
var $clones=$div.clone().attr('id', 'actordiv'+id);
$div.after($clone);
actorcount++;
});
});
</script>
This clones the div and gives the id = "actordiv"+counter;
The div HTML is like this:
<div id="actordiv" style=" padding-left: 5px">
<span class="add-on"><strong>Actor</strong></span>
<input class="input-xlarge" type="text" id="actor" style="height:30px">
<span class="btn" id="btexp1">+</span>
</div>
The problem is the textbox inside all the divs created have the same id="actor";
Now I want to access the textbox with the id="actor" inside all the divs the user made which will have the ids="actordiv1" 2 3 etc... how can I access this with PHP?
Or if better change the textbox id="actor" ids...
Hello guys i have the below html for a number of products on my website,
it displays a line with product title, price, qty wanted and a checkbox called buy.
qty input is disabled at the moment.
So what i want to do is,
if the checkbox is clicked i want the input qty to set to 1 and i want it to become enabled.
I seem to be having some trouble doing this. Could any one help
Now i can have multiple product i.e there will be multiple table-products divs within my html page.
i have tried using jQuery to change the details but i dont seem to be able to get access to certain elements.
so basically for each table-product i would like to put a click listener on the check box that will set the value of the input-text i.e qty text field.
so of the below there could be 20 on a page.
<div class="table-products">
<div class="table-top-title">
My Spelling Workbook F
</div>
<div class="table-top-price">
<div class="price-box">
<span class="regular-price" id="product-price-1"><span class="price">€6.95</span></span>
</div>
</div>
<div class="table-top-qty">
<fieldset class="add-to-cart-box">
<input type="hidden" name="products[]" value="1"> <legend>Add Items to Cart</legend> <span class="qty-box"><label for="qty1">Qty:</label> <input name="qty1" disabled="disabled" value="0" type="text" class="input-text qty" id="qty1" maxlength="12"></span>
</fieldset>
</div>
<div class="table-top-details">
<input type="checkbox" name="buyMe" value="buy" class="add-checkbox">
</div>
<div style="clear:both;"></div>
</div>
here is the javascript i have tried
jQuery(document).ready(function() {
console.log('hello');
var thischeck;
jQuery(".table-products").ready(function(e) {
//var catTable = jQuery(this);
var qtyInput = jQuery(this).children('.input-text');
jQuery('.add-checkbox').click(function() {
console.log(jQuery(this).html());
thischeck = jQuery(this);
if (thischeck.is(':checked'))
{
jQuery(qtyInput).first().val('1');
jQuery(qtyInput).first().prop('disabled', false);
} else {
}
});
});
// Handler for .ready() called.
});
Not the most direct method, but this should work.
jQuery(document).ready(function() {
jQuery('.add-checkbox').on('click', function() {
jQuery(this)
.parents('.table-products')
.find('input.input-text')
.val('1')
.removeAttr('disabled');
});
});
use
jQuery('.add-checkbox').change(function() {
the problem is one the one hand that you observe click and not change, so use change rather as it really triggers after the state change
var qtyInput = jQuery(this).children('.input-text');
another thing is that the input is no direct child of .table-products
see this fiddle
jQuery('input:checkbox.add-checkbox').on('change', function() {
jQuery(this)
.parent()
.prev('div.table-top-qty')
.find('fieldset input:disabled.qty')
.val(this.checked | 0)
.attr('disabled', !this.checked);
});
This should get you started in the right direction. Based on jQuery 1.7.2 (I saw your prop call and am guessing that's what you're using).
$(document).ready(function() {
var thischeck;
$('.table-products').on('click', '.add-checkbox', function() {
var qtyInput = $(this).parents('.table-products').find('.input-text');
thischeck = $(this);
if (thischeck.prop('checked')) {
$(qtyInput).val('1').prop('disabled', false);
} else {
$(qtyInput).val('0').prop('disabled', true);
}
});
});
Removing the property for some reason tends to prevent it from being re-added. This works with multiple tables. For your conflict, just replace the $'s with jQuery.
Here's the fiddle: http://jsfiddle.net/KqtS7/5/