How to subtract a particular value from array using JavaScript - javascript

I am creating a program using JavaScript while a clicking of button it will select a seat and change its background color to green and at the same time the button value will be added to the text field and will toggle accordingly.
Issue: I am adding all the value to the text field using an array, which is successful but during toggling it cannot able to subtract the particular clicking button value from array.
Here I cannot able to use jQuery because this page is coming from a ajax-page load.
// JavaScript Document
var Cur_id;
var Cur_val;
function setId(id, value) {
Cur_id = id;
Cur_val = value;
var SeatVal = document.getElementById(id);
if (SeatVal.style.backgroundImage == "") {
SeatVal.style.backgroundImage = "url(\'themes/frontend/images/greenseat.png\')";
var txbtElementSeat = new Array(document.getElementById("selectedseat").value += Cur_val + ",");
} else if (SeatVal.style.backgroundImage == 'url("themes/frontend/images/greenseat.png")') {
SeatVal.style.backgroundImage = "url(\'themes/frontend/images/seat.png\')";
var txbtElementSeatnbg = document.getElementById("selectedseat").value;
removeSeat(txbtElementSeatnbg, Cur_val);
function removeSeat(txbtElementSeatnbg, value) {
for (var i = 0; i <= txbtElementSeatnbg.length; i++) {
if (txbtElementSeatnbg[i] == value) {
txbtElementSeatnbg.splice(i, 1);
break;
}
}
}
} else if (SeatVal.style.backgroundImage == 'url("themes/frontend/images/seat.png")') {
SeatVal.style.backgroundImage = "url(\'themes/frontend/images/greenseat.png\')";
var txbtElementseatnb = document.getElementById("selectedseat").value += Cur_val + ",";
}
}

Your main issue seems to be that you try to save an array into a textfield. That will actually work, but will convert the array to a string representation.
var a = document.getElementById('selectedseat').value; therefore loads the string representation of the array into a variable "a", not the array itself!
Why don't you use a variable in the outer context (not the local function scope of setId()!) to hold the array? Maybe somewhat like this:
// Create a variable for the array!
var selectedSeats = new Array();
// Build a function that will update the textfield.
// Call this, whenever the array gets changed!
function updateListOfSelectedSeats() {
document.getElementById('selectedseat').value = selectedSeats.join(',');
}
// Removes a seat from the list of selected seats
function removeSeatFromList(seat) {
for (var i = 0; i < selectedSeats.length; i++) {
if (selectedSeats[i] == seat) {
selectedSeats.splice(i, 1);
updateListOfSelectedSeats();
break;
}
}
}
// Now the function that reacts to clicks on a seat
function setId(id, value) {
var Seat = document.getElementById(id);
switch (Seat.style.backgroundImage) {
case 'url("themes/frontend/images/greenseat.png")':
// Seat is already selected and needs to be deselected
Seat.style.backgroundImage = 'url("themes/frontend/images/seat.png")';
removeSeatFromList(value);
break;
case '':
case 'url("themes/frontend/images/seat.png")':
// Seat is empty, select it!
Seat.style.backgroundImage = 'url("themes/frontend/images/greenseat.png")';
selectedSeats.push(value);
updateListOfSelectedSeats();
break;
}
}

To remove the seat from the list use this
//remove seat from list
function removeSeat(seatListElm, seatValue) {
var arr=seatListElm.value.split(',');
var p=arr.indexOf(seatValue);
if(p!=-1){
arr.splice(p, 1);
seatListElm.value=arr.join(',');
}
}
seatListElm would be the element that hold "b5,c7,d5,c2"
seatValue would be something like this "c7"
Working demo code: JSFIDDLE

Related

Find specific line in CSV based on 2 values with Javascript

I am trying to search, find and fetch some data from a CSV file using HTML/PHP/Javascript.
I want to make a form with 2 dropdowns, one for the FROM Zone name and one for the TO Zone name, and use the Zone codes (102, 104, 105 etc) as values for the dropdown items.
After the user have selected the FROM and TO i want to display the single digit to the far right (col 5).
Example: User choose "Zone1" to "Zone4", then the number "4" should be returned.
FromZoneCode;FromZoneName;ToZoneCode;ToZoneName;Distance;;;;
101;zone1;101;zone1;1;;;;
101;zone1;104;zone4;4;;;;
101;zone1;105;zone5;5;;;;
104;zone4;101;zone1;4;;;;
104;zone4;105;zone5;2;;;;
104;zone4;104;zone4;1;;;;
I have tried to search for a solution for this but i cant seem to find the right info.
Worked out after a long time:
Don't know how you got the CSV data. In the following example, I got it by an ajax request.
No jQuery needed.
Created the dropdowns dynamically.
Set the variable delimeter to ; (or) , as required, because most CSV files contains CSV delimeter.
Give the names of the columns for which dropdowns to be created in the variables dropdownname1 and dropdownname2.
Give the name of the column to be displayed as result on chaning dropdowns in the variable resultname.
Create a <span> element with id="result" in the HTML to display the result.
Variable keys contains column names.
Variable values contains array of arrays as values.
var data = [];
$.ajax({
url:"/Users/Default/Downloads/test.csv",
type:"GET",
datatype:"csv",
success:function(response){
data = response.split(/\r\n/);
start();
}
});
//Logic starts here
//Initializations
var keys = [], values = [], delimiter = ";";
var dropdownname1 = "FromZoneName", dropdownname2 = "ToZoneName", resultname = "Distance";
var resultelem = document.getElementById("result");
//Functionalities
function createDropdown(field)
{
function createOption(option, isselected)
{
var optionelem = document.createElement("option");
optionelem.value=option;
optionelem.text=option;
optionelem.selected = isselected;
return optionelem;
}
var selectelem = document.createElement("select");
selectelem.setAttribute("id",field);
var insertedoptions = [];
for(var i=0;i<values.length;i++)
{
var option = values[i][keys.indexOf(field)];
if(insertedoptions.indexOf(option) == -1)
{
insertedoptions.push(option);
selectelem.appendChild(createOption(option));
}
}
selectelem.appendChild(createOption("",true));
return selectelem;
}
function start()
{
keys = data.splice(0,1)[0].split(delimiter);
values = [];
for(var i=0,n=data.length;i<n;i++)
{
values.push(data[i].split(delimiter));
}
var bodyelem = document.getElementsByTagName("body")[0];
bodyelem.appendChild(createDropdown(dropdownname1));
bodyelem.appendChild(createDropdown(dropdownname2));
document.getElementById(dropdownname1).addEventListener("change",displayData);
document.getElementById(dropdownname2).addEventListener("change",displayData);
}
function displayData()
{
var selectelem1 = document.getElementById(dropdownname1), selectelem2 = document.getElementById(dropdownname2);
var selectedvalue1 = selectelem1.value, selectedvalue2 = selectelem2.value;
for(var i=0,n=values.length;i<n;i++)
{
if(values[i][keys.indexOf(dropdownname1)] == selectedvalue1 && values[i][keys.indexOf(dropdownname2)] == selectedvalue2)
{
resultelem.innerHTML=values[i][keys.indexOf(resultname)];
break;
}
else
{
resultelem.innerHTML="";
}
}
}

js search bar update on keypress lagging - and how to revert?

how can i make a search bar on my webpage that:
filters the items (list items/cards) on my page without pressing enter
with the current search bar value and updates automatically as user types
then revert the changes back also when the user deletes letters - (ex: display:none -> display:block)
in plain js
also the current search lags 1 key behind
this is where i am trying to implement it
http://codepen.io/lycjee/pen/dNjBPE
and this is the corrseponding code for the search bar
searchbar.addEventListener('keypress', function(e) {
//filter with keypress - without enter
//filter function - on "chan" array
var filterItems = function(query) {
return chan.filter(function(el) {
return el.toLowerCase().indexOf(query.toLowerCase()) <= -1;
});
};
//searchquery
var searchQuery = document.getElementById('searchbar').value;
//declare a var for array of items to be filtered
var filtered = filterItems(searchQuery);
console.log(searchQuery);
console.log(filtered);
console.log(chan);
//if searchbar is blank and there is a keypress after it
//shows all elements according to the original chan array
//else disables elements according to filtered array
if (searchQuery === "") {
for (let i = 0; i < chan.length; i++) {
document.getElementById(chan[i]).style.display = "block";
}
}
else {
for (let i = 0; i < filtered.length; i++) {
document.getElementById(filtered[i]).style.display = "none";
}
}
filtered = chan;
}

Get table rows and cells with jQuery

I'm working on a web game and need to check for which cells on the table have been selected by the user. Right now I'm just checking for the row and cell index value:
JavaScript
function checkForWin() {
var card = document.getElementById('card');
if ((card.rows[0].cells[0].marker && // 1st row
card.rows[0].cells[1].marker &&
card.rows[0].cells[2].marker &&
card.rows[0].cells[3].marker &&
card.rows[0].cells[4].marker)) {
youWin();
} else {
noWin();
}
}
Is there a more elegant of doing this with jQuery?
Just make some loop :
function checkForWin() {
var card = document.getElementById('card');
var win = true;
for (var i = 0; i < card.rows[0].cells.length; i++){
if(!card.rows[0].cells[i])
win = false;
}
if(win)
youWin();
else
noWin();
}
Using jQuery you could iterate over the list of marked cells or just get the list of marked cells like this:
var marked = $('#cards td.marked');
// If you have a special way to detect a cell is marked that
// needs more custom test than checking the class you can use .filter.
// Just as example I use the same condition.
//var marked = $('#cards td').filter(function () {
// return $(this).hasClass('marked');
//});
// If you want to just iterate the selected cells.
marked.each(function () {
var i = $(this).closest('tr').index();
var j = $(this).index();
console.log(i, j);
});
// If you want to the the array of selected cells.
var indexes = marked.map(function () {
return {
i: $(this).closest('tr').index(),
j: $(this).index()
};
}).get();
To make it easier I assumed that a cell with the marked class means a marked cell. However you can use the condition you want to get the list of marked cells.
See small demo

Modify code for javascript from php

I am using a series of check boxes all are with different name that is checkbox1....checkbox40. I am generating a series of sting with '1' and '0' that is if check box is checked than sting will be concatenated with '1' else it will be concatenated with '0'. I have successfully implemented idea for PHP but as now I am using Ajax I want to develop same code for java script. My PHP code for that is
if (isset($_POST[submit]))
{
for ($i=1; $i<41; $i++)
{
$walue = "restriction".$i;
if(isset($_POST[$walue])) {$val .="1";} else {$val .="0";}
}
}
echo "Equivalent String: ".$val."<p>";
for implementing it using Javascript I have called a function on submit event of form.
My form id is theForm and my checkboxes name is restriction1....restriction40. Please give me hint to implement the idea.
So.. something like this?
getCheckedString = function () {
var chunks = [];
var checkboxes = $("#theForm").children('input[type=checkbox]').each(function () {
chunks[chunks.length] = $(this).is(':checked') ? '1' : '0';
});
return chunks.join('');
}
This will gather up all of the checkboxes in the order they are on the form, put a '1' or '0' in the array, then return the array joined into a string. It's not specific to a particular name, so if there are other checkboxes in the form let me know and I'll alter my answer.
If you have only named checkboxes, you would do:
function getCheckedString1() {
var val = "";
for (var i = 1; i <= 40; ++i) {
var boxes = document.getElementsByName("restriction" + i); // returns an array
if (boxes[0]) {
val += boxes[0].checked ? "1" : "0";
}
}
// alert(val);
return val;
}
However, it is easier and the usual praxis to identify the referenced HTML elements with ID's. So, you would enhance your HTML:
<input type="checkbox" name="restriction1" id="restriction1" ...
<input type="checkbox" name="restriction2" id="restriction2" ...
and then use:
function getCheckedString2() {
var val = "";
for (var i = 1; i <= 40; ++i) {
var box = document.getElementById("restriction" + i); // returns the unique element
if (box) {
val += box.checked ? "1" : "0";
}
}
// alert(val);
return val;
}

How can I restore the order of an (incomplete) select list to its original order?

I have two Select lists, between which you can move selected options. You can also move options up and down in the right list.
When I move options back over to the left list, I would like them to retain their original position in the list order, even if the list is missing some original options. This is solely for the purpose of making the list more convenient for the user.
I am currently defining an array with the original Select list onload.
What would be the best way to implement this?
You can store the original order in an array, and when inserting back, determine what's the latest element in the array that precedes the one to be inserted AND matches what's currently in the select list. Then insert after that.
A better solution is to just store the old array whole and re-populate on every insertion with desired elements as follows (warning: code not tested)
function init(selectId) {
var s = document.getElementById(selectId);
select_defaults[selectId] = [];
select_on[selectId] = [];
for (var i = 0; i < s.options.length; i++) {
select_defaults[selectId][i] = s.options[i];
select_on[selectId][i] = 1;
var value = list.options[i].value;
select_map_values[selectId][value] = i if you wish to add/remove by value.
var id = list.options[i].id; // if ID is defined for all options
select_map_ids[selectId][id] = i if you wish to add/remove by id.
}
}
function switch(selectId, num, id, value, to_add) { // You can pass number, value or id
if (num == null) {
if (id != null) {
num = select_map_ids[selectId][id]; // check if empty?
} else {
num = select_map_values[selectId][value]; // check if empty?
}
}
var old = select_on[selectId][num];
var newOption = (to_add) : 1 : 0;
if (old != newOption) {
select_on[selectId][num] = newOption;
redraw(selectId);
}
}
function add(selectId, num, id, value) {
switch(selectId, num, id, value, 1);
}
function remove(selectId, num, id, value) {
switch(selectId, num, id, value, 0);
}
function redraw(selectId) {
var s = document.getElementById(selectId);
s.options.length = 0; // empty out
for (var i = 0; i < select_on[selectId].length; i++) {
// can use global "initial_length" stored in init() instead of select_on[selectId].length
if (select_on[selectId][i] == 1) {
s.options.push(select_defaults[selectId][i]);
}
}
}
I would assign ascending values to the items so that you can insert an item back in the right place. The assigned value stays with the item no matter which list it's in.

Categories

Resources