Jquery counting - javascript

How do i count #total value + 170 with jquery?
$("#member").click(function() {
if ($('#member').is(':checked')) {
var totalv = $("#total").val();
var skatz = 170;
var skaits = totalv + skatz;
$("#total").val(skaits);
}

You should check if the provided value is actually a number (You can do onkeypress or keyup each time but I say you should always check on submission). Below is your code modified to work (With checks to see if the value is a number).
EDIT: Make sure that your javascript has document ready wrapped around it. (Functions can be outside of this call)
$(document).ready(function () {
$("#member").click(function() {
if ($('#member').is(':checked')) {
var totalv = $("#total").val();
if(isNumber(totalv) == true)
{
var skatz = 170;
var skaits = parseInt(totalv) + skatz;
$("#total").val(skaits);
}
else
{
alert("You must enter a numerical value");
}
}
});
function isNumber(n) {
return !isNaN(parseFloat(n)) && isFinite(n);
}

The result of .val() will be a string, so you first need to convert it to a number:
var totalv = $("#total").val();
var skatz = 170;
var skaits = +totalv + skatz;
$("#total").val(skaits);
(notice the additional + prefix to the totalv variable.

Related

How to create a counter with a plus and minus button which passes a parameter so that I don't have two use two separate functions?

I have created a counter with a plus and minus button. The counter works fine but I would like to simplify my code by passing a parameter to my function that performs both the plus and minus calculations depending on which button is clicked. At the moment I have two separate functions doing this but I would like to pass the 'result' variable as this is the part that tells my script whether I want to add 1 or minus 1, however I am unsure on how to do this?
I have attached my JavaScript below to show what I have so far.
document.getElementById('minus').onclick = function() {
var counter = document.getElementById('counter').innerHTML;
var parsed = parseInt(counter);
var result = parsed -1;
document.getElementById('counter').innerHTML = result;
}
document.getElementById('plus').onclick = function() {
var counter = document.getElementById('counter').innerHTML;
var parsed = parseInt(counter);
var result = parsed +1;
document.getElementById('counter').innerHTML = result;
}
You can make a curried function to "bake" your delta value into the click handlers:
function changeCount(delta) {
return function () {
var counter = document.getElementById('counter').innerHTML;
var parsed = parseInt(counter);
var result = parsed + delta;
document.getElementById('counter').innerHTML = result;
}
}
document.getElementById('minus').onclick = changeCount(-1);
document.getElementById('plus').onclick = changeCount(1);
You can use the same function to modify the counter element and then just pass a negative or positive integer as the parameter to the function, like so:
document.getElementById('minus').onclick = modifyCount(-1);
document.getElementById('plus').onclick = modifyCount(1);
//Just pass the integer into the function to modify the counter element
function modifyCount(val){
const counter = document.getElementById('counter');
counter.innerHTML = parseInt(counter.innerHTML) + val;
}
Possible solution with onclick event:
function count(clicked_id)
{
var counter = document.getElementById('counter').innerHTML;
var parsed = parseInt(counter);
let result = clicked_id == "minus" ? parsed - 1 : parsed + 1;
document.getElementById('counter').innerHTML = result;
}
<button onclick="count(this.id)" id="minus">-</button>
<div id="counter">0</div>
<button onclick="count(this.id)" id="plus">+</button>
You can use the first and only parameter of the click handler, to get the ID of the element. Then use a ternary command to decide, if the result should be incremented or decremented.
function clickHandler(e) {
var counter = document.getElementById('counter').innerHTML;
var parsed = parseInt(counter);
var result = e.target.id === 'plus' ? parsed + 1 : parsed - 1;
document.getElementById('counter').innerHTML = result;
}
document.getElementById('minus').onclick = clickHandler;
document.getElementById('plus').onclick = clickHandler;
You could also rewrite the method to use an if instead of the result variable.
Here's what I would consider an optimized version:
const counterElem = document.getElementById('counter');
function clickHandler(e) {
counterElem.innerHTML =
parseInt(counterElem.innerHTML) +
(e.target.id === 'plus' ? 1 : -1);
}
document.getElementById('minus').onclick = clickHandler;
document.getElementById('plus').onclick = clickHandler;
You could use curried functions.
The following should make your code simple and as required:
function getCounter(multiplier = 1) {
return function () {
var counter = document.getElementById('counter').innerHTML;
var parsed = parseInt(counter);
var result = parsed + (multiplier * 1);
document.getElementById('counter').innerHTML = result;
}
}
document.getElementById('minus').onclick = getCounter(-1);
document.getElementById('plus').onclick = getCounter(); // 1 is the default value
Curried functions are basically, functions that return another function. The inner functions have access to the variables defined in the wrapping function. read more about them here: https://medium.com/javascript-scene/curry-and-function-composition-2c208d774983
I have modified your code to a function, you just need to use that function on the event you want.
function counterFunction(action) {
var counter = document.getElementById('counter').innerHTML;
var parsed = parseInt(counter);
var result = '';
if (action == 'minus') {
result = parsed -1;
}
else if (action == 'plus') {
result = parsed +1;
}
document.getElementById('counter').innerHTML = result;
}
If you need any help please let me know.
In Button tag call the below method in OnClick event
In 'action' parameter , pass the button value as '+' or '-'.
Eg : <button type='button' onClick='return CounterUpdate("+")'>+</Button>
function CounterUpdate(action) {
var counter = document.getElementById('counter').innerHTML;
var parsed = parseInt(counter);
var result =parsed ;
if(action=='+')
{
result = parsed +1;
}
else if(action=='-')
{
result = parsed -1;
}
document.getElementById('counter').innerHTML = result;
}

Call 2 functions in is

I have 2 functions that work fine on their own. Using them in a form. I can call them in one onclick event, however I would like to place both in one script with the first called validate() but only call second function display() if information is correct. So if validate() is called and info not correct they get an alert and returns to form true, if info correct then display() is called. Any help appreciated.
function validate() {
// Get the value of the input field with id="QTY"
var x = document.forms["confirm"]["QTY"].value;
// If x is Not a Number or less than one
if (isNaN(x) || x < 1 ) {
alert("Quantity - Minimum 1 required please");
return true;
}
}
function display()
{
var x=document.confirm.qty.value;
var y=document.confirm.price.value;
var z=document.confirm.total.value;
var confirm = window.confirm('Quantity:' + x + '\nPrice Each: ' + y + '\nTotal Price: ' + z + '\n\nConfirm your order?' );
}if(result)
{
// user has pressed ok
}
else
// user has pressed cancel
{
document.getElementById("myform").reset();
}
It is customary to have validate return true if the validation passes.
function validate() {
// Get the value of the input field with id="QTY"
var x = document.forms["confirm"]["QTY"].value;
// If x is Not a Number or less than one
if (isNaN(x) || x < 1 ) {
alert("Quantity - Minimum 1 required please");
return false;
}
return true;
}
function display()
{
var x=document.confirm.qty.value;
var y=document.confirm.price.value;
var z=document.confirm.total.value;
var confirm = window.confirm('Quantity:' + x + '\nPrice Each: ' + y + '\nTotal Price: ' + z + '\n\nConfirm your order?' );
if(confirm)
{
// user has pressed ok
}
else
// user has pressed cancel
{
document.getElementById("myform").reset();
}
}
if (validate()) { display(); }
If you give us more information about the html and glue code we could help better.

Set cursor at end of string in CKEditor

I wrote the code below to set the first letter to upper case and set the data in CKEditor. The first letter is converting fine, but afterward, the cursor focus is set before the first letter. How can I set the cursor after the character?
CKEDITOR.on('instanceCreated', function (e) {
e.editor.on('contentDom', function () {
e.editor.document.on('keyup', function (event) {
var data = CKEDITOR.instances.editor1.getData();
var str = $(data).text();
var n = str.length;
if (str != null && n == 1) {
CKEDITOR.instances['editor1'].setData(titleCase(str))
function titleCase(string) {
return string.charAt(0).toUpperCase() + string.slice(1);
}
}
});
});
});
this code is work for you :
$(document).ready(function() {
CKEDITOR.on('instanceReady', function(ev) {
ev.editor.focus();
var s = ev.editor.getSelection(); // getting selection
var selected_ranges = s.getRanges(); // getting ranges
var node = selected_ranges[0].startContainer; // selecting the starting node
var parents = node.getParents(true);
node = parents[parents.length - 2].getFirst();
while (true) {
var x = node.getNext();
if (x == null) {
break;
}
node = x;
}
s.selectElement(node);
selected_ranges = s.getRanges();
selected_ranges[0].collapse(false); // false collapses the range to the end of the selected node, true before the node.
s.selectRanges(selected_ranges); // putting the current selection there
});
});

localStorage loadVote when refresh page (broken)

I cannot show voteUp/Down when I refresh page, because if I do voteUp/Down(+1 or -1) and refresh page, this return voteUp/Down (0) again. In this past I was using JSON, but the community recommended without JSON. So I have it, in this moment. Thanks.
var voteUp = document.getElementById('vote-up');
var voteDown = document.getElementById('vote-down');
var handUp = once(function() {
var total = Number(voteUp.innerHTML);
total += 1;
voteUp.innerHTML = total;
saveVote();
});
voteUp.addEventListener('click', handUp);
var handDown = once(function() {
var total = Number(voteDown.innerHTML);
total -= 1;
voteDown.innerHTML = total;
saveVote();
});
voteDown.addEventListener('click', handDown);
function once(fn, context) {
var result;
return function() {
if(fn) {
result = fn.apply(context);
fn = null;
}
return result;
};
}
function saveVote() {
var votes = voteUp, voteDown;
localStorage.setItem('data', votes);
console.log('saveVote');
}
function loadVote() {
var votes = localStorage.getItem('data');
if(!votes){
return;
}
console.log(localStorage.getItem('data'));
}
loadVote();
var voteUp = document.getElementById('vote-up');
function handUp() {
var total = Number(voteUp.innerHTML);
total += 1;
voteUp.innerHTML = total;
}
voteUp.addEventListener('click',handUp,false);
It increments each one value by a click.
There's no such thing as an =+ operator, there is an += operator, however.
+=
Addition assignment.
Also, I'm pretty sure the typeof val is undefined since it's value is never defined in the argument passing of the method.
A variable which's type is undefined can certainly not contain a value which's a number (it's NaN) and thus the error message makes sense.

parseInt() error: invalid argument

I get a javascript error "invalid arguement" when I use parseInt(). What am i doing wrong?
The function is to increase the font size of every element on a frame by 1
<script>
var sizeCounter = 1;
function changeFontSize(){
//var elements = parent.main.document.getElementsByTagName
var myElements = parent.main.document.getElementsByTagName('*')
for (i=0;i<myElements.length;i++){
if(myElements[i].style.fontSize != null){
var elmFontSize = myElements[i].style.fontSize + "";
elmFontSize.replace("px","");
if(elmFontSize != "") {
var elmFontSizeNum = parseInt(elmFontSize);
}
var resultSize = elmFontSizeNum + sizeCounter;
myElements[i].style.fontSize = resultSize + "px";
//alert(myElements[i].className)
}
sizeCounter++;
}
}
</script>
There's a lot wrong. Here's a suggestion for simplifying/rewriting your function:
function changeFontSize(sizeCounter){
sizeCounter = sizeCounter || 1;
var myElements = document.getElementsByTagName('*'), currentFontSize = 0;
for (i=0;i<myElements.length;i++){
var fsNow = getStyle(myElements[i],'font-size');
if (fsNow){
currentFontSize = Number(fsNow.replace(/[^\d]/g,''));
myElements[i].style.fontSize = (currentFontSize + sizeCounter) + 'px';
}
}
}
Where getStyle is:
function getStyle(el,styleProp)
{
el = /string/i.test(typeof el) ? document.getElementById(el) : el;
if (!el){return null;}
var result;
if (el.currentStyle){
return el.currentStyle[styleProp];
}
else if (window.getComputedStyle){
return document.defaultView.getComputedStyle(el,null)
.getPropertyValue(styleProp);
}
return null;
}
See this jsfiddle
parseInt takes a string as first parameter, you may want to make sure that elmFontSize is actually a string using typeof(elmFontSize). If it's not a string, you can transform it into a string before calling the parseInt function.
You only handle "px" and fontsize isn't necessarily a "px" value. If it is for example "em" then parseInt will fail because it is trying to convert a non number value.

Categories

Resources