How to use same function for different Id's in JavaScript? - javascript

function add() {
var txtNumber = document.getElementById("book");
var newNumber = parseInt(book.value) + 1;
book.value = newNumber;
}
function sub() {
var txtNumber = document.getElementById("book");
var newNumber = parseInt(book.value) - 1;
book.value = newNumber;
}
<div class="range">
<label>Book</label>
subtract<input type="text" id="book" value="0" min="0"> Add
</div>
<div class="range">
<label>Pen</label>
subtract<input type="text" id="pen" value="0" min="0"> Add
</div>
How to use same function for different Id's?
I tried using "this" keyword for selecting a current Id but it didn't work...
and i am trying do this in javascript only instead of jquery.

You could use the id as parameter for calling the functions. Inside take the value and convert it to number and if falsey, like NaN take a zero as value.
function add(id) {
var element = document.getElementById(id),
value = +element.value || 0;
element.value = value + 1;
}
function sub(id) {
var element = document.getElementById(id),
value = +element.value || 0;
value--;
if (value < 0) {
value = 0;
}
element.value = value;
}
<div class="range">
<label>Book</label>
<i class="fa fa-minus-circle" aria-hidden="true">-</i><input type="text" id="book" value="0" min="0">
<i class="fa fa-plus-circle" aria-hidden="true">+</i>
</div>
<div class="range">
<label>Pen</label>
<i class="fa fa-minus-circle" aria-hidden="true">-</i><input type="text" id="pen" value="0" min="0">
<i class="fa fa-plus-circle" aria-hidden="true">+</i>
</div>
Input free version with an object as storage.
function add(id) {
storage[id] = storage[id] || 0;
document.getElementById(id).innerHTML = ++storage[id];
}
function sub(id) {
storage[id] = storage[id] || 0;
--storage[id];
if (storage[id] < 0) {
storage[id] = 0;
}
document.getElementById(id).innerHTML = storage[id];
}
var storage = {};
<label>Book</label> - <span id="book">0</span> +<br>
<label>Pen</label> - <span id="pen">0</span> +</i>

pass id name in function like add('book') or add('pen') and this use in function call in javascript
and also use txtNumber instead of book in java script
function add(id) {
var txtNumber = document.getElementById(id);
var newNumber = parseInt(txtNumber.value) + 1;
txtNumber.value = newNumber;
}
function sub(id) {
var txtNumber = document.getElementById(id);
var newNumber = parseInt(txtNumber.value) - 1;
txtNumber.value = newNumber;
}
<div class="range">
<label>Book</label>
subtract<input type="text" id="book" value="0" min="0"> Add
</div>
<div class="range">
<label>Pen</label>
subtract<input type="text" id="pen" value="0" min="0"> Add
</div>

Related

Javascript cant get my value and calculate in html

Im trying to do simple calculation for the fee ,but its doesn't work ,there's no error in the code. Did I miss something in the script ?
<script type="text/javascript">
var bwm = 7.9;
var bswk = 14;
var bsbh = 15;
var wm = 2;
var swk = 11;
var sbh = 12;
var kilo, overkilo, f;
var s = document.getElementById('place');
var place = s.options[s.selectedIndex].value;
var k = document.getElementById('kilo').value;
var tot;
function quote() {
f = document.getElementById('theform');
f.reset();
document.getElementById('calc').onclick = function() {
if (place == 'swk') {
(k * swk) + bswk = tot;
} else if (place == 'sbh') {
(k * sbh) + bsbh = tot;
} else {
(k * wm) + bwm = tot;
}
document.getElementById('tot').value = 'RM ' + parseFloat;
}
}
</script>
<form id="theform" action="#">
<div>
<label for="place">Choose Destination :</label>
<select id="place" onChange="quote()">
<option value="swk">Sarawak</option>
<option value="sbh">Sabah</option>
<option value="wm">WestMalaysia</option>
</select>
</div>
<div>
<label for="kilo">Amount of KG :</label>
<input id="kilo" type="text">
</div>
<div>
<label>Total :</label>
<input id="tot" type="text" readonly="readonly">
</div>
<div>
<label></label>
<input id="calc" type="button" value="calculate">
<input id="r" type="reset" value="clear">
</div>
</form>
The clear works fine ,but the calculate button won't work even i have input the KG and select a option to calculate .
You need to move the definition of the click handler outside of the change handler, unless the click handler would be defined only when an option changes and also it would be defined on every option change which is unnecessary.
Grab all the required values inside the click handler otherwise you would not have the updated values.
And you also need to set the selected index after resetting the form otherwise the change of option would not be visible.
const
bwm = 7.9,
bswk = 14,
bsbh = 15,
wm = 2,
swk = 11,
sbh = 12;
function quote(e) {
const selIndex = e.target.selectedIndex;
document.getElementById("theform").reset();
document.getElementById("place").selectedIndex = selIndex;
}
document.getElementById("calc").onclick = function () {
const select = document.getElementById("place");
const place = select.options[select.selectedIndex].value;
const k = document.getElementById("kilo").value;
if (!k) {
return;
}
let tot;
if (place === "swk") {
tot = k * swk + bswk;
} else if (place === "sbh") {
tot = k * sbh + bsbh;
} else {
tot = k * wm + bwm;
}
document.getElementById("tot").value = "RM " + tot;
};
<form id="theform" action="#">
<div>
<label for="place">Choose Destination :</label>
<select id="place" onChange="quote(event)">
<option value="swk">Sarawak</option>
<option value="sbh">Sabah</option>
<option value="wm">WestMalaysia</option>
</select>
</div>
<div>
<label for="kilo">Amount of KG :</label>
<input id="kilo" type="text">
</div>
<div>
<label>Total :</label>
<input id="tot" type="text" readonly="readonly">
</div>
<div>
<label></label>
<input id="calc" type="button" value="calculate">
<input id="r" type="reset" value="clear">
</div>
</form>
Instead of resetting the form you could also update the calculated value every time the option changes.
const
bwm = 7.9,
bswk = 14,
bsbh = 15,
wm = 2,
swk = 11,
sbh = 12;
document.getElementById("calc").onclick = handleClick;
function handleClick() {
const select = document.getElementById("place");
const place = select.options[select.selectedIndex].value;
const k = document.getElementById("kilo").value;
if (!k) {
return;
}
let tot;
if (place === "swk") {
tot = k * 10 + 10;
} else if (place === "sbh") {
tot = k * sbh + bsbh;
} else {
tot = k * wm + bwm;
}
document.getElementById("tot").value = "RM " + tot;
}
<form id="theform" action="#">
<div>
<label for="place">Choose Destination :</label>
<select id="place" onChange="handleClick()">
<option value="swk">Sarawak</option>
<option value="sbh">Sabah</option>
<option value="wm">WestMalaysia</option>
</select>
</div>
<div>
<label for="kilo">Amount of KG :</label>
<input id="kilo" type="text">
</div>
<div>
<label>Total :</label>
<input id="tot" type="text" readonly="readonly">
</div>
<div>
<label></label>
<input id="calc" type="button" value="calculate">
<input id="r" type="reset" value="clear">
</div>
</form>
I Removed the left-hand side for assignment and set the value.
You defined the var for all instead of that you can use const.
Also form reset not required.
Here is solution of your code
<html>
<script type="text/javascript">
const bwm = 7.9;
const bswk = 14;
const bsbh = 15;
const wm = 2;
const swk = 11;
const sbh = 12;
let kilo, overkilo, f;
var tot;
function quote() {
const s = document.getElementById('place');
const place = s.options[s.selectedIndex].value;
const k = document.getElementById('kilo').value;
f = document.getElementById('theform');
// f.reset();
document.getElementById('calc').onclick = function() {
if (place == 'swk') {
tot = (k * swk) + bswk;
} else if (place == 'sbh') {
tot = (k * sbh) + bsbh;
} else {
tot = (k * wm) + bwm;
}
document.getElementById('tot').value = 'RM ' + parseFloat(tot);
}
}
</script>
<form id="theform" action="#">
<div>
<label for="place">Choose Destination :</label>
<select id="place" onChange="quote()">
<option value="swk">Sarawak</option>
<option value="sbh">Sabah</option>
<option value="wm">WestMalaysia</option>
</select>
</div>
<div>
<label for="kilo">Amount of KG :</label>
<input id="kilo" type="text">
</div>
<div>
<label>Total :</label>
<input id="tot" type="text" readonly="readonly">
</div>
<div>
<label></label>
<input id="calc" type="submit" value="calculate">
<input id="r" type="reset" value="clear">
</div>
</form>
</html>

How should I put limit inside for loop using if condition using javascript

My goal is that only 15 quantities of input elements can be accepted, once the user enters 16 it should say that only 15 input elements is allowed. However I don't know how will I do this. I tried putting condition inside for but it is not not working. I am a little bit confused on this
Here is my HTML code
<div class="form-group">
<label> Quantity: </label>
<input class="form-control" name="quantity" type="number" id="get_Elem"
required>
<br>
<input type="button" id="sb_add_ctrl" name="is_Sub" class="btn btn-
primary" value="Add Control Number">
</div>
<div class="form-group" name="parent" id="parent"></div>
Here is my JS code
$(document).on('click', '#sb_add_ctrl', function() {
var element = $('#get_Elem').val();
var input;
var parent = $(document.getElementById("parent"));
var value = $('#sel_control_num').val();
functionPopulate(parent);
if (isNaN(element)) {
return;
}
for (var i = 0; i < element; i++) {
if(should I do it here??){
}
value = value.replace(/(\d+)$/, function(match, element) {
const nextValue = ++match;
return ('0' + nextValue).slice(1);
});
document.getElementById("parent").style.padding = "5px 0px 0px 0px";
document.getElementById("parent").innerHTML += '<br><input type="text"
value="' + value +
'" class="form-control" name="get_Input_show[]" required>'
}
});
You can check if the element value is < 16 if yes then only add html else show error message.
Demo Code :
$(document).on('click', '#sb_add_ctrl', function() {
var element = $('#get_Elem').val();
var input;
//var value = $('#sel_control_num').val();
var value = 12;
//functionPopulate(parent);
if (isNaN(element)) {
return;
}
//check if elemnt value if < 16
if (element < 16) {
$("#parent").empty() //empty div
for (var i = 0; i < element; i++) {
/* value = value.replace(/(\d+)$/, function(match, element) {
const nextValue = ++match;
return ('0' + nextValue).slice(1);
});*/
document.getElementById("parent").style.padding = "5px 0px 0px 0px";
document.getElementById("parent").innerHTML += '<br><input type="text" value = "' + value + '" class="form-control" name="get_Input_show[]" required>';
}
} else {
alert("only 15") //show error
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="form-group">
<label> Quantity: </label>
<input class="form-control" name="quantity" type="number" id="get_Elem" required>
<br>
<input type="button" id="sb_add_ctrl" name="is_Sub" class="btn btn-
primary" value="Add Control Number">
</div>
<div class="form-group" name="parent" id="parent"></div>
There are two ways in which you can restrict it
You can use maxLength property of an input tag, which will restrict the user to input the 16th character.
You can keep checking the value in the input field and show error if the length is more than 15 character. To do this you can use onkeypress event on input, like
HTML
<input type="text" id="test" onkeypress="test()" />
JS:
<script>
function test() {
alert('Hi')
}
</script>

Connect clicked button value and function in JS

I'm beginner in JS.
I have 2 functions. How to do :
if I click first button, make first function work, if I click second button, make second function work?
Apply pressed button value to function and then apply it to input field.
Example: when I type 'ABC' using Caesar Cipher , it would return 'NOP', when I type 'ABC' using my cipher (or any other), it would return 'BCD' (or any other value, it depends on which cipher is selected). Thanks everyone in advance
My Js and Html code below:
<div class="container">
<div class="row">
<form class="col s12 m12 l12">
<h2>JS Encription</h2>
<div class="row">
<div class="input-field col s5 m5 l5">
<input id="field1" placeholder="Type you text here" id="first_name" type="text" class="validate">
<label for="first_name">Input</label>
</div>
<div class="input-field col s5 m5 l5">
<input id="field2" disabled placeholder="Result is shown here" id="first_name" type="text" class="validate">
<label for="first_name">Output</label>
</div>
</div>
</form>
</div>
<div class="row switchBtns">
<div class="col s12 m12 l12">
<div id="caesarButton" class="col s3 m3 l3 ">
<a class="waves-effect waves-light btn-small">Caesar Cipher</a>
</div>
<div id="mineButton" class="col s3 m3 l3 ">
<a class="waves-effect waves-light btn-small">My Cipher</a>
</div>
<div class="col s3 m3 l3 ">
<a class="waves-effect waves-light btn-small">3rd Variant</a>
</div>
<div class="col s3 m3 l3 ">
<a class="waves-effect waves-light btn-small">4th Variant</a>
</div>
</div>
</div>
</div>
and JS code
// CAESAR
$("#caesarButton").click(function() {
var clicked = $(this).val();
$('#field1').val(encryp(clicked)).val();
});
$('#field1').on('keyup keypress blur', function () {
var textvalue = $(this).val();
$('#field2').val(encryp(textvalue)).val();
});
function encryp(tekst) {
var result = "";
var str = tekst.toUpperCase();
for (var i=0; i<str.length ; i++) {
var ascii = str[i].charCodeAt();
if(ascii>=65 && ascii<=77) {
result+=String.fromCharCode(ascii+13);
}
else if(ascii>=78 && ascii<=90) {
result+=String.fromCharCode(ascii-13);
}
else {
result+=" ";
}
}
return result ;
}
//MINE
$("#mineButton").click(function() {
var clicked = $(this).val();
$('#field1').val(encryp(clicked)).val();
});
$('#field1').on('keyup keypress blur', function () {
var textvalue = $(this).val();
$('#field2').val(encryp(textvalue)).val();
});
function encryp(tekst) {
var result = "";
var str = tekst.toUpperCase();
for (var i=0; i<str.length ; i++) {
var ascii = str[i].charCodeAt();
if(ascii>=65 && ascii<=77) {
result+=String.fromCharCode(ascii+3);
}
else if(ascii>=78 && ascii<=90) {
result+=String.fromCharCode(ascii-3);
}
else {
result+=" ";
}
}
return result ;
}
I whipped up a simplified example of contextually switching input handler functions for you, here ya go:
// use an object as a key-value store for your functions
var funcs = {
caesar: encryp1, // i dont know if i got these the right way around :D
mine: encryp2
}
// store which funciton is currently selected in a variable
var selected = "caesar"
// call this function just to show the default selected function
determineOutput()
// CAESAR
$("#caesarButton").click(function() {
console.log("caesar button clicked!")
// here assign which function to use
selected = "caesar"
determineOutput()
});
//MINE
$("#mineButton").click(function() {
console.log("mine button clicked!")
// here assign which function to use
selected = "mine"
determineOutput()
});
$('#field1').on('keyup keypress blur', function () {
// this function is alled every time one of the events
// listed happens on the #field1 element
determineOutput()
});
function determineOutput(){
var textvalue = $('#field1').val();
//use the function currently selected by addressing it with
// [] on the funcs object
var correctFunction = funcs[selected]
// then call the selected function with the input text
$('#field2').val(correctFunction(textvalue));
// show the user which cipher we're using
$("#currentCipher").html("current cipher:" + selected)
}
function encryp1(tekst) {
var result = "";
var str = tekst.toUpperCase();
for (var i=0; i<str.length ; i++) {
var ascii = str[i].charCodeAt();
if(ascii>=65 && ascii<=77) {
result+=String.fromCharCode(ascii+13);
}
else if(ascii>=78 && ascii<=90) {
result+=String.fromCharCode(ascii-13);
}
else {
result+=" ";
}
}
return result ;
}
function encryp2(tekst) {
var result = "";
var str = tekst.toUpperCase();
for (var i=0; i<str.length ; i++) {
var ascii = str[i].charCodeAt();
if(ascii>=65 && ascii<=77) {
result+=String.fromCharCode(ascii+3);
}
else if(ascii>=78 && ascii<=90) {
result+=String.fromCharCode(ascii-3);
}
else {
result+=" ";
}
}
return result ;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
<input id="field1" placeholder="Type you text here" type="text">
<label for="field1">Input</label>
</div>
<div>
<input id="field2" disabled placeholder="Result is shown here" type="text" class="validate">
<label for="field2">Output</label>
</div>
<p id="currentCipher"></p>
<button id="caesarButton">
Caesar Cipher
</button>
<button id="mineButton">
My Cipher
</button>

Subtract t1 from t2 then add it to already exist t3 and display in t3 in javascript

I want txtFirstNumberValue - txtSecondNumberValue and then add it already exists txtThirdNumberValue value but in my case, it is not working.
function sub() {
var txtFirstNumberValue = document.getElementById('payment_image').value;
var txtSecondNumberValue = document.getElementById('pay_amount').value;
var txtThirdNumberValue = document.getElementById('pay_balance').value;
if (txtFirstNumberValue == "")
txtFirstNumberValue = 0;
if (txtSecondNumberValue == "")
txtSecondNumberValue = 0;
var result = parseInt(txtFirstNumberValue) - parseInt(txtSecondNumberValue);
if (!isNaN(result)) {
document.getElementById('pay_balance').value += result;
}
}
<div class="input-box">
<span>Amount</span>
<input placeholder="Payment Amount" type="text" name="payment_image" onkeyup="sub();" id="payment_image" class="number">
</div>
<div class="input-box">
<span>Expences</span>
<input placeholder="Expenses" type="text" name="expenses" id="pay_amount" onkeyup="sub();" class="number">
</div>
<div class="input-box">
<span>Balance</span>
<input placeholder="Balance" value="15" readonly="readonly" type="text" name="pay_balance" id="pay_balance" class="number">
</div>
txtThirdNumberValue is coming dynamically from PHP code
call function second text onblur event
and change here
document.getElementById('pay_balance').value = parseInt(txtThirdNumberValue) + result;
function sub() {
var txtFirstNumberValue = document.getElementById('payment_image').value;
var txtSecondNumberValue = document.getElementById('pay_amount').value;
var txtThirdNumberValue = document.getElementById('pay_balance').value;
if (txtFirstNumberValue == "")
txtFirstNumberValue = 0;
if (txtSecondNumberValue == "")
txtSecondNumberValue = 0;
var result = parseInt(txtFirstNumberValue) - parseInt(txtSecondNumberValue);
//alert(result);
if (!isNaN(result)) {
document.getElementById('pay_balance').value = parseInt(txtThirdNumberValue) + result;
}
}
<div class="input-box">
<span>Amount</span>
<input placeholder="Payment Amount" type="text" name="payment_image" id="payment_image" class="number">
</div>
<div class="input-box">
<span>Expences</span>
<input placeholder="Expenses" type="text" name="expenses" id="pay_amount" onblur="sub();" class="number">
</div>
<div class="input-box">
<span>Balance</span>
<input placeholder="Balance" value="15" readonly="readonly" type="text" name="pay_balance" id="pay_balance" class="number">
</div>
You need to convert already existing value from string to number before adding result to it. Here's how to do it:
function sub() {
var txtFirstNumberValue = document.getElementById('payment_image').value;
var txtSecondNumberValue = document.getElementById('pay_amount').value;
var txtThirdNumberValue = document.getElementById('pay_balance').value;
if (txtFirstNumberValue == "")
txtFirstNumberValue = 0;
if (txtSecondNumberValue == "")
txtSecondNumberValue = 0;
var result = parseInt(txtFirstNumberValue) - parseInt(txtSecondNumberValue);
if (!isNaN(result)) {
var existing = parseInt(document.getElementById('pay_balance').value);
var newResult = result + existing;
document.getElementById('pay_balance').value = newResult;
}
}
<div class="input-box">
<span>Amount</span>
<input placeholder="Payment Amount" type="text" name="payment_image" onkeyup="sub();" id="payment_image" class="number">
</div>
<div class="input-box">
<span>Expences</span>
<input placeholder="Expenses" type="text" name="expenses" id="pay_amount" onkeyup="sub();" class="number">
</div>
<div class="input-box">
<span>Balance</span>
<input placeholder="Balance" value="15" readonly="readonly" type="text" name="pay_balance" id="pay_balance" class="number">
</div>
I don't know what you are trying to do, but you should parseInt your 3rd value and then add it back.
Here is what you did wrong.
One more thing you should use radix value in your parseInt
function sub() {
var txtFirstNumberValue = document.getElementById('payment_image').value;
var txtSecondNumberValue = document.getElementById('pay_amount').value;
var txtThirdNumberValue = document.getElementById('pay_balance').value;
if (txtFirstNumberValue == "")
txtFirstNumberValue = 0;
if (txtSecondNumberValue == "")
txtSecondNumberValue = 0;
var result = parseInt(txtFirstNumberValue, 10) - parseInt(txtSecondNumberValue, 10);
if (!isNaN(result)) {
//This is what you should be doing. You didn't convert the value to int
//You were concatinating it as a string
var payVal = parseInt(document.getElementById('pay_balance').value, 10);
payVal += result;
document.getElementById('pay_balance').value = payVal;
}
}
<div class="input-box">
<span>Amount</span>
<input placeholder="Payment Amount" type="text" name="payment_image" onkeyup="sub();" id="payment_image" class="number">
</div>
<div class="input-box">
<span>Expences</span>
<input placeholder="Expenses" type="text" name="expenses" id="pay_amount" onkeyup="sub();" class="number">
</div>
<div class="input-box">
<span>Balance</span>
<input placeholder="Balance" value="15" readonly="readonly" type="text" name="pay_balance" id="pay_balance" class="number">
</div>

Javascript Basic Increment and Decrement

Why isn't dec() decreasing the value?
<div id="variableTest">8</div>
<label id="incButton" onclick="inc()">+</div> </br>
<label id="decButton" onclick="dec()">-</div> </br>
​
function dec() {
var testDec = document.getElementById("variableTest").innerHTML;
testDec--;
}
function inc() {
var testInc = document.getElementById("variableTest").innerHTML;
testInc++;
}​
http://jsfiddle.net/fv6VA/8/
element.innerHTML returns a string, not a number. You should use something like this:
var element = document.getElementById("variableTest");
element_number = parseFloat(element.innerHTML);
element_number++;
element.innerHTML = element_number;
Essentially you have made a copy of innerHTML, and are just decrementing it in javascript memory. You haven't actually set the innerHTML of the variableTest node.
function dec() {
var testDec = document.getElementById("variableTest").innerHTML;
testDec--;
document.getElementById("variableTest").innerHTML = testDec;
}
UPDATE
Also, your HTML is messed up. You need to close your label properly
<div id="variableTest">8</div>
<label id="incButton" onclick="inc()">+</label> </br>
<label id="decButton" onclick="dec()">-</label> </br>
<div class="container">
<input type="button" onclick="decrementValue()" value="-" />
<input type="text" name="quantity" value="1" maxlength="2" max="10" size="1" id="number" />
<input type="button" onclick="incrementValue()" value="+" />
</div>
<script type="text/javascript">
function incrementValue()
{
var value = parseInt(document.getElementById('number').value, 10);
value = isNaN(value) ? 0 : value;
if(value<10){
value++;
document.getElementById('number').value = value;
}
}
function decrementValue()
{
var value = parseInt(document.getElementById('number').value, 10);
value = isNaN(value) ? 0 : value;
if(value>1){
value--;
document.getElementById('number').value = value;
}
}
</script>

Categories