Adding two numbers instantly using javascript - javascript

I am using visual studio 2008 for developing a webpage. The problem description is like this : I have 3 textboxes in the webpage one is "Price" second one is "quantity" and third one is "Amount". I want to get price*quantity=Amount.
I dont want to have any buttonclicks while doing so. First I am entering value into price then im entering value to quantity, as soon as I move the cursor out of quantity I want the answer printed in third text box automatically without button click. I want to do it in javascript.

I think what you mean is the blur event, which gets triggered when a textinput loses its focus (if you click outside of it).
Bind it to your textarea like this:
price.addEventListener("blur", function( event )
{
// do it
}, true);
Fiddle: http://jsfiddle.net/egLzz5gb/

You can use the change event on the input fields. This event is fired every time the value in the input is changed. I don't know what your form looks like, but this code should give you a general idea how to do it:
quantityInput.addEventListener('change', function(){
amountInput.value = parseInt(quantityInput.value) * parseInt(priceInput.value);
});
If you're working with decimal numbers, use parseFloat() instead of parseInt(), be careful though, and preferably use Math.round(), as calculations with floating point are not 100% precise.

Price: <input type="text" id="price">
Quantity: <input type="text" id="quantity" onkeyup="myFunction()">
Amount: <input type="text" id="amount"">
<script>
function myFunction() {
var p = document.getElementById("price");
var q = document.getElementById("quantity");
var a = document.getElementById("amount");
a.value = p.value * q.value ;
}

Related

Homemade "Captcha" System - One minor glitch in javascript, can't enable submit button

So basically what I'm trying to do as a measure of security (and a learning process) is to my own "Capthca" system. What happens is I have twenty "label's" (only one shown below for brevity), each with an ID between 1 and 20. My javascript randomly picks one of these ID's and makes that picture show up as the security code. Each label has its own value which corresponds to the text of the captcha image.
Also, I have the submit button initially disabled.
What I need help with is figuring out how to enable the submit button once someone types in the proper value that matches the value listed in the HTML label element.
I've posted the user input value and the ID's value and even when they match the javascript won't enable the submit button.
I feel like this is a really really simple addition/fix. Help would be much much appreciated!!!
HTML code
<div class="security">
<label class="captcha enabled" id="1" value="324n48nv"><img src="images/security/1.png"></label>
</div>
<div id="contact-div-captcha-input" class="contact-div" >
<input class="field" name="human" placeholder="Decrypt the image text here">
</div>
<input id="submit" type="submit" name="submit" value="Send the form" disabled>
Javascript code
//Picks random image
function pictureSelector() {
var number = (Math.round(Math.random() * 20));
//Prevents zero from being randomly selected which would return an error
if (number === 0) {
number = 1;
};
console.log(number);
//Set the ID variable to select which image gets enabled
pictureID = ("#" + number);
//If the siblings have a class of enabled, remove it
$(pictureID).siblings().removeClass("enabled");
//Add the disabled class to all of the sibling elements so that just the selected ID image is showing
$(pictureID).siblings().addClass("disabled");
//Remove the disabled class from the selected ID
$(pictureID).removeClass("disabled");
//Add the enabled class to the selected ID
$(pictureID).addClass("enabled");
};
//Calls the pictureSelector function
pictureSelector();
//Gets the value of the picture value
var pictureValue = $(pictureID).attr("value");
console.log(pictureValue);
//Gets the value of the security input box as the user presses the keys and stores it as the variable inputValue
$("#contact-div-captcha-input input").keyup(function(){
var inputValue = $("#contact-div-captcha-input input").val();
console.log(inputValue);
});
console.log($("#contact-div-captcha-input input").val());
//Checks to see if the two values match
function equalCheck() {
//If they match, remove the disabled attribute from the submit button
if ($(pictureValue) == $("#contact-div-captcha-input input").val()) {
$("#submit").removeAttr("disabled");
}
};
equalCheck();
UPDATE
Fiddle here
UPDATE #2
$("#contact-div-captcha-input input").keyup(function(){
var inputValue = $("#contact-div-captcha-input input").val();
console.log(inputValue);
if (pictureValue === inputValue) {
$("#inputsubmit").removeAttr("disabled");
}
});
So I got it working 99.9%, now the only problem is that if someone were to backspace or delete the correct value they have inputted, the submit button does not then change back to disabled. Any pointers?
Known issue.
Give your button a name OTHER THAN submit. That name interferes with the form's submit.
EDIT
A link was requested for this -- I don't have a link for pure JavaScript, but the jQuery docs do mention this issue:
http://api.jquery.com/submit/
Forms and their child elements should not use input names or ids that
conflict with properties of a form, such as submit, length, or method.
Name conflicts can cause confusing failures. For a complete list of
rules and to check your markup for these problems, see DOMLint.
EDIT 2
http://jsfiddle.net/m55asd0v/
You had the CSS and JavaScript sections reversed. That code never ran in JSFiddle.
You never re-called equalCheck. I added a call to your keyUp handler.
For some reason you wrapped pictureValue inside a jQuery object as $(pictureValue) which couldn't have possibly done what you wanted.
Basic debugging 101:
A console.log inside of your equalCheck would have shown you that function was only called once.
A console log checking the values you were comparing would have shown
that you had the wrong value.
Basic attention to the weird highlighting inside of JSFiddle would have shown you had the code sections in the wrong categories.

Can I change dyanmic javascript variable depending on user form input?

My question here is if there is a way to change the dynamic price calculation depending on the name a user enters in the input field.
I have code that works very well for calculating a dynamic price in an html form. Here is the code:
Using this input:
<input class="typeahead" type="text" placeholder="Amount" name="Amount"/>
My Javascript then calculates price:
jQuery("input[name='Amount']").change(function () {
if (isNaN(parseFloat(this.value)) || !isFinite(this.value)) {
jQuery(this).val('');
return false;
}
var calc = parseFloat(this.value) * 0.95;
jQuery(this).parents("form").find("input[name='price']").val(calc);
});
That by itself works fantastic. It calculates the amount by .95 and then assigns that value as price.
If I add this into the form:
<input class="stores typeahead" type="text" placeholder="Stores" name="name"/>
What can I do here to be able to calculate the price at different values depending on the store name. For example, if someone enters McDonalds, I want it to calculate at .90. If someone enters Target, I want it to calculate at .92. The previous javascript cannot accomplish this because it calculates everything at .95 instead of being able to change depending on the store entered.
I would prefer to accomplish this with javascript because I'm not very skilled with php.
You can create a Javascript object for this.
var stores = {
"McDonalds" : .90,
"Target" : .92,
}
var storeName = jQuery(this).parents("form").find("input[name='name']").val();
console.log(stores[storeName]); //Output the store cost to console.
Though I think the jQuery lookup function is questionable. I'm sure there is a better way to select that textbox. But that's the general concept you're looking for.

Force iOS numeric keyboard with custom / currency pattern

Is there a possiblity to force an iOS-device to show the numeric keyboard while using a custom pattern as input type?
my input pattern:
<input id="price" class="numeric" pattern="\d+((\.|,)\d{1,2})?" name="price"
title="" data-mini="true" data-clear-btn="true" autocomplete="off" autofocus />
I want to type a currency value like '14.99' and show up a keyboard with access to numbers on the iOS device
<input type='number' />
<input pattern='[0-9]*' />
<input pattern='[\d]*' />
are all missing the decimal sign and/or are not validating as number when adding a decimal sign. An alternative way could be a javascript function which is creating the decimal sign on the right place, like pressing 1->2->9->9 in this order creates on keypress() 0.01->0.12->1.29->12.99,
but this requires the input field to be type='text' --> obvious problem here is that the text keyboard is showed when focussing the input field.
How can I solve this issue?
EDIT
Environment:
JQM 1.3.2
jquery 1.8.2
For now, JavaScript is the only solution. Here's the simplest way to do it (using jQuery):
HTML
<input type="text">
JavaScript
$('input[type="text"]').on('touchstart', function() {
$(this).attr('type', 'number');
});
$('input[type="text"]').on('keydown blur', function() {
$(this).attr('type', 'text');
});
The idea is simple. The input starts off and ends up with type="text", but it briefly becomes type="number" on the touchstart event. This causes the correct iOS keyboard to appear. As soon as the user begins to enter any input or leave the field, the input becomes type="text" once again, thus circumventing the validation.
There's one downside to this method. When the user returns to an input that has already been filled out, the input will be lost (if it doesn't validate). This means the user won't be able to go back and edit previous fields. In my case, this isn't all that bad because the user may want to use the calculator over and over again with different values, so automatically deleting the input will save them a few steps. However, this may not be ideal in all cases.
It looks like Mobile Safari supports the new HTML5 input type attributes of email, number, search, tel, and url. These will switch the keyboard that is displayed. See the type attribute.
So for example, you could do this:
<input type="number" />
And when the input box has focus, the number keyboard is shown (as if the user had the full keyboard and hit the "123" button.
If you really only want numbers, you could specify:
<input type="tel" />
And then the user would get the phone number dialing keypad.
I know this works with Mobile Safari -- I only assume it will work with UIWebView.
http://conecode.com/news/2011/12/mobile-safari-uiwebview-input-types/
I made this little snippet to achieve what you want and I've tested it on iPhone 5 v7.0.3
I used e.which to read CharCode entered and then push it into an array (before) which represents digits before decimal mark and another array (after) to move values from (before) array past the decimal mark.
It might look complicated, due to my humble programming skills.
1) Code demo - 2) Currency conversion demo
HTML:
<input type="tel" id="number" />
JS
Variables and functions:
// declare variables
var i = 0,
before = [],
after = [],
value = [],
number = '';
// reset all values
function resetVal() {
i = 0;
before = [];
after = [];
value = [];
number = '';
$("#number").val("");
$(".amount").html("");
}
// add thousand separater
function addComma(num) {
return num.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
}
Main code:
// listen to keyup event
$("#number").on("keyup", function (e, v) {
// accept numbers only (0-9)
if ((e.which >= 48) && (e.which <= 57)) {
// convert CharCode into a number
number = String.fromCharCode(e.which);
// hide value in input
$(this).val("");
// main array which holds all numbers
value.push(number);
// array of numbers before decimal mark
before.push(value[i]);
// move numbers past decimal mark
if (i > 1) {
after.push(value[i - 2]);
before.splice(0, 1);
}
// final value
var val_final = after.join("") + "." + before.join("");
// show value separated by comma(s)
$(this).val(addComma(val_final));
// update counter
i++;
// for demo
$(".amount").html(" " + $(this).val());
} else {
// reset values
resetVal();
}
});
Reset:
// clear arrays once clear btn is pressed
$(".ui-input-text .ui-input-clear").on("click", function () {
resetVal();
});
Result:
I think that you can use the same approach that I suggested to Ranjan.
Using a textfield like a buffer. First you need to detect when the keyboard appears and check if the first responder is the webview. Then you become a textview as the first responder.
When you are setting the text inside the input of the webview, you can add some logic to validate the number.
Here is a link of my example project with the solution, in your case you don't need change the inputView. But the approach is the same, use a Man in the middle.
Cant comment on https://stackoverflow.com/a/19998430/6437391 so posting as a separate answer...
This is the same idea as https://stackoverflow.com/a/19998430/6437391 but instead of switching the type, its the pattern that's switched.
This has the effect of not clearing the value on the textfield on focus when value does not match numeric format, for example, if the value has separators( 1,234.56 ).
$('input[type="text"]').on('touchstart', function() {
$(this).attr('pattern', '[0-9]*');
});
$('input[type="text"]').on('focus', function() {
$(this).attr('pattern', actualpattern);
});

How to update 2 textboxes with javascript?

How can I update a multiple textboxes value with Javascript, when user change the value of textboxes,
and I have a value already on those textboxes?
Am I doing in the right track on the code below?
<input type="text" id="amount_textbox" onChange="UpdateValue()" value="100">
<input type="text" id="amount_textbox" onChange="UpdateValue()" value="200">
function UpdateValue()
{
//alert ("you have changed the textbox...");
var x = document.getElementById('amount_textbox').value;
document.getElementById("amount_textbox").setAttribute("value", x);
document.getElementById('amount_textbox').value = x;
}
That function is working only for the first textbox, the second one can not update, how can I make other textbox work?
in jquery
$("#text").val("my new value");
in javascript
document.getElementById("text").setAttribute("value", "my new value");
document.getElementById('text').value = 'Blahblah';
First of all, I'm not sure why you'd want to set the value of the textarea(?) to itself - doesn't quite make sense, but here's the code nevertheless.
function checkTotal()
{
var tbox = document.getElementById('ammount_textbox');
var val = tbox.innerHTML;
tbox.innerHTML = val;
}
Your event handler is onClick, but it seems like you want to prevent changes? A click is not a change to the content of a form text box. Perhaps you want onChange?
change your onClick to onKeyup. With textareas, I have been able to access the value using just the value. Since the content is between opening and closing tags, you might be able to use the javascript innerHTML property ("That works with the button tag instead of value"). Good Luck!
function UpdateValue()
{
alert ("you have changed the textbox...");
var x = document.getElementById('amount_textbox').value;
document.getElementById("amount_textbox").setAttribute("value", x);
document.getElementById('amount_textbox').value = x;
}

Real time updating of values on a form

Slightly related to my other question (which was answered) here, I was wondering if the following was possible (it likely is and very basic but I'm a bit noobish at JavaScript)!
So I have 2 input fields where the user types something into a form. They press "calculate" and then the function totals up what they have entered and then calculates 1,2 and 3% for each value respectively. It looks something like this:
input 1%value
input 2%value
input 3%value
total total
Is there a way for me to be able to update the form in real time? So by this I mean, as soon as the user enters a value into a field the function automatically starts updating the values such as total etc? How would I go about achieving this, can it be done purely in JavaScript?
Thanks
If you want to display 'realtime' (meaningly, as the user types) values, you can use the keyup values :
http://www.w3schools.com/jsref/event_onkeyup.asp
(for pure javascript)
http://api.jquery.com/keyup/ (for
jquery)
Place an event handler on the onBlur event. If you had a Javascript function called calculateStuff(), your input element could reference it like this:
<input name="something" type="text" onblur="calculateStuff();" value="">
The onBlur event happens when the user leaves the field. If you want it to happen as they are still typing, you could use the onChange handler in the same way.
Yes. You should call an onkeyup / onchange event in JavaScript to determine if the user has typed anything and inside the event just have it call a JavaScript function which refreshes the form by doing the math and inserting the values.
You can also add other event listeners such as blur etc.
It has been a while so i cant post any usable code but Google is your friend here.
Without building a complete answer for you here are some hints:
pure javascript would require something like this using the .value from an element:
alert(document.getElementById('elementid').value);
if you use a javascript library as for example jquery you can use something as .val()
edit: you can use the onchange event to process the changes
Use onchange event handler. Simplex code are given below :
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<script>
function summation()
{
var input1 = document.getElementById('input1').value;
var input2 = document.getElementById('input2').value;
var input3 = document.getElementById('input3').value;
var total = (input1*1) + (input2*1) +(input3*1);
document.getElementById('total').innerHTML = "Total = $"+total;
}
</script>
</head>
<body>
<p>Input 1 : <input id="input1" type="number" onchange="summation()"></p>
<p>Input 2 : <input id="input2" type="number" onchange="summation()"></p>
<p>Input 3 : <input id="input3" type="number" onchange="summation()"></p>
<p id="total"></p>
</body>
It's simple! Instead of using the button, add an onChange="your_calculate_function()" attribute to each of your inputs.

Categories

Resources