Storing Key and Value using Javascript in array - javascript

I have a jsp page on which table is coming dynamically and have checkboxes on that page when you click on that box it should save in array and when it uncheck the box it should remove value from array.
I have tried this by creating a method but it is not working perfectly can you please help me..
function addCheckboxVAlues(checked){
var split = checked.value.split("|");
var key =split[0];
var value=split[1];
var chks = $("input[name='"+key+"']:checked");
if (chks.length > 0) {
uninvoiced.push(value);
} else {
uninvoiced.pop(key);
}
console.log(uninvoiced);
}

You need to use splice to remove the element from the array
function addCheckboxVAlues(checked){
var split = checked.value.split("|");
var key =split[0];
var value=split[1];
var chks = $("input[name='"+key+"']:checked");
var index = uninvoiced.indexOf(key);
if (chks.length > 0) {
uninvoiced.push(value);
} else if(index > -1){
uninvoiced.splice(index, 1);
}
console.log(uninvoiced);
}

This code looks way more complex than it needs to be. Presumably the checkbox has a click listener on it, so it should be called with the checkbox as this. All you have to do is add the value if the checkbox is checked, or remove it if it's unchecked.
That will be hugely more efficient than running a checked selector every time.
The following uses an inline listener for convenience, likey you're attaching them dynamically but it seems to be called the same way.
var uninvoiced = [];
function addCheckbox(el) {
var value = el.value.split('|')[1];
if (el.checked) {
uninvoiced.push(value);
} else {
uninvoiced.splice(uninvoiced.indexOf(value), 1);
}
console.log(uninvoiced);
}
foo|bar: <input type="checkbox" value="foo|bar" onclick="addCheckbox(this)">
fee|fum: <input type="checkbox" value="fee|fum" onclick="addCheckbox(this)">
There is a polyfill for indexOf on MDN.

Related

Outputting an object to a page that keeps close function

I posted this question before, among others. But it was suggested I need to ask a more specific or focused question.
I am working on an output history log on a single page. And I want to make it so each output it's self is contained in box object that can be closed or deleted individually. Like this.
Now I have managed to get everything working to the point where it will nicely output to a box with a close button. However the close button it's self will not function in this case.
So, I am trying to output it like this...
HTML:
<p>History log:</p><br><div style="white-space:pre-wrap"><ul
id="outputListItem" class="boxcontainer"></ul></div>
SCRIPT:
document.getElementById("Add").onclick = function(e) {
convertOutput();
}
function convertOutput(){
//this is the part I have been trying to get working
convertOutput.addEventListener('close', function() {
this.parentElement.style.display = 'none';
}
});
var output = document.getElementById("output").value;
var li = document.createElement('li');
li.className = "containedboxes";
var dateTime = todayDateTime();
li.innerHTML = "<time id='time'>" + dateTime +"</time><br /> <br />"+ output
+"<br /><br /><span class='close'>×</span>";
document.getElementById('outputListItem').prepend(li);
}
And the script to close the box:
var closebtns = document.getElementsByClassName("close");
var i;
for (i = 0; i < closebtns.length; i++) {
closebtns[i].addEventListener("click", function() {
this.parentElement.style.display = 'none';
});
}
It was suggested to me on the last question I posed I should use convertOutput() right after addEventListener() loop immediately after it. If this is how you do it, i am still quite new to JavaScript, so not sore how to properly do this. I created a fiddle for this also, but for some reason I can't get the script to run properly in the fiddle, But all the code is there to see.
I am looking to solve this using vanilla JavaScript.
I created an example for you. Hopefully this helps you get going :) A couple things to note, I use a data attribute to store the index for the item in the array, so you can delete it when you click on the list item.
document.addEventListener('DOMContentLoaded', function(){
let nameEl = document.querySelector("#name");
let submitEl = document.querySelector("#submit-name");
let historyEl = document.querySelector(".history-list");
let historyList = [
{ name: 'Mitch'},
{ name: 'Max'},
{ name: 'Mike'},
];
function addToList(arr) {
// Clear up list and then update it
while(historyEl.firstChild) {
historyEl.removeChild(historyEl.firstChild);
}
// Update the list with the historyList
for(let item in historyList) {
let name = historyList[item].name;
let listContent = document.createElement("li");
listContent.textContent = name;
// We will use the index to remove items from the list
listContent.setAttribute('data-value', item);
listContent.addEventListener("click", removeFromList)
historyEl.appendChild(listContent);
}
}
function removeFromList(index) {
// Takes the index of the object, and will later remove it
console.log("Removed Item " + this.dataset.value);
historyList.splice(index, 1);
addToList(historyList);
}
addToList(historyList);
submitEl.addEventListener("click", function(event) {
if(nameEl.value) {
// Add the name to the start of the history list array.
historyList.unshift({ name: nameEl.value})
nameEl.value = '';
// Update the dom with the new array
addToList(historyList);
}
});
});
<label for="name">Type Name</label>
<input type="text" name="name" id="name">
<button id="submit-name">Submit Name</button>
<ul class="history-list"></ul>
Hopefully this gives you a good idea on how to get the task done and let me know if you have any questions :)
Your boxes don't respond to the click event simply because your script crashes before the events even get attached to it.
The following block right at the beginning:
document.getElementById("Add").onclick = function(e) {
convertOutput();
}
tries to add a click listener to the HTML element Add which does not exist. If you either remove the code block or add the appropriate element your boxes will have it's click functionality.

Recursive IDs and duplicating form elements

I have the following fiddle:
http://jsfiddle.net/XpAk5/63/
The IDs increment appropriately. For the first instance. The issue is when I try to add a sport, while it duplicates, it doesn't duplicate correctly. The buttons to add are not creating themselves correctly. For instance, if I choose a sport, then fill in a position, and add another position, that's all fine (for the first instance). But when I click to add another sport, it shows 2 positions right away, and the buttons aren't duplicating correctly. I think the error is in my HTML, but not sure. Here is the JS I am using to duplicate the sport:
$('#addSport').click(function(){
//increment the value of our counter
$('#kpSport').val(Number($('#kpSport').val()) + 1);
//clone the first .item element
var newItem = $('div.kpSports').first().clone();
//recursively set our id, name, and for attributes properly
childRecursive(newItem,
// Remember, the recursive function expects to be able to pass in
// one parameter, the element.
function(e){
setCloneAttr(e, $('#kpSport').val());
});
// Clear the values recursively
childRecursive(newItem,
function(e){
clearCloneValues(e);
});
Hoping someone has an idea, perhaps I've just got my HTML elements in the wrong order? Thank you for your help! I'm hoping the fiddle is more helpful than just pasting a bunch of code here in the message.
The problem is in your clearCloneValues function. It doesn't differentiate between buttons and other for elements that you do want to clear.
Change it to:
// Sets an element's value to ''
function clearCloneValues(element){
if (element.attr('value') !== undefined && element.attr('type') !== 'button'){
element.val('');
}
}
As #PHPglue pointed out in the comments above, when new positions are added, they are incorrectly replicated (I'm assuming here) to the newly cloned for
There is a similar problem with the add years functionality.
A quick fix would be to initialize a variable with a clone of the original form fields:
var $template = $('div.kpSports').first().clone();
Then change your addSport handler to:
$('#addSport').click(function () {
//increment the value of our counter
$('#kpSport').val(Number($('#kpSport').val()) + 1);
//clone the first .item element
var newItem = $template.clone();
…
});
However, there are no event bindings for the new buttons, so that functionality is still missing for any new set of form elements.
Demo fiddle
Using even a simple, naive string based templates the code can be simplified greatly. Linked is an untested fiddle that shows how it might be done using this approach.
Demo fiddle
The code was simplified to the following:
function getClone(idx) {
var $retVal = $(templates.sport.replace(/\{\{1\}\}/g, idx));
$retVal.find('.jsPositions').append(getItemClone(idx, 0));
$retVal.find('.advtrain').append(getTrainingClone(idx, 0));
return $retVal;
}
function getItemClone(setIdx, itemIdx) {
var retVal = itemTemplate.replace(/\{\{1\}\}/g, setIdx).replace(/\{\{2\}\}/g, itemIdx);
return $(retVal);
}
function getTrainingClone(setIdx, trainingIdx) {
var retVal = trainingTemplate.replace(/\{\{1\}\}/g, setIdx).replace(/\{\{2\}\}/g, trainingIdx);
return $(retVal);
}
$('#kpSportPlayed').on('click', '.jsAddPosition', function() {
var $container = $(this).closest('.kpSports');
var containerIdx = $container.attr('data_idx');
var itemIdx = $container.find('.item').length;
$container.find('.jsPositions').append(getItemClone(containerIdx, itemIdx));
});
$('#kpSportPlayed').on('click', '.jsAddTraining', function() {
var $container = $(this).closest('.kpSports');
var containerIdx = $container.attr('data_idx');
var trainIdx = $container.find('.advtrain > div').length;
$container.find('.advtrain').append(getTrainingClone(containerIdx, trainIdx));
});
$('#addSport').click(function () {
var idx = $('.kpSports').length;
var newItem = getClone(idx);
newItem.appendTo($('#kpSportPlayed'));
});

JQuery DataTables How to get selected rows from table when we using paging?

For example I selected (checked) 2 rows from second page than go to first page and select 3 rows. I want get information from 5 selected rows when I stay at first page.
$('tr.row_selected') - not working
Thanks.
Upd.
I created handler somthing like this:
$('#example').find('tr td.sel-checkbox').live("click", function () {
/*code here*/
});
But right now when click event is hadle the row from table is hidding. I think it may be sorting or grouping operation of DataTables. Any idea what I must do with this?
When a checkbox gets selected, store the row information you want in a global object as a Key-Value pair
I don't remember specifically how i did it before but the syntax was something like
$('input[type=checkbox]').click(function()
{
var row = $(this).parent(); //this or something like it, you want the TR element, it's just a matter of how far up you need to go
var columns = row.children(); //these are the td elements
var id = columns[0].val(); //since these are TDs, you may need to go down another element to get to the actual value
if (!this.checked) //becomes checked (not sure may be the other way around, don't remember when this event will get fired)
{
var val1 = columns[1].val();
var val2 = columns[2].val();
myCheckValues[id] =[val1,val2]; //Add the data to your global object which should be declared on document ready
}
else delete myCheckValues[id];
});
When you submit, get the selected rows from your object:
for (var i = 0; i < myCheckValues.length; i++)
...
Sorry, haven't done JS in a long time so code as is might not work but you get the idea.
$('#example').find('tr td.sel-checkbox').live("click", function () {
var data = oTable.fnGetData(this);
// get key and data value from data object
var isSelected = $(this).hasClass('row_selected');
if(isSelected) {
myCheckValues[key] = value;
checkedCount++;
} else {
delete myCheckValues[key];
checkedCount--;
}
});
.....
On submit
if(checkedCount > 0) {
for(var ArrVal in myCheckValues) {
var values = myCheckValues[ArrVal]; // manipulate with checked rows values data
}
}

How to remove duplicated content/value with jQuery

So, i have span element where i appending some content - sometimes this content is duplicated. How to remove this one value which is duplicate of another ...
This is how looks like my output html:
<span class="some_class">
"value01"
"value01"
"value02"
"value03"
"value03"
</span>
I can't add any function because i have no idea how to do this, can u help me?
If these values are being added by JS code, then You can make sth like this:
http://jsfiddle.net/Sahadar/Nzs52/5/
You just have to make object which will store all strings placed inside this span, then just before insertion check if this inserted string is already in store object.
function(event) {
var textareaValue = textarea.value();
if(insertedTexts[textareaValue]) {
event.preventDefault();
textarea.value('');
} else {
insertedTexts[textareaValue] = true;
someSpan.append("\""+textareaValue+"\"");
}
}
If these values are already inside span, use function as follows:
var someSpan = $('.some_class');
var insertedTexts = [];
var result = someSpan.text().match(/"\w+(?=\")/gm);
result = result.map(function(value) {
return value.substring(1,value.length);
});
result.forEach(function(value) {
if(insertedTexts.indexOf(value) === -1) {
insertedTexts.push(value);
}
});
var newSpanText = "\""+insertedTexts.join('""')+"\"";
someSpan.text(newSpanText);
console.info(result, insertedTexts);
It's rebuilding span text (trimming etc.) but main functinality is preserved.
jsFiddle working copy:
http://jsfiddle.net/Sahadar/kKNXG/6/
Create an array variable
var vals = [];
which keeps track of the items. Then, in your function that appends items to the span check:
if (vals.indexOf("Mynewvalue") > -1) {
// Add to the span...
}

Sum a list of text boxes in jQuery

I have a form in which there are textbox(s) added dynamically using jquery.
The textbox ids is formed as an array, i.e. Quantity[0], Quantity[1], Quantity[2] ...
I want to add the numbers in these textbox(s) and display the value in another textbox named "total_quantity" preferably when the focus is shifted out of the array textbox.
How can I do it? I dont mind using jQuery or plain javascript, which ever is easier.
I would suggest giving a common class to your quantity fields such that:
<input type="text" class="quantity" onblur="calculateTotal();" />
Then you would be able to define the following function with jQuery:
function calculateTotal() {
var total = 0;
$(".quantity").each(function() {
if (!isNaN(this.value) && this.value.length != 0) {
total += parseFloat(this.value);
}
});
$("#total_quantity").val(total);
}
The onblur event will fire each time the focus is shifted from the quantity fields. In turn, this will call the calculateTotal() function.
If you prefer not to add a common class, you can use the $("input[id^='Quantity[']") selector, as Felix suggest in the comment below. This will match all the text boxes that have an id starting with: Quantity[
var Total = 0;
$("input[id^='Quantity[']").each(function() { Total += $(this).val()|0; });
$("#total_quantity").val(Total);
Use the following function, if one can't use document.getElementsByName(), as some MVC frameworks such as Struts and Spring MVC use the name attribute of a text to bind the element to a backend object.
function getInputTypesWithId(idValue) {
var inputs = document.getElementsByTagName("input");
var resultArray = new Array();
for ( var i = 0; i < inputs.length; i++) {
if(inputs[i].getAttribute("id") == idValue) {
resultArray.push(inputs[i]);
}
}
return resultArray;
}

Categories

Resources