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.
Related
I'm trying to write a function to copy some fields (in real time) from a specific form, to another form
I try to be more specific:
I have 2 forms
- The first form is the one the user will fill in.
- The other form is hidden.
When the user will fill the first form, the second form (hidden) will be filled by the same informations.
Some fields are automatically filled by some calculations, so I can't use keyup/keypress or "click" to start the function
I wrote something like this, but it doesn't work
$(function(){
var form1 = $('#form1'),
form2 = $('#form2');
$('#fieldname_form1').change(function(){
$('input[name="inputname2"]', form2).val(function(){
return $('input[name="inputname1"]', form1).val();
});
});
});
You can copy in real time using the keyup function, something like this. Otherwise, when you say
Some fields are automatically filled by some calculations
What do you mean? These calculations are made by you using JS or what? Because, if you are using JS you can fill the two fields at the same time when you make the calculations.
this works for me...
$(function() {
$('#i1').change(function(evt) {
$('#i2').val(evt.target.value);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
<input type="text" name="name1" id="i1" />
</form>
<form>
<input type="text" name="name2" id="i2" />
</form>
The change event is fired after the element has lost the focus. For the "user editable" elements you should use keyup (for the textbox) and change for the drop down elements.
On the other hand, for the fields filled automatically, you don't have any nice and clean solutions. I can think in two options:
If the calculations trigger is always the user changing some value, you could copy every form value after that happens.
(very bad option, but it would still work) You could be constantly checking for changes in every element and copying them using setInterval function.
As a side note
As well as your code should work, there is a simpler way to do it:
$('#fieldname_form1').change(function(){
var value = $('input[name="inputname1"]', form1).val();
$('input[name="inputname2"]', form2).val(value);
});
This should work -
$(function() {
var form1 = $('#form1'),
form2 = $('#form2');
$('#fieldname_form1').change(function() {
$('input[name="inputname2"]', form2).val($(this).val());
});
});
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 ;
}
i have input with type number like this
<input type="number" class="number" min="0" max="999999" value="0" id="id">
when i use this code
$("#id").val();
if it's number like 1 it return the number
but if not a number like 1+1 it return empty string ""
so can i get the actual value with type number or i have to change to text to do so
i test it with chrome and firefox
i know that it will work with type text
but i'm looking to faster solution if there are non then i will change it to text and rewrite the code
here is my question
now when i change the type to text using jquery it remove the value can i change it without remove the value ?
$('#id').attr('type','text')
what i want to do is make the type text get the value and return it back to number
You can not do it with <input type='number'/>,
<input type="number" > will expect you to put a number, so if you put anything like 1+1, it is not considered a number, so returns an empty string "".
you can instead use <input type=text/>
See this fiddle
$('input').on('change', function() {
var strVal = $("#id").val();
var intVal = eval(strVal);
alert(intVal);
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" class="number" value="0" id="id">
Edit:
if you cant change whole html, you can change type of the element using jquery,
$('input[type=number]').attr('type','text')
just put this on page load
If someone needs an input type="number" , there is a reason.
Premise: I'm not the same Robert that made the initial question :-)
but ...
I was exactly in the same situation of the Robert who made the initial question ( destiny matter? ), anyway
making a deeper research, I have found this answer
JavaScript get clipboard data on paste event (Cross browser)
I beloved that twice because, nevertheless, it is pure vanilla javascript
I have made this code with input type = "number" and it works like a charm
The main behavior because I want input type = "number" is that this input type, when focused ON MOBILE will open the numbers pad INSTEAD than the letters keyboard. Here the input is driven, you can press only numbers and dashes
But in my app , they can paste the number.. so having a check on the paste event, is a logical consequence
try it
function handlePaste (e) {
var clipboardData, pastedData;
// Stop data actually being pasted into div
e.stopPropagation();
e.preventDefault();
// Get pasted data via clipboard API
clipboardData = e.clipboardData || window.clipboardData;
pastedData = clipboardData.getData('Text');
// Do whatever with pasteddata
alert(pastedData);
}
document.getElementById('myInput').addEventListener('paste', handlePaste);
<p>This example uses the addEventListener() method to attach a "paste" event to an input type="number" element. Paste some text in the input...</p>
<input type="number" id="myInput" value="Try to paste something in here" size="40">
OK Solution to your problem
$('input[type=number]').each(function(){
var val = $(this).val();
$(this).attr('type','text');
$(this).val(val);
});
above code will work on all inputs with type number. If you want to use only one use class or id in first line. If you want to count value from string like 1+1 u can use eval in try catch block. But this is generally a lot more complicated solution.
I'm very new to HTML and JavaScript, but I wanted to know if there is any way to make the numeric value in a textbox go up by one each time a button is pressed. This needs to be done to multiple textboxes so I was thinking this could be made with a function.
<html>
<head>
function (add) {
function goes here
}
</head>
<input type="text">
<input type="button" value="Add One" onclick="add()">
</body>
</html>
I am sorry if my code makes no sense, because I don't know how to accomplish this. Any help is very appreciated!
This is quite simple, really. Your code will need the following elements:
A function in Javascript that is called whenever the button is pressed
A way to retrieve the current value of the text box
A way to put the new value back into the text box
To refer to a particular element in your page, you will need to give it an id. Don't forget to give it a default value, either in code or in HTML, as well, so that you don't start with an empty text box. For example:
<input type="text" value="0" id="textField"/>
You can then get the value of that text field in Javascript using the following:
var textField = document.getElementById( "textField" );
The Javascript variable textField now contains a reference to the text field, and we can just get its content using textField.value. You can also write back to the contents using the same value variable. You will also need to use the parseInt function to turn the text in the field into a number so that Javascript won't just try to stick the character '1' on the end of it.
In the <HEAD> section of your page, you would add the following:
<script language="Javascript>
function handleButtonClick() {
var textField = document.getElementById( "textField" );
var currentValue = parseInt(textField.value);
// Add one
currentValue = currentValue + 1;
// Put it back with the new +1'd value
textField.value = currentValue;
}
</script>
To call a function in Javascript whenever a button is pressed, you would use an event handler, which signals Javascript to run a particular snippet of code whenever an action happens in the browser. In this case, since you're wanting to run code when the user clicks a button, you would use the onClick handler. You can either set this as part of a script or in your HTML code. Doing it in Javascript is ultimately more robust, but for simplicity, I'm going to do it in HTML code.
<input type="button" onClick="handleButtonClick()"/>
And that's it. When you click the button, assuming you've got it all wired up correctly.
See this page for some basic information about getElementById and this page for some basic info about what other event handlers are available for you.
Try this.
<script type="text/javascript">
function add() {
var num = document.getElementById("mynum").value;
if(num == '') num = 0;
document.getElementById("mynum").value = parseInt(num ,10) + 1;
}
</script>
<html>
<head>
function (add) {
function goes here
}
</head>
<div id='txt'></div>
<form action="" method="post">
<input type="text" id='mynum'>
<input type="button" onclick="add()">
</form>
</body>
</html>
hope will help you
I would use jquery for this, so your html should be something like this:
<input type="number" id="numbox">
<button type="button" id="button">
In your javascript file add an event handler:
$("#button").click(addOne);
This means that whenever the element with the id "button" is pressed, the addOne function is called. So from here you write the addOne function, which takes the value of the number text box, adds one to it, and then sets the value of the text box to the new number.
var addOneToEach = function() {
$(":text").each(function(){
var num = $(this).val();
$(this).val(num + 1);
});
}
is there a way to implement a text change event to detect text change on an HTML input text field? It's possible to simulate these using key events (key press etc), however, it's really not performant and difficult, is there a better way?
onChange doesn't fire until you lose focus later. If you want to be really strict with instantaneous changes of all sorts, use:
<input
type = "text"
onchange = "myHandler();"
onkeypress = "this.onchange();"
onpaste = "this.onchange();"
oninput = "this.onchange();"
/>
When I'm doing something like this I use the onKeyUp event.
<script type="text/javascript">
function bar() {
//do stuff
}
<input type="text" name="foo" onKeyUp="return bar()" />
but if you don't want to use an HTML event you could try to use jQuerys .change() method
$('.target').change(function() {
//do stuff
});
in this example, the input would have to have a class "target"
if you're going to have multiple text boxes that you want to have done the same thing when their text is changed and you need their data then you could do this:
$('.target').change(function(event) {
//do stuff with the "event" object as the object that called the method
)};
that way you can use the same code, for multiple text boxes using the same class without having to rewrite any code.
Well unless I misunderstand you can just use the onChange attribute:
<input type="text" onChange="return bar()">
Note: in FF 3 (at least) this is not called until some the user has confirmed they are changed either by clicking away from the element, clicking enter, or other.
I used this line to listen for input events from javascript.
It is useful because it listens for text change and text pasted events.
myElement.addEventListener('input', e => { myEvent() });
Use the oninput event
<input type="text" oninput="myFunction();" />