Using JavaScript to increment top/left/bottom/right values
Because style.top
is a string with units on the end of it like "300px"
you can only do math with it when you convert just the numeric part to an actual number.
Assuming you have a positioned element (so setting the top
value will do something) and you already have a top
style set directly on the element and not set via CSS (so getting obj.style.top
will actually get you something), you can do it by parsing the number out of the style value like this:
var obj = document.getElementById("something");
var topVal = parseInt(obj.style.top, 10);
obj.style.top = (topVal + 300) + "px";
Working example: http://jsfiddle.net/jfriend00/pt46X/
JavaScript increment and decrement each time a button is pressed
You need to use parseInt
or similar to let JavaScript know that this should be treated as a number and not a string:
const adjustValue = event => { const increasePressed = event.target.id === 'increase'; const decreasedPressed = event.target.id === 'decrease';
if (increasePressed || decreasedPressed) { const currentValue = parseInt(document.querySelector('#el').innerHTML); const el = document.querySelector('#el');
el.innerHTML = increasePressed ? currentValue + 10000 : currentValue - 10000; }};
document.querySelector('#container').addEventListener('click', adjustValue);
<div id="container"> <span>Current value: </span><span id="el">0</span><br/> <input id="increase" type="button" value="Increase" /> <input id="decrease" type="button" value="Decrease" /></div>
What is a method that can be used to increment letters?
Simple, direct solution
function nextChar(c) {
return String.fromCharCode(c.charCodeAt(0) + 1);
}
nextChar('a');
As others have noted, the drawback is it may not handle cases like the letter 'z' as expected. But it depends on what you want out of it. The solution above will return '{' for the character after 'z', and this is the character after 'z' in ASCII, so it could be the result you're looking for depending on what your use case is.
Unique string generator
(Updated 2019/05/09)
Since this answer has received so much visibility I've decided to expand it a bit beyond the scope of the original question to potentially help people who are stumbling on this from Google.
I find that what I often want is something that will generate sequential, unique strings in a certain character set (such as only using letters), so I've updated this answer to include a class that will do that here:
class StringIdGenerator {
constructor(chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ') {
this._chars = chars;
this._nextId = [0];
}
next() {
const r = [];
for (const char of this._nextId) {
r.unshift(this._chars[char]);
}
this._increment();
return r.join('');
}
_increment() {
for (let i = 0; i < this._nextId.length; i++) {
const val = ++this._nextId[i];
if (val >= this._chars.length) {
this._nextId[i] = 0;
} else {
return;
}
}
this._nextId.push(0);
}
*[Symbol.iterator]() {
while (true) {
yield this.next();
}
}
}
Usage:
const ids = new StringIdGenerator();
ids.next(); // 'a'
ids.next(); // 'b'
ids.next(); // 'c'
// ...
ids.next(); // 'z'
ids.next(); // 'A'
ids.next(); // 'B'
// ...
ids.next(); // 'Z'
ids.next(); // 'aa'
ids.next(); // 'ab'
ids.next(); // 'ac'
How to use increment number to do the math and update the result in jQuery
Here you go with a solution https://jsfiddle.net/ceksng83/15/
$(".numbers-row").append('<div class="inc button_inc">+</div><div class="dec button_inc">-</div>');$(".button_inc").on("click", function() { var $button = $(this); var oldValue = $button.parent().find("input").val();
if ($button.text() == "+") { var newVal = parseFloat(oldValue) + 1; } else { // Don't allow decrementing below zero if (oldValue > 1) { var newVal = parseFloat(oldValue) - 1; } else { newVal = 0; } } $button.parent().find("input").val(newVal); //update span to do the math and update #total_ad $('#' + $(this).siblings('input').data('pax')).text(newVal); var cost_ad = parseInt($('#cost_ad').attr('value'));//pre-defined value from attribute-value var amt_ad = parseInt($('#amt_ad').text());//update value from increment $('#total_ad').html(cost_ad*amt_ad);//math result from multiply});
.numbers-row { position: relative; width: 97px; height: 40px; overflow: visible;}
.numbers-row.list { margin: auto; margin-bottom: 5px; margin-top: 15px;}
input.qty2 { position: relative; width: 35px; height: 40px; border-radius: none; text-align: center; left: 31px; font-size: 12px; padding: 5px;}
.button_inc { text-indent: -9999px; cursor: pointer; position: absolute; width: 33px; height: 40px; z-index: 9;}
.dec { background: #fff url('https://www.ecobank.com/img/iconMinus.gif') no-repeat center center; border: 1px solid #cccccc; left: 0; top: 0; -webkit-border-top-left-radius: 4px; -webkit-border-bottom-left-radius: 4px; -moz-border-radius-topleft: 4px; -moz-border-radius-bottomleft: 4px; border-top-left-radius: 4px; border-bottom-left-radius: 4px;}
.inc { background: #fff url('https://www.ecobank.com/img/iconPlus.gif') no-repeat center center; right: 0; top: 0; border: 1px solid #cccccc; -webkit-border-top-right-radius: 4px; -webkit-border-bottom-right-radius: 4px; -moz-border-radius-topright: 4px; -moz-border-radius-bottomright: 4px; border-top-right-radius: 4px; border-bottom-right-radius: 4px;}
<link href="https://netdna.bootstrapcdn.com/bootstrap/3.1.1/css/bootstrap.min.css" rel="stylesheet"/><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><script src="https://netdna.bootstrapcdn.com/bootstrap/3.1.1/js/bootstrap.min.js"></script>
<div class="row"> <div class="col-md-6 col-sm-6"> <div class="form-group"> <label>Adults</label> <div class="numbers-row"> <input type="text" value="1" class="qty2 form-control" name="qty_ad" data-pax="amt_ad"> </div> </div> </div> <div class="col-md-6 col-sm-6"> <div class="form-group"> <label>Children</label> <div class="numbers-row"> <input type="text" value="0" class="qty2 form-control" name="qty_ch" data-pax="amt_ch"> </div> </div> </div></div><hr />Adult Price = <span id="cost_ad" value="100">100</span> x <span id="amt_ad">1</span> = <span id="total_ad"></span><br />Child Qty <span id="amt_ch"></span>
Related Topics
Where's the Connection Between Index.HTML and Index.Js in a Create-React-App Application
How to Add Dom Element Script to Head Section
Calculate Color Values from Green to Red
How to Dynamically Remove a Stylesheet from the Current Page
How to Get CSS3 Multi-Column Count in JavaScript
How to Generate an APK That Can Run Without Server with React-Native
How to Remove "Disabled" Attribute Using Jquery
Google Chrome Console.Log() Inconsistency with Objects and Arrays
How to Capitalize the First Letter of Each Word in a String Using JavaScript
Jquery - Multiple $(Document).Ready ...
How to Avoid Global Variables in JavaScript
Get Keys of a Typescript Interface as Array of Strings
Find All Possible Subset Combos in an Array
Why Does JavaScript Variable Declaration at Console Results in "Undefined" Being Printed