Make number in form go up every time button is clicked - javascript

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);
});
}

Related

How to detect an empty input field on submit and have Jquery replace it with a specific value?

I've seen various similar questions posted, but I can't quite seem to get all the pieces together.
I have a really simple form with an option single input field. I'd like to allow the user to input a value to use, but if they don't I want it to use a default, but only on submit.
Here's the HTML and JS I'm working with. This simply grabs the input value and adds it to the button URL. What I need it to do is see if it's blank on submit only and replace it with "NoName"
<script type="text/javascript">
$(document).ready(function(){
$('#button').click(function(e) {
var inputvalue = $("#rep").val();
window.open("https://example.com/"+inputvalue, "_blank");
});
});
</script>
<form id="options">
<p><input type="text" id="rep" name="rep" placeholder="Your Rep ID: " style="width:auto;" value="" /></p>
<p><button type="button" id="button" style="color:white; background-color: blueviolet; border:none; border-radius: 3px;">GO!</button></p>
</form>
The examples and solutions I've seen have it using placeholders, or onBlur events that cause the box to keep changing if they click in or out of it. I'd like this to stay blank, unless they enter something, then the button URL would change based on that alone.
If empty > use default value in the URL and if not empty > use the url+value entered.
The current behavior works fine if something is entered, but if not, it simply goes to the URL (as the current script tells it to)
If I understand you well is as simple as you described: if empty > use default value in the URL and if not empty > use the url+value entered.
just use simple if else, I made small jsfiddle for you.
get the user value
var userValue=$('#rep').val();
then check if user value is null or empty
if(userValue){ }
if it is empty then use default value
$(function(){
$('#button').click(function(){
var myDefault="http://url.com";
var userValue=$('#rep').val();
if(userValue){ location.href=userValue; }
else { //use default
location.href=myDefault; }
});
});

Javascript to "copy in real time" some fields from a form to another form (with different input names)

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());
});
});

trouble resetting form through javascript or jquery

I have the below jQuery function which is called when ever I click a button on my page. This button is supposed to reset the form and reload a fresh page.
function Create(txt) {
if (txt="createUser") {
document.forms[0].reset();
$('#myform').each(function() {
this.reset();
});
$('input[name=method]').val(txt);
document.forms[0].submit();
}
}
But for some reason, it does not go to this.reset() at all and I see all the form values in my action class. How should I solve this?
Below is how the button is defined.
<input type="button" value="Create" class="btn" onclick="Create('createUser');">
edit: Ok guys.. i know how input type="reset" works and i have another button in my page doing the same.. I have a create user form where i can search and see an existing user details or fill the form and create a new user. if i search for a user and then click on create to create another user, it sends a new request to the server and reloads the page.. but in the action class.. the bean has not been reset.. and i get all the values back on the page. hence ..i want to reset the form...without using the reset button...
I selected John's answer .. made a slight modification and below is the final function i used.
function Create(txt){
if (txt="createUser"){
var $form = $('#myform');
$form.find(':input').not(':button,:submit, :reset, :hidden').val('').removeAttr('checked').removeAttr('selected'); // Clear all inputs
$form.find('input[name=method]').val(txt);
$form.submit();
}
}
Instead of java script, you can have html code,
<input type="reset" value="Reset">
As others have pointed out, you have = where you should have ==, but that means the if-statement is always true. It is not, however, the reason you "see all the form values in my action class".
I think the problem may be that you are misinterpreting what the reset() method does. It does not clear all the input values; instead, it resets them to their original values (i.e., the values in the "value" attributes).
You may want to clear them yourself, rather than use the reset() method.
function Create(txt) {
if (txt == 'createUser') {
var $form = $('#myform');
// Clear form values
$form.find(':input:not(:button,:submit,:reset,:checkbox,:radio,:hidden)').val('');
$form.find('input:checkbox,input:radio)').prop('checked', false);
$form.find('input[name=method]').val(txt);
$form.submit();
}
}
Note: The :input selector matches all input, textarea, select and button elements.
Note: It appears the OP does not want hidden inputs to be cleared, but does want checkboxes and radio buttons cleared.
You seem to be setting a variable here -
if (txt="createUser"){...
Change it to -
if (txt == "createUser") {..
That way you're doing a comparison, instead of setting a variable.
the button does not have type="reset" so either change it to reset or use
document.getElementById("myform").reset(); instead of
document.forms[0].reset();
$('#myform').each(function(){
this.reset();
});
I would do like this:
$(document).ready(function() {
$("#createUserButton").on("click", function() {
var form = $("#myForm")[0];
form.reset();
$("input[name=method]").val("CreateUser");
form.submit();
}
});
And your button becomes:
<input type="button" value="Create" class="btn" id="createUserButton">
I'd suggest you to place an id attribute as well in your input text, something like:
<input type="text" name="method" id="methodName" />
And then you could reference it by id which is faster than by name, like this:
$("#methodName").val("CreateUser");
Your code was wrong, in your if you should've used == or === instead of just = and your form should've just have called reset method. No need to iterate over an id using each, even because an ID have to be unique in an HTML page.
Here's a workin fiddle, just type something in the first input to see it happening.

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