Child Div is not removed when tried to remove using Jquery - javascript

Clearing child div inside parent div, there are many answers like :
$(".ChildDiv").html("");
$('.ChildDiv > div').remove();
$(".ChildDiv").html("");
$("#ParentDiv").html("");
$(".ChildDiv div").remove();
$(".ChildDiv div").empty();
$('.ChildDiv ').find('div').remove();
Probably I have listed all possible way to remove the div's, but even after using all these, I still not able to clear all the div's inside Parent Div. let me explain what I am doing and what I need.
Scenario :
I have two container-1, one of the container has input search box, where I can search for entering employee name and select few employees Ex. 5 and can use "Add" button to move those employees to the other container-2 which is 'div'.
Now I click on report button event and get the information of those 5 people in different aspx, now if i go back to the page where i have to search for another 3 employees and when I again click on the "Add" button, it should add only 3 employees instead it is adding last searched 5 + 3 employees!!.
So i am trying to clear the 5 employees inside that div after i click on "Report" button , when i use alert() it says it has 0 element, but when I add it for the second time, it appends the data again, which i dont need. here is the code :
Points to remember :
1. ParentDiv is the container-2
2. ChildDiv is the child div inside ParentDiv(which is dynamically appended when we select 5 employees on "Add" button click"
Here is the code:
HTML :
<table id="topTable">
<tr>
<td id="leftpane">
<h4>Search for Employee by Name or Profile:</h4>
<input type="text" id="EmployeeSearchBox" class="search-box" aria-multiselectable="true" />
<select id="EmployeeList" size="20" multiple></select>
</td>
<td id="centerpane">
<div> <input type="button" value="Add >>" class="AddButton" id="buttonAdd" /></div>
<div> <input type="button" value="Add All >>" class="AddButton" id="buttonAddAll" /></div>
</td>
<td id="rightpane">
<h4>Selected Employees:</h4>
<div id="ParentDiv"></div>
</td>
</tr>
</table>
Run Report button event
<input class="data" type="submit" name="cmdSubmit" value="Run Report" onclick="return FormValidate();"
onserverclick="RunReport" runat="server" id="Submit1" />
Add Button Click :
which moves the employees from container-1 to container-2.
$(document).on('click', '#buttonAdd', function (e) {
$('#EmployeeList :selected').each(function (i, selected) {
myHash[$(selected).val()] = $(selected).text();
});
var myNode = $("#ParentDiv")[0];
while (myNode.firstChild) {
myNode.removeChild(myNode.firstChild);
}
for (var emp_id in myHash) {
var emp = $("#ParentDiv").append("<div class= ChildDiv id=" + emp_id + ">" + myHash[emp_id] + " <span class='close'>×</Span> </div>");
}
$('#EmployeeSearchBox').val("").trigger('input');
});
On click of "Report" button it should clear all the elements from ParentDiv/ChildDiv which is what I did, but still it is not clearing it, how can I resolve/remove these elements once "Report" button event clicked.
Here is a sample of "Report" button event :
function FormValidate() {//Part of my other code
$(".ChildDiv").html("");
$('.ChildDiv > div').remove();
$(".ChildDiv").html("");
$("#ParentDiv").html("");
$(".ChildDiv div").remove();
$(".ChildDiv div").empty();
$('.ChildDiv ').find('div').remove();
}
None of them is working, i feel there is an issue with the "Add" button event, where it is storing the data.
NOTE :
I don't want to clear the array of employee list, since I want to select multiple employees again again Ex. I can select 2 employees starts with the letter "M" and I can search the 2 employees of letter "L" and add those 2 employees, the container should hold 4 employees before "Report" button click.
Let me know if I am clear enough.
Console Log

Finally I could able to fix the issue, i was facing, I am posting the answer, now it is working as I need.
$(document).on('click', '#buttonAdd', function (e) {
var div_count = $('#ParentDiv').find('div').length;
if (div_count === 0) {
myHash = []; // Clearing the hash, so that it can add fresh employees, if count == 0 in container- 2.
$('#EmployeeList :selected').each(function (i, selected) {
myHash[$(selected).val()] = $(selected).text();
});
}
else { // If there are existing employees in container-2 then append few more.
$('#EmployeeList :selected').each(function (i, selected) {
myHash[$(selected).val()] = $(selected).text();
});
}
var myNode = $("#ParentDiv")[0];
console.log(myNode);
while (myNode.firstChild) {
myNode.removeChild(myNode.firstChild);
}
for (var emp_id in myHash) {
var emp = $("#ParentDiv").append("<div class= ChildDiv id=" + emp_id + ">" + myHash[emp_id] + " <span class='close'>×</Span> </div>");
}
$('#EmployeeSearchBox').val("").trigger('input');
});
What I did
Since I should be able to append multiple employees by searching, that is handled in 'else' part, if I generated the "Report" then, I am clearing the Container-2.
When I come back to page to search few more employees, by this time Container-2 will not be having any employees, so
var div_count = $('#ParentDiv').find('div').length;
if (div_count === 0) {
myHash = [];
//....
}
will clear the array which allow me to add fresh employees, hence it solved my problem :)
Thanks all for the support.

Edited to adjust on comments:
You need to clear the myHash variable. Otherwise employees will be added again from there.

Related

Setting values of dynamically added input fields changing all input fields

I have a form where users can create recipes. I start them off with one ingredient field (among others) and then use .append() to add as many more as they want to the div container that holds the first ingredient. The first input field has an id of IngredientName1 and dynamically added input fields are IngredientName2, IngredientName3, etc.
When they start typing in the input field, I pop a list of available ingredients filtered by the value they key into IngredientNameX. When they click on an ingredient in the list, it sets the value of the IngredientNameX field to the text from the div - like a search & click to complete thing. This all works very well; however, when you add IngredientName2 (or any beyond the one I started them with initially) clicking on an available ingredient sets the values of every single IngredientNameX field. No matter how many there are.
I hope this is enough context without being overly verbose, here's my code (I've removed a lot that is not relevant for the purpose of posting, hoping I didn't remove too much):
<div id="ingredientsContainer">
<input type="hidden" id="ingredientCounter" value="1">
<div class="ingredientsRowContainer">
<div class="ingredientsInputContainer"><input class="effect-1 ingredientsInput" type="text" name="IngredientName1" placeholder="Ingredient" id="IngredientName1" data-ingID="1"><span class="focus-border"></span></div>
</div>
<input type="hidden" name="Ingredient1ID" id="Ingredient1ID">
</div>
<script>
$(document).ready(function(){
$(document).on('keyup', "[id^=IngredientName]",function () {
var value = $(this).val().toLowerCase();
var searchValue = $(this).val();
var valueLength = value.length;
if(valueLength>1){
var theIngredient = $(this).attr("data-ingID");
$("#Ingredients").removeClass("hidden")
var $results = $('#Ingredients').children().filter(function() {
return $(this).text() === searchValue;
});
//user selected an ingredient from the list
$(".ingredientsValues").click(function(){
console.log("theIngredient: "+theIngredient);//LOGS THE CORRECT NUMBER
var selectedIngredientID = $(this).attr("id");
var selectedIngredientText = $(this).text();
$("#IngredientName"+String(theIngredient)).val(selectedIngredientText);//THIS IS WHAT SETS EVERYTHING WITH AN ID OF IngredientNameX
$("#Ingredient"+String(theIngredient)+"ID").val(selectedIngredientID);
$("#Ingredients").addClass("hidden");
});
$("#Ingredients *").filter(function() {
$(this).toggle($(this).text().toLowerCase().indexOf(value) > -1)
});
} else {
$("#Ingredients").addClass("hidden")
}
});
$("#AddIngredient").click(function(){
var ingredientCounter = $("#ingredientCounter").val();
ingredientCounter++;
$("#ingredientCounter").val(ingredientCounter);
$('#ingredientsContainer').append('\
<div class="ingredientsRowContainer">\
<div class="ingredientsInputContainer"><input class="effect-1 ingredientsInput" type="text" name="IngredientName'+ingredientCounter+'" placeholder="Ingredient" id="IngredientName'+ingredientCounter+'" data-ingID="'+ingredientCounter+'"><span class="focus-border"></span></div>\
</div>\
<input type="hidden" name="Ingredient'+ingredientCounter+'ID" id="Ingredient'+ingredientCounter+'ID">\
');
});
});
</script>
[UPDATE] I realized the problem is happening because the function is running multiple times. I assume this happening because I'm calling a function on keyup of a field whose id starts with IngredientName so when one has a key up event, all existing fields run the function. How do i modify my:
$(document).on('keyup', "[id^=IngredientName]",function () {
to only run on the field with focus?

Show Selected Items Before Removing from Database

I've been researching how to do this and I can't find any helpful links so I'm asking here.
I have table on my website with data from my database. Each item has a delete checkbox next to it. If the user checks these boxes then hits the delete button, they are prompted with a message asking them if they are sure they want to delete the items. If they say yes, then the items are removed. I'd like to show what they selected in the confirmation box.
Example: Let's say they selected item4, item8, and item9, then clicked on delete. I'd want the prompt to say:
"Are you sure you want to delete the selected items?
item4
item8
item9"
I'm not sure how to even start this. Here's my current delete button:
<input type="submit" value="Delete" onclick="return confirm('Are you sure you want to delete the selected item(s)?');"/>
You could use javascript for this, something like below will work (pseudo code);
<!-- Add the onclick handler -->
<input type="submit" onclick="submitOnClick();" value="Delete" />
// Javascript function
function submitOnClick() {
var ret = "";
var table = getTable();
for (int i = 0; i < table.length; i++) {
if (row.checked) {
ret += row.innerText + " ";
}
}
alert('Are you sure you want to delete the selected items of " + ret);
}
Depending how your HTML is setup/structured you may have to change things to get it working properly.
Hoped this helped.

Dynamically Update DIV information based on CHECKBOX input value

I am trying to have a list of input checkboxes (which will be generated by PHP at a later time) but for now the content is static. So based off of the input, be able to select an employee, populates my div based on the selection and when unchecking the input, remove that same employee. I also need to be able to select multiple employees, instead of just one. Currently it updates the div with an employee but I cannot remove said employee. I can also only select one employee at a time (need to be able to click as many employees as needed all at once).
Here is what I got:
HTML
<div id="employee-list">
</div>
<div class="small-2 columns bord-right3 check-box">
<input type="checkbox" class="boxid" value="Joe Smith" name="employees">
<label class="checkbox-select">Select</label>
</div>
<div class="small-10 columns bord-right3">
<span class="employee-name">Joe Smith</span>
</div>
<div class="small-2 columns bord-right3 check-box">
<input type="checkbox" class="boxid" value="John Smith" name="employees">
<label class="checkbox-select">Select</label>
</div>
<div class="small-10 columns bord-right3">
<span class="employee-name">John Smith</span>
</div>
JS
$('input[name="employees"]').change(function () {
var inputVal = $('input[name="employees"]:checked').map(function () {
return this.value;
}).get();
console.log(inputVal);
if ($(this).prop('checked')) { //which checkbox was checked
if ($(this).val() == inputVal ) {
$("#employee-list").append('<span class="employee-name2_1">X ' + inputVal + '</span>');
}
} else {
$('.li_'+$(this).val()).remove();
console.log('item removed');
}
});
Any help is greatly appreciated! Please let me know if I have missed anything.
If I understand the goal correctly some of your code inside the change listener was unnecessary. You don't have to use map to get the value of the checkbox, $(this).val() is sufficient. From there a single if/else can add or remove the information as necessary.
Fiddle
$('input[name="employees"]').change(function () {
var inputVal = $(this).val();
var className = inputVal.replace(/ /g, '_');
if ($(this).prop('checked')) { //which checkbox was checked
$("#employee-list").append('<span class="span_' + className + '">X ' + inputVal + '</span>');
} else {
$('.span_'+className).remove();
console.log('item removed');
}
});

Show/Hide JQuery?

I have a problem where I have to show/hide multiple labels inside of the same td tag. Here is my JQuery code:
$j( document ).ready(function() {
var records = [];
var userID = 'here I am passing user ID'
~[tlist_sql;
SELECT ID1, User_ID, ID2
From RESERVATIONS
]
records.push({'idOne':"~(ID1)",'idTwo':"~(User_ID)",'idThree':"~(ID2)"});
[/tlist_sql]
for(var i=0; i< records.length; i++){
//here I am looking for matchin userID in my records array
if(records[i].idTwo == userID){
//If match, I want to hide input field and display name.
$j('#hide_' + records[i].idOne).parent('.hideEmail').hide().next('.showName').show();
}
//Here I'm looking if any of my records idThree has value 0
if(records[i].idThree == '0'){
//if match hide input and show word 'Reserved'
$j('#hide_' + records[i].idOne).parent('.hideEmail').hide().next('.showResreved').show();
}
}
});
Here is my html code:
<td>
<span class="hideEmail">
<input type="text" value="" id="hide_~(ID1)"/>
</span>
<label class="showName" style="display:none">
<span class="firstLast">Display Name</span>
</label>
<label class="showReserved" style="display:none">
<span class="notavailable">Reserved</span>
</label>
</td>
So problem show up once I combined both labels. At the first point I had only label with the class 'showName' and my logic worked fine. But once I added one more if statement in my JQuery and added another label with class 'showReserved' my code still displayed name label and class 'hideEmail' was hidden but class 'showReserved' never was displayed. Can anyone tell me why this does not work? Should I not combine two labels or something is wrong in my jquery?
Here is my working example: https://jsfiddle.net/dmilos89/nephebbv/2/
The problem its in this part:
$j('#hide_' + records[i].idOne).parent('.hideEmail').hide().next('.showResreved').show();
You typed "showReserved" wrong.
Here's a simple fix:
$j('#hide_' + records[i].idOne).parent('.hideEmail').hide().next('.showReserved').show();

JQuery, Javascript button

Sorry for the vague title, couldn't think of how to title my question. So I've made a html/css table wherein I placed an edit button for each row. Pressing the button would transform a certain text field into a text-input field there by allowing the user to edit the data inside; at the same time the edit button then transforms to save button. After editing , the user then would press the save button and the text-input field would then revert back into a text field and the save button back to an edit button. But it's not entirely working
This is my problem, after editing the data inside, upon pressing the save button, the data inside is deleted and replaced with: <input type= and outside the text-input field is: " />
and the save button remains as is, a "SAVE" button and not back to an "EDIT" button
here's the script:
$(document).ready(function () {
// listen for email edit button click
$("button#edit").on('click', function () {
// get email inline to this edit button
var email = $(this).parent().siblings('td.email').html();
alert(email);
// change button from edit to save
$(this).attr('id', 'save-email').html('SAVE');
// change email display to input field
$(this).parent().siblings('td.email').html('<input type="text" id="user-email" value="' + email + '" />');
});
// listen for email save button click
$("button#save-email").on('click', function () {
// get new email inline to this save button
var newEmail = $(this).parents('tr').find($('input#user-email')).val();
alert(newEmail);
// change input field back to display
$(this).parent().siblings('td.email').html(email);
// change button from save to edit
$(this).attr('id', 'edit').html('EDIT');
});
});
sorry for the wall of text.
try to put it this way :
$(document).on('click',"button#save-email", function() {...
instead of
$("button#save-email").on('click', function()
using the second one won't work, because when it is run, $("button#save-email"), doesn't exist yet.
The problem is that the first handler is the only one attached in script.
Your javascript code is executed when the page is ready.
At that moment only the first handler is attached because there is not yet an element button#save-email. When you click save, it is the first handler that is executed again, not the one think !
Why don't you create two distinct buttons and show one or the other ?
<table>
<tr>
<td class="email">myemail#domain.com</td>
<td>
<button class="btn-edit">Edit</button>
<button class="btn-save" style="display:none">Save</button>
</td>
</tr>
<tr>
<td class="email">myemail#domain.com</td>
<td>
<button class="btn-edit">Edit</button>
<button class="btn-save" style="display:none">Save</button>
</td>
</tr>
</table>
Javascript
// listen for email edit button click
$('.btn-edit').on('click', function() {
var $this = $(this),
$parentRow = $this.closest('tr');
// get email inline to this edit button
var email = $this.parent().siblings('td.email').html();
// change button from edit to save
$parentRow.find('.btn-edit').hide();
$parentRow.find('.btn-save').show();
// change email display to input field
$(this)
.parent()
.siblings('td.email')
.html('<input type="text" id="user-email" value="'+email+'" />');
});
// listen for email save button click
$('.btn-save').on('click', function() {
var $this = $(this),
$parentRow = $this.closest('tr');
// get new email inline to this save button
var newEmail = $(this).parent().siblings('td.email').find('#user-email').val();
// change input field back to display
$(this).parent().siblings('td.email').html(newEmail);
// change button from save to edit
$parentRow.find('.btn-edit').show();
$parentRow.find('.btn-save').hide();
});
DEMO
Take a look at KnockoutJS, which utilizes nice Bindings helping you to do things like that much easier. Here is an example of an editable grid with KnockoutJS
KnockoutJS Editable Data example
Neat & Works
<table>
<tr>
<td>some text</td>
<td><input type='button' value='edit' id='btn'/></td>
</tr>
</table>
$(document).ready(function() {
$("#btn").click(function() {
var $btn=$(this);
var opn= $btn.val()
switch(opn){
case 'edit':
var $td=$(this).parent().parent().find('td:first');
var email=$td.html();
$td.html("").append('<input type="text" value="'+email+'">');
$btn.val("save");
break;
case 'save':
var $input=$(this).parent().parent().find('td:first input');
var email=$input.val();
$input.parent().html(email);
$btn.val("edit");
break;
}
});
});
http://jsfiddle.net/h55rc/

Categories