Javascript: Add new attribute to a variable - javascript

HTML
<div id = "btnsdhd" class="btn-group">
<button type="button" id="31" value="SD" class="btn btn-default">SD</button>
<button type="button" id="32" value="HD" class="btn btn-default">HD</button>
</div>
JS
var btnsdhdDiv = $('#btnsdhd');
var getsdhd = function () {
// Get all sdhd's from buttons with .active class
var sdhd = $('button.active', btnsdhdDiv).map(function () {
return $(this).val();
}).get();
// If no sdhd's found, get sdhd's from any button.
if (!sdhd || sdhd.length <= 0) {
sdhd = $('button', btnsdhdDiv).map(function () {
return $(this).val();
}).get();
}
return sdhd;
};
The above code captures the values of the buttons and places it in the variable getsdhd
If none of the buttons are selected by default it captures both the values (SD,HD) I want to modify the if statement and add a third value NC to the variable when to no buttons are selected
I want it to look like (SD,HD,NC) when no buttons are slected.
I tried to use the .push() method but that didnt work.
Any leads would be helpful.

push() can not be chained in your case since push returns the new length, not the updated array. You need to add it below the get().
var btnsdhdDiv = $('#btnsdhd');
var getsdhd = function () {
// Get all sdhd's from buttons with .active class
var sdhd = $('button.active', btnsdhdDiv).map(function () {
return $(this).val();
}).get();
// If no sdhd's found, get sdhd's from any button.
if (!sdhd || sdhd.length <= 0) {
sdhd = $('button', btnsdhdDiv).map(function () {
return $(this).val();
}).get()
sdhd.push("NC");
}
return sdhd;
};
console.log(getsdhd());
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id = "btnsdhd" class="btn-group">
<button type="button" id="31" value="SD" class="btn btn-default">SD</button>
<button type="button" id="32" value="HD" class="btn btn-default">HD</button>
</div>

You are not invoking the getsdhs function. If you invoke your function it will work. I used console.log to test if it works.
JS
var btnsdhdDiv = $('#btnsdhd');
var getsdhd = function () {
// Get all sdhd's from buttons with .active class
var sdhd = $('button.active', btnsdhdDiv).map(function () {
return $(this).val();
}).get();
// If no sdhd's found, get sdhd's from any button.
if (!sdhd || sdhd.length <= 0) {
sdhd = $('button', btnsdhdDiv).map(function () {
return $(this).val();
}).get();
sdhd.push("NC");
}
console.log(sdhd);
return sdhd;
}();
Fiddle: https://jsfiddle.net/ABr/p23cb5dk/1/

Related

JS/jQuery dynamically create arrays for each BUTTON GROUP then store BUTTON DATA VALUE accordingly on click

I have 2 button groups with multiple buttons each. I can add/remove buttons' data-value to/from a global array, but I need one array for each button grup. Cannot do that, I always end up with only 1 array.
$(document).ready(function() {
// create array (need 2 arrays, actually)
var dataValueArr = [];
// on button click
$(".button-group button").click(function() {
var dataValue = $(this).data("value");
if ($(this).hasClass("selected")) {
$(this).removeClass("selected");
// remove value from array
var filteredValues = dataValueArr.filter(function(e) {
return e !== dataValue;
});
dataValueArr = filteredValues;
} else {
$(this).addClass("selected");
// add value to array
dataValueArr.push(dataValue);
}
console.log(dataValueArr);
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="button-group">
<button data-value="1">1</button>
<button data-value="2">2</button>
</div>
<div class="button-group">
<button class="selected" data-value="A">A</button>
<button data-value="B">B</button>
<button data-value="C">C</button>
</div>
One way to do it is by create the array using window[Arrayname] = [], in the example below we get the index of the buttongroup and use that combines with a string to create the name for the array.
so if you add another button group you don't have to change the jquery.
Demo
$(document).ready(function() {
// on button click
$(".button-group button").click(function() {
var btninx = $(this).closest(".button-group").index();
if (!window["dataValueArr" + btninx]) window["dataValueArr" + btninx] = [];
var dataValue = $(this).data("value");
if ($(this).hasClass("selected")) {
$(this).removeClass("selected");
// remove value from array
var filteredValues = window["dataValueArr" + btninx].filter(function(e) {
return e !== dataValue;
});
window["dataValueArr" + btninx] = filteredValues;
} else {
$(this).addClass("selected");
// add value to array
window["dataValueArr" + btninx].push(dataValue);
}
console.log(window["dataValueArr" + btninx]);
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="button-group">
<button data-value="1">1</button>
<button data-value="2">2</button>
</div>
<div class="button-group">
<button class="selected" data-value="A">A</button>
<button data-value="B">B</button>
<button data-value="C">C</button>
</div>

Trying to save all generated 'li' elements to local storage using JavaScript

This code successfully takes the contents of the form and saves it to an ordered list, 2 more functions do the same thing but instead create a timestamp. I'm trying to take every li element that gets generated and save it to localStorage when you push the save button and then repopulate it again from the local storage when you push the "load" button. I can't get it to work come hell or high water. The load button does nothing, and oddly enough the "save" button acts as a clear all and actually removes everything rather then saving it. Console log shows no errors. I have the JavaScript below and the corresponding HTML.
let item;
let text;
let newItem;
function todoList() {
item = document.getElementById("todoInput").value
text = document.createTextNode(item)
newItem = document.createElement("li")
newItem.onclick = function() {
this.parentNode.removeChild(this);
}
newItem.onmousemove = function() {
this.style.backgroundColor = "orange";
}
newItem.onmouseout = function() {
this.style.backgroundColor = "lightblue";
}
todoInput.onclick = function() {
this.value = ""
}
newItem.appendChild(text)
document.getElementById("todoList").appendChild(newItem)
};
function save() {
const fieldvalue = querySelectorAll('li').value;
localStorage.setItem('item', JSON.stringify(item));
}
function load() {
const storedvalue = JSON.parse(localStorage.getItem(item));
if (storedvalue) {
document.querySelectorAll('li').value = storedvalue;
}
}
<form id="todoForm">
<input id="todoInput" value="" size="15" placeholder="enter task here">
<button id="button" type="button" onClick="todoList()">Add task</button>
<button id="save" onclick="save()">Save</button>
<button id="load" onclick="load()">Load</button>
</form>
As #Phil and #Gary explained part of your problem is trying to use querySelectorAll('li') as if it would return a single value. You have to cycle through the array it returns.
Check the below code to give yourself a starting point. I had to rename some of your functions since they were causing me some errors.
<form id="todoForm">
<input id="todoInput" value="" size="15" placeholder="enter task here">
<button id="button" type="button" onClick="todoList()">Add task</button>
<button id="save" onclick="saveAll()" type="button">Save</button>
<button id="load" onclick="loadAll()" type="button">Load</button>
</form>
<div id="todoList"></div>
<script>
let item;
let text;
let newItem;
function todoList() {
item = document.getElementById("todoInput").value
text = document.createTextNode(item)
newItem = document.createElement("li")
newItem.onclick = function() {
this.parentNode.removeChild(this);
}
newItem.onmousemove = function() {
this.style.backgroundColor = "orange";
}
newItem.onmouseout = function() {
this.style.backgroundColor = "lightblue";
}
todoInput.onclick = function() {
this.value = ""
}
newItem.appendChild(text)
//Had to add the element
document.getElementById("todoList").appendChild(newItem);
}
function saveAll() {
//Create an array to store the li values
var toStorage = [];
var values = document.querySelectorAll('li');
//Cycle through the li array
for (var i = 0; i < values.length; i++) {
toStorage.push(values[i].innerHTML);
}
console.log(toStorage);
//Can´t test this on stackoverflow se the jsFiddle link
localStorage.setItem('items', JSON.stringify(toStorage));
console.log(localStorage);
}
function loadAll() {
const storedvalue = JSON.parse(localStorage.getItem('items'));
console.log(storedvalue);
//Load your list here
}
</script>
Check https://jsfiddle.net/nbe18k2u/ to see it working

Two events on the same button with two click

I need to create a button that works like this :
var i = true
first click --> var i = false
second click --> var i = true
....
HTML
<input type="button" value="test" onclick="stop(); start();" />
How can i specify theese functions in my JS document ?
you can toggle a boolean by doing this :
var b = true;
b = !b
in your case use :
<input type="button" value="test" onclick="b = !b;" />
it's better to doing this with a function
var b = true;
function toggle () { b = !b; console.log(b) }
and in your html
<input type="button" value="test" onclick="toggle();" />
You can do it like this
<input type="button" value="test" />
And the javascript code.
var btn = document.getElementsByTagName('input')[0];
var i = true;
btn.addEventListener('click', function() {
if (i == true)
i = false;
else
i = true;
});
make a counter for clicks
var countClick= 0
if (countClick== 1) {
//do the first click code
}
if (countClick== 2) {
//do the second click code
}
You can simply associate a function call on onclick event and then toggle the boolean value:
var i = true;
function clicked () {
//toggle the value
i = !i;
console.log(i);
}
<input type="button" value="test" onclick="clicked();" />
Here is a snippet that does what you want. You can have it toggle forever or just the one time like your example.
var buttonClicks = 0;
var boolValue = true;
var boolValueOutput = document.getElementById("boolValue")
boolValueOutput.innerHTML = boolValue;
function onButtonClick()
{
buttonClicks++;
// If you want it to only work once uncomment this
//if (buttonClicks > 2)
// return;
boolValue = !boolValue;
boolValueOutput.innerHTML = boolValue;
}
<input type="button" value="test" onclick="onButtonClick();" />
<p id="boolValue"></p>

I can't find out why I can't access two functions

I'm trying to save in local storage the information from input. But when I press on "Save" or "Load", it enters in the "if" but not in the functions $('#save').on('click',...) and $('#load')...
if (typeof (Storage) !== "undefined") {
$('#save').on('click', function() {
window.alert("storagecomp");
$('input[type="text"]').each(function() {
var id = $(this).attr('id');
var value = $(this).val();
localStorage.setItem(id, value);
});
});
$('#load').on('click', function () {
window.alert("warnigclick");
$('input[type="text"]').each(function () {
var id = $(this).attr('id');
var value = localStorage.getItem(id);
$(this).val(value);
});
});
} else {
window.alert("Não suporte do browser para o LocalStorage");
}
Here's the code that calls the javascript code above.
<div id="buttonsL">
<button type="submit" id="buttonL" name="submit">Registar Oferta</button>
<button id="save" name="submitG">Save</button>
<button id="load" name="fg" >Load</button>
<script src="../JSFiles/LocalStorageStuff.js" language="Javascript"></script>
</div>
I've been searching all over but I can't figure out what I am doing wrong. Why isn't it accessing those two functions?
Typos:
$('input[type=text"]').each(function() {
^---what's this for?
in both of your click handlers.

Knockout js how to Implement Countdown Timer

I'm new on Knockout js.Trying to implement countdown timer on html with using knockout js
For this purpose I added 4 html elements(input, span and start, stop buttons) on view. When start button is pressed, the value that written on <input> objects should be passed to refreshViewModel, and there will be countdown process. When the countdown is processing remaining time will be showed inside <span> element. If the stop button is pressed countdown will be stopped.
If the countdown finishes another function(that is callbacked from another viewModel) which is filtering the page with some parameters will be initiated.
Binded textbox value to span value. I cannot figure out how to count and show to remaining value inside span dynamically?
Html:
<div id="pnlTimer" class="row">
<div class="span2 pull-right" style="border:1px solid rgb(218, 218, 218)" >
<span style="font-weight:bold">Reload Interval</span>
<br />
<input id="initialTime" style="width:20px;height:14px" data-bind="value: initialTime" />
<span id="remainingTime" style="visibility:hidden"> / 15</span> second(s)
<button class="btn" style="margin-top:5px" id="StartCounter" data-bind="click: StartCounter">
<i class="icon-play"></i>
</button>
<button style="visibility:hidden;margin-top:5px;margin-left:-44px" class="btn" id="StopCounter" data-bind="click: StopCounter">
<i class="icon-stop"></i>
</button>
</div>
</div>
Js:
#Url.Content("~/Content/App/viewModels/listCasesViewModel.js
#Url.Content("~/Content/App/viewModels/RefreshPageTimerViewModel.js
$(document).ready(function () {
var viewModel = new ListCasesViewModel();
viewModel.init();
var pnl = $("#pnlFilterPanel").get()[0];
ko.applyBindings(viewModel, pnl);
var viewModelTimer = new RefreshPageTimerViewModel();
viewModelTimer.init();
var pnlTimer = $("#pnlTimer").get()[0];
ko.applyBindings(viewModelTimer, pnlTimer);
viewModelTimer.callBackMethod = viewModel.filter;
});
First viewModel :RefreshPageTimerViewModel:
var RefreshPageTimerViewModel = function () {
var self = this;
self.StartCounter = ko.observable();
self.StopCounter = ko.observable();
self.initialTime = ko.observable();
self.remainingTime = ko.computed(function () {
return self.initialTime();
}, self);
countDown: ko.observable()
this.init = function () {
self.Count();
}
this.callBackMethod = function () {
alert("not implemented!");
}
this.Count = function () {
var initial = self.initialTime; // initialTime value;
var remaining = self.remainingTime;
if (remainingTime <= 0) {
this.ExecuteCallBackMethod();
}
}
this.ExecuteCallBackMethod = function () {
this.callBackMethod();
}
};
Second viewModel: ListCasesViewModel:
var ListCasesViewModel = function () {
var self = this;
self.selectedStartDate = ko.observable(null);
self.selectedEndDate = ko.observable(new Date());
self.selectedSearchKey = ko.observable("");
self.selectedStatuses = ko.observableArray();
self.selectedHospitals = ko.observableArray();
// methods...
this.init = function () {
self.selectedEndDate(new Date());
self.filter();
}
this.filter = function () {
// get filter control values
var startDate = self.selectedStartDate(); // dtStart.value();
var endDate = self.selectedEndDate(); //dtEnd.value();
var searchText = self.selectedSearchKey();
//And Some calculations....
The main problem is your ViewModel code, it uses an observable where you wanted a function (to Start and Stop the counter). Also, it does not seem to have a clear definition of what it is trying to do.
Also, im assuming you wanted the Start button to show when the timer is stopped, and the Stop button to show when the timer is started - so ive taken the liberty to add this functionality too.
Here is the rewritten view model:
var RefreshPageTimerViewModel = function () {
var self = this;
self.timerId = 0;
self.elapsedTime = ko.observable(0);
self.initialTime = ko.observable(0);
self.remainingTime = ko.computed(function(){
return self.initialTime() - self.elapsedTime();
});
self.isRunning = ko.observable(false);
self.StartCounter = function(){
self.elapsedTime(0);
self.isRunning(true);
self.timerId = window.setInterval(function(){
self.elapsedTime(self.elapsedTime()+1);
if(self.remainingTime() == 0){
clearInterval(self.timerId);
self.isRunning(false);
self.Callback();
}
},1000)
}
self.StopCounter = function(){
clearInterval(self.timerId);
self.isRunning(false);
}
self.Callback = function(){}
}
A few things to note:
Has a property timerId, which does not need to be observable, but allows us to stop the timer which is used to increment the elapsedTime
has an observable property isRunning used to control the visibility of the Start and Stop buttons
has an empty function Callback which can be used to execute any function when the countdown reaches zero.
Here is the new markup:
<div id="pnlTimer" class="row">
<div class="span2 pull-right" style="border:1px solid rgb(218, 218, 218)" >
<span style="font-weight:bold">Reload Interval</span>
<br />
<input id="initialTime" style="width:20px;height:14px" data-bind="value: initialTime" />
<span id="remainingTime" data-bind="text: remainingTime"></span> second(s)
<button class="btn" style="margin-top:5px" id="StartCounter" data-bind="click: StartCounter, visible: !isRunning()">
start
</button>
<button style="margin-top:5px" class="btn" id="StopCounter" data-bind="click: StopCounter, visible:isRunning()">
Stop
</button>
</div>
</div>
Note the addition of visible: !isRunning() to the start and visible:isRunning() to the stop buttons.
Finally, here is the init code:
$(function(){
var viewModelTimer = new RefreshPageTimerViewModel();
viewModelTimer.Callback = function(){
alert("finished");
};
ko.applyBindings(viewModelTimer);
})
Note the creation of a callback function which simply alerts. Your code could be as it was, ie viewModelTimer.callBackMethod = viewModel.filter;
Finally, a live example to allow you to play around: http://jsfiddle.net/eF5Ec/

Categories