Slidebar which can be adjusted manually - javascript

I did a Slidebar (0-99) which is working well.
I want to add 2 buttons to manually change it (first button -1 ; second button +1).
It was working well with my "-1" code for the first button, but the second one isnt working and I dont understand why. (It add 1 but for example if my slidebar is at 50, when i click its not going to 51 but 501).
Here is my code :
<div>
<button id="moins1" onclick="moins1()">MOINS 1</button>
<span class="unselectable rangeValue1" id="rangeValue1">RR</span>
<Input class="range" type="range" name="BarreRR" value="0" min="0" max="99" onChange="rangeSlide1(this.value)" onmousemove="rangeSlide1(this.value)"></Input>
<button id="plus1" onclick="plus1()">PLUS 1</button>
</div>
<script type="text/javascript">
function rangeSlide1(value) {
document.getElementById('rangeValue1').innerHTML = value;
}
function moins1(){
var Yop = document.getElementById('rangeValue1').textContent;
Yop -=1;
document.getElementById('rangeValue1').innerHTML = Yop;
console.log(Yop);
}
function plus1(){
var Yop = document.getElementById('rangeValue1').textContent;
Yop +=1;
document.getElementById('rangeValue1').innerHTML = Yop;
console.log(Yop);
}
</script>
Thanks for help, Zartex.

The issue is that textContent returns string and using + operator will try to concatenate the values. So you can parse it. But I would recommend directly connecting your range with displayed value and only alter the range using the buttons or change them together for example:
function rangeSlide1(value) {
document.getElementById('rangeValue1').innerHTML = value;
}
function moins1() {
let range = document.querySelector('.range')
if (range.value != 0) {
let newValue = range.value - 1
document.getElementById('rangeValue1').innerHTML = newValue
range.value = newValue
}
}
function plus1() {
let range = document.querySelector('.range')
if (range.value < 99) {
let newValue = Number(range.value) + 1
document.getElementById('rangeValue1').innerHTML = newValue
range.value = newValue
}
}
<div>
<button id="moins1" onclick="moins1()">MOINS 1</button>
<span class="unselectable rangeValue1" id="rangeValue1">RR</span>
<Input class="range" type="range" name="BarreRR" value="0" min="0" max="99" onChange="rangeSlide1(this.value)" onmousemove="rangeSlide1(this.value)"></Input>
<button id="plus1" onclick="plus1()">PLUS 1</button>
</div>
Considering your range is limited from 0 to 100 I added condition not to go under 0

it will help you,
Yop value always in "50" + 1 it will return by concat 501
so parseInt your string and add/minus by 1
function moins1(){
var Yop = document.getElementById('rangeValue1').textContent;
Yop = parseInt(Yop)-1;
document.getElementById('rangeValue1').innerHTML = Yop;
console.log(Yop);
}
function plus1(){
var Yop = document.getElementById('rangeValue1').textContent;
Yop = parseInt(Yop)+1;
document.getElementById('rangeValue1').innerHTML = Yop;
console.log(Yop);
}

Related

Pagination in vanilla Javascript without any frameworks or libraries

Stackoverflow! I got a task to create sortable/dynamic table with options to add and remove content and I've managed to do it. My last task however is to make a pagination of 20 rows per page and that's where my 10 days Javascript knowledge is put to a high test. Namely, I can't even put my foot of the ground.
Can anyone help me out in understanding the logic behind the creation of pagination?
here is the code for paginating your table for 20 elements per page:
Edit the function loadTableData() with this:
//Pagination
function loadTableData(movieData, page_size, page_number) {
// human-readable page numbers usually start with 1, so we reduce 1 in the first argument
var movieDatap = movieData.slice((page_number - 1) * page_size, page_number * page_size);
const tableBody = document.getElementById('tableData');
let txt = '';
for (let i = 0; i < movieDatap.length; i++) {
txt = txt + `<tr><td>${movieDatap[i].name}</td>
<td>${movieDatap[i].genre}</td><td>${movieDatap[i].rating}</td>
<td><button onclick="deleteRow(${i});">Delete</button>
<button onclick="editRow(${i});">Edit</button></td></tr>`;
}
tableBody.innerHTML = txt;
}
function decreaseTableDatas(){
var value = parseInt(document.getElementById('pagenumber').value, 10);
value = isNaN(value) ? 0 : value;
value--;
document.getElementById('pagenumber').value = value;
loadTableData(movieData, 20, value);
}
function incrementTableDatas(){
var value = parseInt(document.getElementById('pagenumber').value, 10);
value = isNaN(value) ? 0 : value;
value++;
document.getElementById('pagenumber').value = value;
loadTableData(movieData, 20, value);
}
window.onload = () => {
loadTableData(movieData, 20, 1);
}
Update the HTML with this:
<div class="pagination">
<div class="pagination-block">
<span class="pageButton outline-none" onclick="decreaseTableDatas()" id="button_prev">Prev</span>
<input type="button" value="1" id="pagenumber" />
<span class="pageButton outline-none" onclick="incrementTableDatas()" id="button_next">Next</span>
</div>
</div>
I hope that is what you are looking for mate

Add/decrease value on click

I have some code that I've implemented as a counter, however, can this code be slightly modified to allow a button to increase a value by 200 and then decrease down to 0? I understand that ++x will increase, but I'm not sure why +x won't add? Is it something to do with strings?
Javascript:
let x = 200;
$('.counter-button.counter-up').on('click', () => {
$('.counter-input.w-input').val( +x );
});
$('.counter-button.counter-down').on('click', () => {
if (x > 0) {
$('.counter-input.w-input').val( -x );
}
});
$('.counter-input.w-input').change(function () {
const num = Number($(this).val());
// if it's a number
if (num) {
// assign its value to x
x = num;
}
});
Thanks for any help with this!
For the record (honoring your initial question): here's a 'vanilla' solution.
{
document.addEventListener("click", addOrSubtract);
function addOrSubtract(evt) {
const from = evt.target;
if (from.dataset.addvalue) {
const numberInput = document.querySelector("input");
const newValue = +numberInput.value + +from.dataset.addvalue;
numberInput.value = newValue >= +numberInput.min
&& newValue <= +numberInput.max ? newValue : numberInput.value;
}
}
}
<input type="number" min="0" max="4000" value="0" readonly>
<button data-addvalue="200">increment</button> (max 4000)
<button data-addvalue="-200">decrement</button> (min 0)
.val() doesn't increase or decrease, it assigns. Try:
$('.counter-input.w-input').val( $('.counter-input.w-input').val() + x );
When you pass +x or -x it will just set that value as a value of the input. So you could first calculate the new value by adding or subtracting x of the current value based on the clicked button class.
let x = 200;
let input = document.querySelector('.counter-input.w-input')
let buttons = document.querySelectorAll('.counter-button')
buttons.forEach(b => {
b.addEventListener('click', function() {
let value = +input.value;
if (this.classList.contains('counter-up')) {
value += x
} else if (value > 0) {
value -= x
}
input.value = value
})
})
<button class="counter-button counter-up">Up</button>
<button class="counter-button counter-down">Down</button>
<input value="0" type="text" class="counter-input w-input">

Count inputs number onchange

i have a little problem with my code, i need to count inputs when change the value, my code is working but when i used the increase button the count dont change the value.
HTML CODE:
<div class="input-group input-number-group">
<div class="input-group-button">
<span class="input-number-decrement">-</span>
</div>
<input class="input-number" type="number" value="1" min="0" max="1000" onchange="count(this.value);">
<div class="input-group-button">
<span class="input-number-increment">+</span>
</div>
</div>
<div class="input-group input-number-group">
<input class="input-number" type="text" id="totalcount" placeholder="0" />
</div>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
JS CODE:
$('.input-number-increment').click(function() {
var $input = $(this).parents('.input-number-group').find('.input-number');
var val = parseInt($input.val(), 10);
$input.val(val + 1);
});
$('.input-number-decrement').click(function() {
var $input = $(this).parents('.input-number-group').find('.input-number');
var val = parseInt($input.val(), 10);
$input.val(val - 1);
})
/* Count. */
function count(value) {
var Total = 0;
value = parseInt(value); // Convertir a numero entero (nĂºmero).
Total = document.getElementById('totalcount').value;
// Valida y pone en cero "0".
Total = (Total == null || Total == undefined || Total == "") ? 0 : Total;
/* Variable genrando la suma. */
Total = (parseInt(Total) + parseInt(value));
// Escribir el resultado en una etiqueta "span".
document.getElementById('totalcount').value = Total;
}
Here is the fiddle
I need to count when i press the + or rest when i press - button, any idea?
Thank so much.
the onchange event listener is triggered when the user changes the input by typing. Therefore .val() wont cause it to fire up.
You can easily trigger the onchange event manually by adding
$(".input-number").change();
to the desired functions in your code.
In your specific case this should do the trick:
$('.input-number-increment').click(function() {
var $input = $(this).parents('.input-number-group').find('.input-number');
var val = parseInt($input.val(), 10);
$input.val(val + 1);
$(".input-number").change();
});
$('.input-number-decrement').click(function() {
var $input = $(this).parents('.input-number-group').find('.input-number');
var val = parseInt($input.val(), 10);
$(".input-number").change();
})
Now your count function will execute when the user clicks the increment and decrement buttons.

How to reuse code block in javascript

I am new to learning javascript and apologize if this question is too basic. I have tried to search for a solution but nothing has been clear to me. I have created this code in this link.
https://jsfiddle.net/5p7wzy9x/3/
var btn = document.getElementById("calc");
btn.addEventListener("click", function() {
var total = 0;
var count = 0;
var values = document.getElementsByClassName("value");
for (var i = 0; i < values.length; i++) {
var num = parseFloat(values[i].value);
if (!isNaN(num)) {
total += num;
count++;
}
}
output = total / count;
var totalTb = document.getElementById("total");
totalTb.value = count ? output : "NaN";
});
var btn = document.getElementById("calcTwo");
btn.addEventListener("click", function() {
var total = 0;
var count = 0;
var values = document.getElementsByClassName("value");
for (var i = 0; i < values.length; i++) {
var num = parseFloat(values[i].value);
if (!isNaN(num)) {
total += num;
count++;
}
}
output = (total / count);
var totalTb = document.getElementById("total");
totalTb.value = output >= 90 ? "A"
: output >= 80 ? "B"
: output >= 70 ? "C"
: output >= 60 ? "D"
: "YOU FAIL!";
});
My question is, how would I go about being able to use the same code for the second "grade" button without having to copy and pasting the same code?
I saw that you can use functions to invoke the same code block but am confused how I would go about it. I apologize if this question has already been answered, but I have diligently searched and tried to figure this out on my own. Thank you in advanced.
Instead of passing anonymous functions (functions with no names) to your event handlers as data:
btn.addEventListener("click", function() { ...
set up those functions as "function declarations" so that you can call them by name. Then, instead of passing them into the .addEventListner() method call, you reference them by name (without parenthesis next to the name).
Here's an example:
// Both buttons are configured to call the same event handling function:
document.getElementById("btn1").addEventListener("click", doSomething);
document.getElementById("btn2").addEventListener("click", doSomething);
function doSomething(){
console.log("Hello!");
}
<input type=button id="btn1" value="Click Me">
<input type=button id="btn2" value="Click Me">
Here is how you can combine common code in one function:
var btn = document.getElementById("calc");
var btn2 = document.getElementById("calcTwo");
var totalTb = document.getElementById("total");
btn.addEventListener("click", function() {
var output = getTotal();
totalTb.value = output < Infinity ? output : "NaN";
});
btn2.addEventListener("click", function() {
var output = getTotal();
totalTb.value = output >= 90 ? "A"
: output >= 80 ? "B"
: output >= 70 ? "C"
: output >= 60 ? "D"
: "YOU FAIL!";
});
function getTotal() {
var total = 0;
var count = 0;
var values = document.getElementsByClassName("value");
for (var i = 0; i < values.length; i++) {
var num = parseFloat(values[i].value);
if (!isNaN(num)) {
total += num;
count++;
}
}
output = total / count;
return output;
}
<form id="form1">
<input class="value" type="text" value="80" /><br />
<input class="value" type="text" value="50" /><br />
<input class="value" type="text" value="15" /><br />
<input class="value" type="text" value="30" /><br />
<input class="value" type="text" value="90" /><br />
<br />
<input type="text" id="total" />
<button type="button" id="calc">Calculate</button>
<button type="button" id="calcTwo">Grade</button>
</form>

function to increment / decrement more than stepper in javascript

Hello I am trying to rewrite a function that will increment / decrement more than 1 stepper in javascript. Here is what I tried so far
here is a codepen link http://codepen.io/Ongomobile/pen/XdyBgv/
Here is 1 of the steppers
<div class="qtyDiv">
<label class="qtyLabel" for="qty1 " name"one"><abbr title="Quantity">Qty</abbr></label>
<input class="qtyInput" id="qty1" value="0" name"one" />
<!-- <button class=" tallyBtn" id="down" onclick="modify_qty(-1)">-1</button>
<button class="tallyBtn"id="up" onclick="modify_qty(1)">+1</button> -->
<button class=" tallyBtn" id="down" onclick="stepperVal("one",-1)">-1</button>
<button class="tallyBtn"id="up" onclick="stepperVal("one",1)">+1</button>
</div>
// This is current one
function modify_qty(val) {
var qty = document.querySelector("#qty1").value;
var new_qty = parseInt(qty,10) + val;
if (new_qty < 0) {
new_qty = 0;
}
document.querySelector("#qty1").value = new_qty;
return new_qty;
}
This is what I tried
function stepperVal(name,val){
var qty = 0;
var new_qty = parseInt(qty,10) + val;
if (new_qty < 0) {
new_qty = 0;
}
[name].value = new_qty;
return new_qty;
}
A few issues:
What's the purpose of this line parseInt(qty,10) + val;? parseInt is intended to convert a string into its equivalent digit. Not much point in calling it on a base10 number.
Not sure what the point of the name argument to stepperVal is. Isn't the amount to be stepped already implied by the value argument?
You can pass a reference to the object triggering the onclick event by passing this to your function declared within the onclick.
new_qty always evaluates to val
stepperVal(arg,-1) is actually the same as stepperVal(arg,0). Why not just call it that way?
Updated code
replace "one" with this in :
<div class="qtyDiv">
<label class="qtyLabel" for="qty1 " name"one"><abbr title="Quantity">Qty</abbr></label>
<input class="qtyInput" id="qty1" value="0" name"one" />
<!-- <button class=" tallyBtn" id="down" onclick="modify_qty(-1)">-1</button>
<button class="tallyBtn"id="up" onclick="modify_qty(1)">+1</button> -->
<button class=" tallyBtn" id="down" onclick="stepperVal(this,-1)">-1</button>
<button class="tallyBtn"id="up" onclick="stepperVal(this,1)">+1</button>
</div>
Simplified JS:
function stepperVal(event, val){
clicked_link = event.target
return clicked_link.value = Math.max(0, val); # Return the greater of 0 and `val`
}
Use following it must work:
function stepperVal(name,val){
var qty = 0;
var new_qty = parseInt(document.getElementsByName(name),10) + val;
if (new_qty < 0) {
new_qty = 0;
}
document.getElementsByName(name).value = new_qty;
return new_qty;
}

Categories

Resources