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');
}
});
Related
The mandatory div id gets different numbers of inputs field displayed in it dynamically. Each input field starting from the first gets an id attr1, then attr2,..attr[n]. I need a way to get this into an array that gets the value of each input field with keyup and puts them into a separate input field with id detail.
This code works but returns undefined in some case when the hard coded input field ids exceed the generated input field ids. Thanks.
<div id="attributes"> <!--Start of Div Refreshed on Ajax Page Refresh-->
<div id="mandatory">
</div>
</div>
var total = '#attr1, #attr2';
$("#attributes").on('keyup', total, function(){
update();
})
function update() {
$("#detail").val($('#attr1').val() + "," $('#attr2').val());
}
If I understood right your question I think you're looking for something like that:
var fields = $("#mandatory").find("input"),
ids = [];
fields.each(function(){
$(this).on("keyup", function(){
var val = "";
ids = [];
fields.each(function(){
val += $(this).val() + (fields.length === ($(this).index() + 1) ? "": ", ");
ids.push($(this).get(0).id);
});
$("#detail").val(val);
console.log(ids)
});
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="attributes">
<div id="mandatory">
<input id="one" class="one" value="54"/>
<input id="two" class="two" value="55"/>
<input id="three" class="three" value="587"/>
</div>
</div>
<input id="detail" type="text" />
I'm not sure if this is what you're looking for, but I think it'll take you down the right path. In this example, any time a text input field is generated, an input event handler is attached to it that changes the value of a main textarea. If this isn't quite what you're looking for, please let me know and I'll be happy to try to work it out more.
document.getElementById('adder').onclick = function() {
var dynamicTextbox = document.createElement('input');
dynamicTextbox.setAttribute('type', 'text');
dynamicTextbox.setAttribute('class', 'dynamicText');
dynamicTextbox.addEventListener("input", function() {
var allTextboxes = document.getElementsByClassName('dynamicText');
var allValues = '';
for (var i=0; i < allTextboxes.length; i++) {
allValues += allTextboxes[i].value;
}
document.getElementById('detail').value = allValues;
});
document.getElementById('textboxes').appendChild(dynamicTextbox);
}
<textarea id="detail"></textarea>
<input id="adder" type="button" value="Add Text Field" />
<div id="textboxes"></div>
I'm currently trying to build a post filter section into a website and need some help with the JavaScript/jQuery that goes along with it. Below you can see an example of the layout visually and the html layout.
The sequence of events will go as follows:
User selects from the top list of filters (bottom tags are not visible until selected)
Once selected the "selected tag filter disappears from the top list and is added to the bottom ("circular tags")".
the user can also delete the tags and they will return to the top list of filters.
The way I imagined this working:
Selecting a filter
check for "checked checkbox"
add selected "checkbox" label + value attribute to an array
get the last values added to the array and create new filter tag underneath under content tag container
Removing a Filter
user clicks the small x on the tag they wish to remove
the tag is removed added back to the top list of filters and removed from the array
<div class="blog-feed-filters">
<h5>FILTER</h5>
<div class="checkbox">
<input class="checkbox-active" id="check1" type="checkbox" name="filter" value="1">
<label for="check1">Turas Application Updates</label>
<br>
<input class="checkbox-active" id="check2" type="checkbox" name="filter" value="2">
<label for="check2">General News</label>
<br>
<input class="checkbox-active" id="check3" type="checkbox" name="filter" value="3">
<label for="check3">Organisation Updates</label>
<br>
<input class="checkbox-active" id="check4" type="checkbox" name="filter" value="4">
<label for="check4">UI Updates</label>
</div>
<hr />
<div id="content-tag-container">
<div class="content-tag">Update ✕</div>
<div class="content-tag">Mobile Applications ✕</div>
<div class="content-tag">New website update ✕</div>
<div class="content-tag">Update ✕</div>
</div>
</div>
JavaScript/ Jquery Please excuse the mess. I'm a noob:D
$('.checkbox-active').click(function () {
//check to see if the checkbox has been "checked"
if (document.getElementById('check1').checked) {
var filtersSelected = [];
//get the item that has been checked and add it to an array
$.each($("input[name='filter']:checked"), function () {
filtersSelected.push($(this).val() + $("label[for='checkbox-active']").innerText);
});
//find the last item in the array
if (!Array.prototype.last) {
Array.prototype.last = function () {
return this[this.length - 1];
};
};
//create a new filter tag and add it to the content-tag-container div
for (var c in filtersSelected.last()) {
var newElement = document.createElement('div');
newElement.className = "content-tag";
newElement.innerHTML = "<a href=''>" + "✕" + "</a>";
document.getElementById("content-tag-container").appendChild(newElement);
};
}
});
Any help is appreciated. Cheers
I made some changes in your javascript :
$(document).ready( function() {
$('.checkbox-active').click(
function() {
//console.log("Hi");
//check to see if the checkbox has been "checked"
var filtersSelected = [];
//console.log($("input[name='filter']:checked"));
//get the item that has been checked and add it to an array
var pushed=false;
$.each($("input[name='filter']:checked"), function() {
//console.log( );
filtersSelected.push($(this).val() + $("label[for='"+$(this).attr('id')+"']").text());
$("label[for='"+$(this).attr('id')+"']").remove();
$(this).remove();
pushed=true;
});
console.log(filtersSelected);
//find the last item in the array
if (!Array.prototype.last) {
Array.prototype.last = function() {
return this[this.length - 1];
};
}
;
//create a new filter tag and add it to the content-tag-container div
if(pushed){
var c = filtersSelected.last();
var newElement = document.createElement('div');
newElement.className = "content-tag";
newElement.innerHTML = c + "<a href=''>" + "X" + "</a>";
document.getElementById("content-tag-container")
.appendChild(newElement);
}
});
});
Above code is partially running to add checked values in filtered list.
Replace your javascript with above code.
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.
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();
Hi all I am struggling to achieve my my goal and I really need some help.
I have a list of single check boxes that I need to be able to get the values and be able to put them in to a list
So for example 3 check boxes on the screen there could be more, the user clicks on one one or all of the them, and I want to be able to output the following:
<ul>
<li>Checkbox1 Value</li>
<li>Checkbox2 Value</li>
<li>Checkbox13Value</li>
</ul>
I also need to be able to save the selected values to a hiiden field as well like this if possible:
Checkbox1 Value | Checkbox2 Value | Checkbox3 Value
There will be 2 sections on the page with where I will need this functionality so I assume I will be looking into the div tags that contain the check boxes.
I have found some code but I get it to do what I need
function updateTextArea() {
var allVals = [];
$('#c_b :checked').each(function() {
allVals.push($(this).val());
});
$('#EXCUR').val(allVals)
$('#t').val(allVals)
}
$(function() {
$('#c_b input').click(updateTextArea);
updateTextArea();
});
My HTML will be like this:
<div id="c_b">
<div>
<input type="checkbox" value="one_name">
<input type="checkbox" value="one_name1">
<input type="checkbox" value="one_name2">
</div>
</div>
<div id="c_G">
<div>
<input type="checkbox" value="one_name" checked>
<input type="checkbox" value="one_name1">
<input type="checkbox" value="one_name2">
</div>
</div>
<textarea id="t"></textarea> <!-- UL LIST SHOULD GO HERE -->
<input type="hidden" id="EXCUR" />
<div id="OP"></div>
Any help with this would be great, I just cant get it to work
Many thanks in advance
Jason
Here is a fiddle of what I think you're looking for but if you answer my comment above I'll be able to help you further.
You can use jQuery's map() to extract the values you want into an array and then join the items in the array however you want.
Something like this:
function updateTextArea() {
var items = $.map($('#c_b :checked'),function(el, ix) {
return 'Checkbox' + (ix+1) + ' ' + $(el).val();
});
if(items.length > 0) {
$('#t').val('<ul><li>' + items.join('</li><li>') + '</li></ul>');
$('#EXCUR').val(items.join(' | '))
} else {
$('#t').val('');
$('#EXCUR').val('');
}
}
$(function() {
$('#c_b input').click(updateTextArea);
updateTextArea();
});
Fiddle to demonstrate
function updateTextArea(){
var vals = []
var str="<ul>";
//iterate over checked boxes
$("input:checked").each(function(){
var v = $(this).val()
vals.push(v)
str += "<li>" + v + "</li>"
})
str+="</ul>"
$("#EXCUR").val(vals.join("|"));
$("#t").val(str);
}
$(function(){
//bind click to all checkboxes in the page
$(":checkbox").click(updateTextArea);
})