How can I adjust in my Jquery Code see description of problem - javascript

Currently right now it adds up a visit counter. Example: I have a text field and I type 1 then next text field I type of 20 so 1 of 20 visits. Next document I use it uses the same counter so it would automatically calculate up the visits for me to say 2 of 20 visits. What I want to figure out is if I need to change the counter to say 3 of 20 instead of 2 out of 20 how can I adjust the code to save my changes.
Currently the counter reverts back after I save my document with the counter in it- reverts back to 2 of 20 not reflecting me changing it to 3 of 20.
window.onload = function(e){
setCurrentCount('previousvisit','currentvisit','totalvisits');
}
function setCurrentCount(prevId, currentId, totalId ) {
var prevEle = document.getElementById(prevId);
var currentEle = document.getElementById(currentId);
var totalEle = document.getElementById(totalId );
if( prevEle && currentEle && totalEle ) {
var totalVal = parseInt(totalEle.value);
if( totalVal > 0) {
var prevVal = 0;
// check the prev value
// if it is empty, set it to the total value
if(! prevEle.value ) {
//currentEle.value = totalVal;
prevEle.value = totalVal;
} else {
currentEle.value = parseInt(prevEle.value) + 1;
}
}
}
}
If I change the counter to reflect a different number outside the initial calculation I want it to save it- right now it reverts back to the number it actually should be in the calculation.

Related

count number of inputs which have value

js noob here - I'm trying to count the number of inputs that have a value out of a calculated number of them. The code I came up with trying to achieve that is the following:
var fields = document.querySelectorAll('[id^=example-]'), count = 0;
for (var z = 0; z <= fields.length; z++) {
if (fields[z].value != "") {
count = count + 1;
}
console.log('count is: ' + count);
}
Context: there are 3 inputs total and the above code executes on a click event.
Now the first time, this obviously runs fine if for example I set the value of the first input out of the three and returns [1]. The second time I update the same field's value, the counter increases again (logically).
Now, what I would like to achieve is to check all three inputs at the time the event fires & count how many of them have a value (and not increase the counter furthermore if they are already counted as having a value in the previous fire event).
Any help would be greatly appreciated. Thanks!
Shorter
const count = [...document.querySelectorAll('[id^=example-]')]
.filter(fld => fld.value.trim() !== "")
.length

Get the highest number or the next available number in a list

I'm encountering a problem with assigning the next invoice line value.
I have written a piece of javascript to get the next value but somehow it is missing the next available value and still choosing the highest value.
What I need is the highest or the next available number, LineNo is what I need the highest or next of.
Code
onGridBeforeEditLines: function (e) {//grid 2
var event123 = e;
var lineNo = 0;
var grid = $("#gridLines").data("kendoGrid");
$(grid.dataSource.data()).each(function (i, v) {
if (v != null) {
if (v.LineNo >= lineNo)
lineNo = v.LineNo; //Getting the highest value
}
});
lineNo++;
grid = $("#gridContracts").data("kendoGrid");
if (e.model.PaymentPeriodID == 0) {
var selectedItem = grid.dataItem(grid.select());
e.model.PaymentPeriodID = selectedItem.ID;
e.model.LineNo = lineNo; //setting the value to the grid
}
},
Images
It seems to work fine for getting the highest number and adding 1 to it. The highest is 3, so 4 is the next available line number.
It doesn't seem to work in when finding the next available number. I have removed line no 2 so 2 should be the next available option but it still gets the highest and adds 1 to it.
Thank you in advance for help.
if (v.LineNo > lineNo+1) { // then we skipped a space
// next open value is lineNo+1
lineNo = lineNo+1;
return false; // break loop
} else if (v.LineNo == lineNo+1) {
lineNo = v.LineNo; //Getting the next sequential value , keep looping
} else {
// lineNo should stay the same
}

How to do something when backspace or delete is pressed

So I am having trouble getting my code to do something when I hit backspace or delete.
The code I have works just fine. It runs the following code, updating the size and value of multiple text input fields.
It calls compute(), which calls update() multiple times through updateAllFields().
function compute(input,number){
var decider = String(input.value);
updateAllFields(decider,number);
}
function update(label,convert,decider,number){
var updater = document.getElementById(label);
updater.value = parseInt(decider, number).toString(convert);
updater.style.width = ((updater.value.length + 1) * 12.5) + 'px';
}
function updateAllFields(decider,number){
update('binary',2,decider,number);
update('octal',8,decider,number);
update('decimal',10,decider,number);
update('hexadecimal',16,decider,number);
}
Now, that all runs just fine. I ran into an issue that, when an entire field is deleted, I get NaN, and can no longer edit the text fields unless I outsmart the NaN value.
How it happens is that that if a user hits "Ctrl+home", then backspace (wiping the entire field), NaN appears.
What I want, instead, is that when NaN would have appeared, all of the text inputs are reset to the same size and appearance that they were when their placeholders were showing.
I had looked this up, and found the following:
var input = document.getElementById('display');
input.onkeydown = function() {
var key = event.keyCode || event.charCode;
if( key !== 8 && key !== 46 )
return true;
};
It doesn't work. I even tried replacing the return false to instead read my replacement code:
function refresh(label,number){
var refresher = document.getElementById(label);
refresher.value = '';
refresher.size = number;
}
function refreshAllFields(){
refresh('binary','3');
refresh('octal','2');
refresh('decimal','4');
refresh('hexadecimal','8');
}
And that doesn't work.
What am I doing wrong? How can I get my fields to just reset to their original states if the entire text-field of one is wiped out?
You don't need to decrease the possibility of error. You need to prevent errors at all. Just validate the input data and you won't get NaN.
Simply add a check in your compute if the input is an integer:
function compute(input,number){
var decider = String(input.value);
if (isNumeric(decider))
{
// do something else
decider = "0"; // for example
}
updateAllFields(decider, number);
}
where isNumeric is a function which determines if a string represents number. There are many ways to do this, for example this:
function isNumeric(value)
{
if (isNaN(value)) {
return false;
}
var x = parseFloat(value);
return (x | 0) === x;
}
Also, you can stop passing your decider and number to every function as a string:
function compute(input, number){
if (isNumeric(input.value))
{
updateAllFields(parseInt(input.value, number)); // val is a Number now
} else {
updateAllFields(0); // for example
}
}
function update(label,convert,val){
var updater = document.getElementById(label);
updater.value = val.toString(convert);
updater.style.width = ((updater.value.length + 1) * 12.5) + 'px';
}
function updateAllFields(val) {
update('binary',2,val);
update('octal',8,val);
update('decimal',10,val);
update('hexadecimal',16,val);
}

dice random value 1 to 10 and overthrow in Javascript

Hi I have code like this:
$('#Generator_Rzutow').click (function(){
var val1 = $('#rzucane').val();
var val2 = $('#zachowywane').val();
var zbior = [];
var limit = 10;
alert (val1);
alert (val2);
for (var i=0; i<val1;i++){
var wynik_rzutu = 1+Math.floor(Math.random()*10);
if (wynik_rzutu<limit){
zbior.push(wynik_rzutu);
} else {
limit = limit+10;
wynik_rzutu = wynik_rzutu+1+Math.floor(Math.random()*10);
if (wynik_rzutu<limit){
zbior.push(wynik_rzutu);
} else {
limit = limit+10;
wynik_rzutu = wynik_rzutu+1+Math.floor(Math.random()*10);
zbior.push(wynik_rzutu);
}
}
}
$('#wypisz').text (zbior);
});
My problem is that when it randoms '10' it sometimes add 10 to array, when it should randomize another time and ad it to prev value.
My second question is. How to get it to randomize another value and ad it to prev as long as it randomize 10. For ex: so it could get numer 74, when it randomize 7x10 and 4, and then it past it to array.
I know I should do it by while lop but I couldn`t get working solition, so instead I put 'if'
The first problem is that you don't reset your limit at each iteration. You start with limit 10, then when the first number larger than 10 is generated, the limit is increased to 20 and all subsequent numbers will be compared to 20 to see if they are added to the array or re-generated (and they will all be added to the array, since they are all smaller than 20).
As for your second problem, i think this piece of code behaves accordingly:
for (var i=0; i<val1;i++){
var wynik_rzutu = 0, limit = 0;
while (wynik_rzutu >= limit) {
wynik_rzutu += 1+Math.floor(Math.random()*10);
limit += 10;
}
zbior.push(wynik_rzutu);
}
You can also add a counter to prevent it from an infinite cycle (if Math.random() always returns 0.9 for example), but i doubt it is something you really require.

Implementing voting logic based on previous score

Wondering how to handle this. I've done it previously, but it involves a lot of if/else statements and I can't seem to figure it out without resorting to that. I posted it on codereview and got someone to help me re-facor it, but now I'm trying to get this functionality working properly.
How this works now is, if you click "up", it'll increase the score 1 point. If you click "up" again, it'll decrease the score. That's fine. If you click "down" it'll have the same behavior. It will not however go below 0 ever, since I don't want to display a negative score.
Right now I'm just checking to see if the previous or next buttons have .upColor and .downColor css classes on them, which check if they've already voted. I'm having trouble trying to update the proper score based off of this especially if the original score is 0, or if the score is 10.
Logic I'm trying to implement:
E.g. Original score is 0:
User votes up. Score goes to 1. User votes down. Score goes to 0 (not -1)
User votes down. Score stays at 0. User votes up. Score goes to 1.
E.g. Original score is 10:
User votes up. Score goes to 11. User votes down. Score goes to 9.
User votes down. Score goes to 9. User votes up. Score goes to 11.
Code:
$(function() {
var handleClick = function($btn) {
var $voteContainer = $btn.parent();
var scoreNode = $('.count');
var originalScore = Number($voteContainer.data('original-score'));
if ($btn.hasClass('down')) {
if ($btn.prevAll('.up').hasClass('upColor')) {
$btn.prevAll('.up').toggleClass('upColor');
alert('voted up now voting down, decrease 2 points, but don\'t go below 0.');
}
}
if ($btn.hasClass('up')) {
if ($btn.nextAll('.down').hasClass('downColor')) {
$btn.nextAll('.down').toggleClass('downColor');
alert('voted down now voting up, increase by 2 points');
}
}
var increment = $btn.hasClass('up') ? 1 : $btn.hasClass('down') && originalScore > 0 ? -1 : 0; // default
// Only do something if there is an increment
if (increment) {
var currentScore = Number(scoreNode.text()) || 0;
var newScore = currentScore + increment;
var diff = Math.abs(originalScore - newScore);
// Can't go more than + or - 1
if (diff > 1) {
newScore = originalScore;
}
// Set new displayed value
scoreNode.text(newScore);
}
$btn.hasClass('up') ? $btn.toggleClass('upColor') : $btn.toggleClass('downColor');
};
var upBtn = $('.up');
var downBtn = $('.down');
upBtn.add(downBtn).click(function() {
var $btn = $(this);
handleClick($btn);
});
});
Demo: http://jsfiddle.net/3kCPw/
I won't rewrite your code because it will take me too long, but I will give you some code that I would have used from the start.
Start with the original number:
var original_vote = 2;
var current_vote = original_vote;
Keep this as a constant to refer to for the future. Then when you click the up vote, you can add 1 to that simply with:
current_vote = original_vote + 1;
Then un-checking the up vote would make it:
current_vote = original_vote;
Then just do the opposite for down voting.
Keeping the original number ensures that you will not accidentally make the votes go out of the scope that it should.
Hope this helps!

Categories

Resources