Jquery Each Input Within DIV (Has A Table) - javascript

Im currently trying to get all input elements from a DIV.
$("[required]").each(function() {
});
I have this code which returns every element with a required attribute.
I know within the function of that each() I can use each item like:
$(this)
So I get the div ID's shown below, and try to get all the inputs from it via:
var id = $(this).attr('id');
console.log("### " + id);
console.log($("#" + id + " > :input").length);
Which returns 0 when I have 4 in put elements within that DIV (also theres a table in the div).
What I would ideally like to do is for each input element within my div, print its ID.
UPDATED
<div id="contactAddress" required="true">
<td>Addres line 1:</td>
<td colspan="2">
<input type="text"/>
</td>
<td>Addres line 2:</td>
<td colspan="2">
<input type="text" />
</td>
</tr>
</div>
console.log($(this).html());
Shows nothign but if i add anythign outsire the or like below...
<div id="contactAddress" required="true">
<input type="text" />
And run console.log($(this).html()); It shows it put not the table?
Any ideas im using Jquery Mobile

This below will find all inputs inside the div element. It will then leave a log of the id of this element.
$("div > input").each(function() {
console.log( $(this).attr("id") );
});
if you need the div id containing the inputs you could use .parent()
$("input").each(function() {
console.log( $(this).parent().attr("id") );
});

Related

How to use checked input values used for math as part of cloned div elements

I have written a script that clones a certain div as required by the user. Within the div there are three checkbox input options and each option as a numeric value. I want the script to allow the user to select a checkbox and then the value will be reflected in another input space and each value that are added will be separated by a comma.
The tricky part is that it should be done for each clone, and that each checkbox has the same class name to which the script should be written. I realize that using unique id's would be better, but I would like it that a for loop could do it for any number of checkboxes under the specific class.
Here is the html script:
<style>
.hidden {
display: none;
}
</style>
<body>
<h2>Test</h2>
<button id="add">Add</button>
<div class="test hidden">
<div class="user_input1">
<label>Input1</label>
<input class="input1" type="text" required>
<label>Input2</label>
<input type="text" name="value2" required>
<div class="user_input2">
<table>
<thead>
<tr>
<th>Pick Option</th>
</tr>
</thead>
<tbody>
<tr id="append">
<td><input class="test" type="checkbox" name="test" value="1">Test1</td>
<td><input class="test" type="checkbox" name="test" value="2">Test2</td>
<td><input class="test" type="checkbox" name="test" value="3">Test3</td>
</tr>
</tbody>
</table>
<input type="text" id="insert" name="check">
<button class="hidden" id="testbtn">Calc</button>
</div>
</div>
</div>
<form action="server/server.php" method="POST">
<div class="paste">
</div>
<button type="submit" name="insert_res">Submit</button>
</form>
</body>
And my attempt for the jQuery:
$(document).ready(function() {
var variable = 0
$("#add").click(function() {
var element = $(".test.hidden").clone(true);
element.removeClass("hidden").appendTo(".paste:last");
});
});
$(document).ready(function(event) {
$(".test").keyup(function(){
if ($(".test").is(":checked")) {
var test = $(".test").val();
};
$("#insert").val(test);
});
$("#testbtn").click(function() {
$(".test").keyup();
});
});
I think a for loop should be used for each checkbox element and this to specify each individual clone, but I have no idea where or how to do this. Please help!
I am assuming you already know how to get a reference to the dom element you need in order to append, as well as how to create elements and append them.
You are right in that you can loop over your dataset and produce dom elements with unique id's so you can later refer to them when transferring new values into your input.
...forEach((obj, index) => {
(produce tr dom element here)
(produce three inputs, give all unique-identifier)
oneOfThreeInputs.setAttribute('unique-identifier', index); // can set to whatever you want, really
(proceed to creating your inputs and appending them to the tr dom element)
targetInputDomElementChild.setAttribute('id', `unique-input-${index}`); // same here, doesn't have to be class
});
Observe that I am using template strings to concat the index number value to the rest of the strings. From then on, you can either reference the index to refer to the correct input or tr using jquery in your keyUp event handler:
function keyUpEventHandler($event) {
const index = $(this).attr('unique-identifier');
const targetInput = $(`#unique-input-${index}`)
// do stuff with targetInput
}
I have created a fiddle to show you the route you can take using the above information:
http://jsfiddle.net/zApv4/48/
Notice that when you click an checkbox, in the console you will see the variable number that designates that set of checkboxes. You can use that specific number to get the input you need to add to and concat the values.
Of course, you still need to validate whether it is being checked or unchecked to you can remove from the input.

Remove created element by id using jquery [duplicate]

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();
});
});

target only relevant div

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);
}
});

How to remove displayed value from td and replace with input field?

I have dynamic table that display names and input fields. If name is displayed in table row user have option to delete that name. I know how to remove value from specific table row but I have problem replacing that same spot with input field that should be the same as other available fields. Here is my code that I have so far:
<cfoutput>
<tr>
<td>#TimeFormat(CurrentTime,'hh:mm tt')#</td>
<td onClick="deleteSlot('#TimeSlotID#')">
<cfif UserID GT 0>
<label>
<div id="#TimeSlotID#">
(<b>#First# #Last#</b>)
<img src="images/delete.png"/>
</div>
</label>
<cfelseif UserID EQ -1>
<label>
<input type="text" name="email" id="email#currentRow#" class="email">
<input type="button" name="slot" id="slot#currentRow#" class="slot" value="Save" onClick="saveTime(this,'#TimeSlotID#')" style="display: none">
</label>
</cfif>
</td>
</tr>
</cfoutput>
JavaScript:
//This code display save button if user start typing in available field.
$(document).ready(function() {
$(".email").keyup(function(e) {
if($(this).val() != '') {
$(".email").not(this).attr('disabled','disabled');
$(this).next(".slot").show();
} else {
$(".email").removeAttr('disabled');
$(this).next(".slot").hide();
}
});
});
//This is the code where I'm trying to remove name from the cell and replace with input field
function deleteSlot(TimeSlotID){
$('#' + TimeSlotID).replaceWith('<label><input type="text" name="email" id="email#currentRow#" class="email"><input type="button" name="slot" id="slot#currentRow#" class="slot" value="Save" onClick="saveTime(this,'#TimeSlotID#')" style="display: none"></label>');
}
This code that I currently use in deleteSlot function does replace name with input field but if I start typing in that field I do not have Save button showed up like in the others. I'm not 100% sure if this can be done the way I started or I should use something else. I tried append but that did not work, gave me extra input fields every time I clicked. If anyone knows better way to fix this please let me know.
I believe the event keyup needs to be re-applied:
$(document).ready(function() {
applyKeyUp();
});
function applyKeyUp() {
$(".email").keyup(function(e) {
if($(this).val() != '') {
$(".email").not(this).attr('disabled','disabled');
$(this).next(".slot").show();
} else {
$(".email").removeAttr('disabled');
$(this).next(".slot").hide();
}
});
}
function deleteSlot(TimeSlotID){
$('#' + TimeSlotID).replaceWith('<label><input type="text" name="email" id="email#currentRow#" class="email"><input type="button" name="slot" id="slot#currentRow#" class="slot" value="Save" onClick="saveTime(this,'#TimeSlotID#')" style="display: none"></label>');
applyKeyUp();
}
The issue is with weirdness of the id you are passing.Since the id is already having '#' in front of it, the jquery selector would not be able to apply the target by id. If you really need '#' in front of the id, then you need to apply id equal to selector.
$('#' + TimeSlotID)
should be
$("[id = '" + TimeSlotID + "']")
Example : https://jsfiddle.net/DinoMyte/6d5ry9br/5/

How to remove cloned element div except first div using jquery

I have a problem with removing cloned div. I*m unable to remove the cloned div which div clicked on to be remove. My code is like below:
<div id="item_details">
<table>
<tr>
<td>
<p class="label_text">Name:</p>
</td>
<td>
<input name="item_name[]" type="text" value="" id="item_name" class="input_text" style="width: 126px;" />
</td>
<td>
<p class="label_text">Brand:</p>
</td>
<td>
<input name="item_brand[]" type="text" value="" id="item_brand" class="input_text" style="width: 126px;" />
</td>
<td>
<p class="label_text">Model No:</p>
</td>
<td>
<input name="model_number[]" type="text" value="" id="model_number" class="input_text" style="width: 126px;" />
</td>
</tr>
</table>
<p style="margin:-16px 0px 0px 600px;">
Remove Item
</p>
</div>
<div id="new_item_details" class="new_item_details"></div>
<p style="margin:0px 0px 0px 0px;">
Add New Item Here
</p>
And my jquery code like this:
<script src="http://code.jquery.com/jquery-latest.min.js"
type="text/javascript"></script>
<script>
jQuery(document).ready(function(){
var id=0;
var max=10;
jQuery('#add_item').click(function(){
var button = $('#item_details').clone();
id++;
button.find('input').val('');
button.removeAttr('id');
button.insertBefore('.new_item_details');
button.attr('id','new_'+id);
});
jQuery('.remove').click(function(e){
jQuery("#new_1").last().remove();
//jQuery('#removeitem').toggle( !$("#new_item_details").is(":empty") );
e.preventDefault();
});
});
</script>
I tried like this. For every cloned div I appended new div id with increment number. But I'm unable to remove the particular cloned div. First div dont be removed. please help me how to solve this. Thanks.
The problem is that you subscribe to .remove elements click event at page load. The .remove elements inside your cloned divs will not be part of this subscribe. You have to use event delegation to subscribe to new elements created after page load as well:
replace:
jQuery('.remove').click(function(e){
by
jQuery(document).on('click', '.remove', function(e){
Also, a simpler solution will be to just remove the parent div of your clicked .removeelement:
jQuery(document).on('click', '.remove', function(e){
var parentDiv = jQuery(this).parent().parent();
// if not original div (id == item_details)
if(parentDiv.attr('id') !== 'item_details') {
parentDiv.remove();
}
e.preventDefault();
});
Whilst the first answer was there before me and pointed out the problem with the click, I'll still post this as I may as well, it's a different approach to solving the removal.
I've added data attributes to each of the clones, and a corresponding data-id to the button too, so on click it check it's id and removes the form with that id.
So if it helps :) http://jsfiddle.net/sfmwbgfa/
jQuery(document).ready(function(){
var id=0;
var max=10;
jQuery('#add_item').click(function(){
var button = $('#item_details').clone();
id++;
button.find('input').val('');
button.removeAttr('id');
button.insertBefore('.new_item_details');
button.attr('id','new_'+id).attr('data-id', id);
button.find('.remove').attr('data-id',id);
});
jQuery(document).on('click', '.remove', function(e){
var thisId = jQuery(this).data('id');
jQuery('div[data-id="'+thisId+'"]').remove();
//jQuery('#removeitem').toggle( !$("#new_item_details").is(":empty") );
e.preventDefault();
});
});
try
use event delegation like which is used by manji
jQuery(document).on("click",".remove",function (e) {
OR use clone(true) : it will copy event handler (deep copy)
var button = $('#item_details').clone(true);
NOTE: id should be unique
var id = 0;
jQuery(document).ready(function () {
var max = 10;
jQuery('#add_item').click(function () {
var button = $('#item_details').clone(true);
id++;
button.find('input').val('');
button.removeAttr('id');
button.insertBefore('.new_item_details');
button.attr('id', 'new_' + id);
});
jQuery('.remove').click(function (e) {
jQuery("#new_"+id).remove();
//jQuery('#removeitem').toggle( !$("#new_item_details").is(":empty") );
id--;
e.preventDefault();
});
});
**
DEMO
**

Categories