Automat js form calculator - javascript

I need help with a js/jQuery automat form calculator.
The function is time=games*(players*15),
so basically there are 3 form fields games players result in field time.
I want the result to be in real time not by pressing a button.
Here is the code I made with a trigger button, but I want without calculate button, just by completing fields.
Nvm, I resolved it with an onChance for fields.
<SCRIPT LANGUAGE="JavaScript">
function CalculateSum(games, players, form)
{
var A = parseFloat(games);
var B = parseFloat(players);
form.Time.value = A*(B*15) ;
}
function ClearForm(form)s
{
form.input_A.value = "";
form.input_B.value = "";
form.Time.value = "";
}
// end of JavaScript functions -->
</SCRIPT>
// HTML -->
<FORM NAME="Calculator" METHOD="post">
<P>Games: <INPUT TYPE=TEXT NAME="input_A" SIZE=10></P>
<P>Plyers <INPUT TYPE=TEXT NAME="input_B" SIZE=10></P>
<P><INPUT TYPE="button" VALUE="Calculate time" name="Calculate time"
onClick="CalculateSum(this.form.input_A.value, this.form.input_B.value, this.form)"></P>
<P><INPUT TYPE="button" VALUE="Clear" name="Clear" onClick="ClearForm(this.form)"></P>
<P>Time = <INPUT TYPE=TEXT NAME="Time" SIZE=12></P>
</FORM>

You can use the function keyup() to trigger the function so the result is update everytime the user add a number

You can use keyup to trigger when you enter a value
function CalculateSum()
{
var games = $('input[name=input_A]').val()
var players = $('input[name=input_B]').val()
var time = parseFloat(games) * (parseFloat(players) * 15)
$('input[name=Time]').val(time)
}
function ClearForm()
{
$('input[name=input_A], input[name=input_B], input[name=Time]').val('')
}
// bind view
$('input[name=input_A], input[name=input_B]').on('keyup', function(){
CalculateSum()
})
$('input[name=Clear]').on('click', function(){
ClearForm()
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<FORM NAME="Calculator" METHOD="post">
<P>Games: <INPUT TYPE=TEXT NAME="input_A" SIZE=10></P>
<P>Plyers <INPUT TYPE=TEXT NAME="input_B" SIZE=10></P>
<P><INPUT TYPE="button" VALUE="Clear" name="Clear"></P>
<P>Time = <INPUT TYPE=TEXT NAME="Time" SIZE=12></P>
</FORM>

Related

Choosing among radio buttons and Text Field

I have 2 radio buttons. All of them have different values. I also have one text field, in case I need a different value, I can enter that value on that text field.
<form action="" onsubmit="return doSubmit(this)">
<input type="radio" name="url" value="https://example.com/fee/25"> $25
<input type="radio" name="url" value="https://example.com/fee/50"> $50
<input type="submit" value="Submit">
</form>
and here is the Javascript I've found to make radio buttons working
<script type="text/javascript">
function doSubmit(form) {
var urls = form['url'];
var i = urls && urls.length;
while (i--) {
if (urls[i].checked) {
window.location = urls[i].value;
}
}
document.getElementById("amount").value;
return false;
}
</script>
I have one text field:
<input type="text" name="amount" size="10" id="amount" value="">
Ok. If the amount is entered, then I need to use this code:
document.getElementById("amount").value
But how to make it working with radio buttons? I have created this JS code:
<script type="text/javascript">
var link = "https://example.com/fee/";
var input= document.getElementById('amount');
input.onchange=input.onkeyup= function() {
link.search= encodeURIComponent(input.value);
};
</script>
What I'm doing wrong? Thanks in advance for your time. I love and enjoy learning from experts.
I would create a separate radio button for the text input:
var options = Array.from(document.querySelectorAll("[name=url]"));
amount.addEventListener('focus', function() {
options[0].checked = true; // If textbox gets focus, check that radio button
});
options[0].addEventListener('change', function() {
amount.focus(); // if first radio button gets checked, focus on textbox.
});
function doSubmit(form) {
// get checked value, replace empty value with input text
var value = options.find( option => option.checked ).value || amount.value;
window.location = "https://example.com/fee/" + value;
return false;
};
<form action="" onsubmit="return doSubmit(this)">
<input type="radio" name="url" value="" checked>
$<input type="text" name="amount" size="5" id="amount" value="" >
<input type="radio" name="url" value="25"> $25
<input type="radio" name="url" value="50"> $50
<input type="submit" value="Submit">
</form>
Instead of using the url as the value for the radio buttons, consider using the value you wish to pass to the url:
function doSubmit(form) {
var endpoint = "https://example.com/fee/";
// gets the values of input elements that were selected
var checkedValues = Array.from(form.amounts)
.filter(radio => radio.checked)
.map(radio => radio.value);
// if a radio button was checked, use its value
// otherwise, use the value in the text field
var amount = checkedValues.length ?
checkedValues[0] : form.amount.value;
console.log('redirecting to: ', endpoint + amount);
return false;
}
// uncheck radio buttons when text is entered
function uncheck() {
Array.from(document.querySelectorAll('input[name="amounts"]'))
.forEach(radio => radio.checked = false);
}
<form action="" onsubmit="return doSubmit(this)">
<input type="radio" name="amounts" value="25"> $25
<input type="radio" name="amounts" value="50"> $50
<input type="text" name="amount" onkeyup="uncheck()">
<input type="submit" value="Submit">
</form>
Edit: Wow I completely forgot you could use the :checked attribute as a css selector. In this case, the code becomes quite simple:
function doSubmit(form) {
// select checked inputs with the specified name attribute
var checkedRadio = document.querySelector('input[name="amounts"]:checked')
// if we have a radio button that is checked, use its value
// otherwise, use the text input's value
var amount = checkedRadio ? checkedRadio.value : form.amount.value;
window.location = 'https://example.com/fee/' + amount;
return false;
}
// uncheck radio buttons when text is entered
function uncheck() {
Array.from(document.querySelectorAll('input[name="amounts"]'))
.forEach(radio => radio.checked = false);
}
<form action="" onsubmit="return doSubmit(this)">
<input type="radio" name="amounts" value="25"> $25
<input type="radio" name="amounts" value="50"> $50
<input type="text" name="amount" onkeyup="uncheck()">
<input type="submit" value="Submit">
</form>

HTML-Javascript Input-Calculation-Output

I need just want to add some textboxes/form to input data from a user through HTML and take them into variables in a script that will run a calculation and then output the answer to the calculation. I have some code but its not working properly. It seems that when the submit button is clicked, the function isn't called. Any help would be great: here's the code.
<form id="frm1" action="form_action.asp">
Initial Displacement: <input type="number" name="x"><br>
Initial Velocity: <input type="number" name="v"><br>
Acceleration: <input type="number" name="a"><br>
Time Passed: <input type="number" name="t"><br>
<input type="button" onclick="calc()" value="Submit"/>
</form>
<script>
function calc()
{
var b=document.getElementById("frm1");
document.write(b.element[0].value+b.element[1].value*b.element[2].value+(1/2)*b.element[3].value*b.element[2].value*b.element[2].value);
}
</script>
https://jsfiddle.net/zytyf16q/#&togetherjs=qABKDyLpK2
There is a mistype in your code on the submit button. Your submit button should look like:
<!DOCTYPE html>
<html>
<body>
Initial Displacement:
<input type="number" id="x" name="x">
<br> Initial Velocity:
<input type="number" id="v" name="v">
<br> Acceleration:
<input type="number" id="a" name="a">
<br> Time Passed:
<input type="number" id="t" name="t">
<br>
<input type="button" onclick="calc('x','v','a','t')" value="Submit">
</body>
<script>
function calc(x, v, a, t) {
var Displace = parseInt(document.getElementById(x).value)
var Velocity = parseInt(document.getElementById(v).value)
var Acceleration = parseInt(document.getElementById(a).value)
var Time = parseInt(document.getElementById(t).value)
var calculations = Displace + (Velocity * Acceleration) + ((1 / 2) * Time * Acceleration * Time);
alert(calculations)
}
</script>
</html>
I added id's to the inputs, and then used document.getElementById to select them and save them to a variable with their respective name. Then I carried out the calculation.
<form id="frm1" action="form_action.asp">
Initial Displacement: <input type="number" name="x" id="x"><br>
Initial Velocity: <input type="number" name="v" id="v"><br>
Acceleration: <input type="number" name="a" id="a"><br>
Time Passed: <input type="number" name="t" id="t"><br>
<input type="button" onclick="calc()" value="Submit"/>
</form>
<script>
function calc()
{
var x = document.getElementById('x').value
var v = document.getElementById('v').value
var a = document.getElementById('a').value
var t = document.getElementById('t').value
document.write(x+v*a+(1/2)*t*a*a);
}
</script>

Passing value from one field to another

I want to pass the value 9112232453 of one textfield to another.
I know I need Javascript for this but I don't know how to do it.
HTML
<form method = "post" action="">
<input type="checkbox" name="phone" value="9112232453" onclick='some_func();' >
<input type="text" name="phone" value="" id="phone">
<input type="submit" name="Go">
</form>
Then later, I want to use the value in my php.
You could use a JS. function to take param (this.value) like:
<script>
var some_func = function (val){
var input = document.getElementById("phone");
input.value = val;
}
</script>
<form method = "post" action="">
<input type="checkbox" name="phone" value="9112232453" onclick='some_func(this.value);' >
<input type="text" name="phone" value="" id="phone">
<input type="submit" name="Go">
</form>
The best way is to not obtrude the HTML code with Javascript event handlers.
So, you can add a DOMContentLoaded event listener to the document, and as soon as DOM is loaded:
You add a change event listener to the input[type=checkbox], and then:
1.1. If the checkbox is checked, then you change the input#phone's value to its value
1.2. If not, then you empty the input#phone's value.
document.addEventListener('DOMContentLoaded', function() {
document.getElementById('cbphone').addEventListener('change', function(e) {
var phone = document.getElementById('phone');
if (this.checked) {
phone.value = this.value;
// you can even enable/disable the input#phone field, if you want to, e.g:
// phone.disabled = false;
}
else {
phone.value = '';
// phone.disabled = true;
}
});
});
<form method="post" action="">
<input type="checkbox" name="cbphone" id="cbphone" value="9112232453">
<input type="text" name="phone" id="phone">
<input type="submit" name="Go" value="Go">
</form>
before submit form use validation and check whether the field value is filled up or not. if yes get value of the field.
if(document.getElementBy("fieldIdfirst").value!="")
{
document.getElementBy("fieldIdSecond").value=document.getElementElementById("fieldIdfirst");
}
Thanks it..
Try this: http://jsfiddle.net/yhuxy4e1/
HTML:
<form method = "post" action="">
<input type="checkbox" name="phone" value="9112232453" onclick='some_func();' id="chk_phone">
<input type="text" name="phone" value="" id="txt_phone">
<input type="submit" name="Go">
</form>
JavaScript:
some_func = function() {
var checkBox = document.getElementById('chk_phone');
var textBox = document.getElementById('txt_phone');
textBox.value = checkBox.value;
}

How to solve validation using multiple buttons in a form

I have a form, with a number of textboxes which a user can fill in. At the bottom of the form I have two buttons. One for canceling and one for submitting. Like the example below
<form action='bla.php' method='post'>
<input type='text' name='someTextField1'>
<input type='text' name='someTextField2'>
<input type='text' name='someTextField3'>
<input type='submit' name='submit'>
<input type='submit' name='cancel'>
</form>
And I have a js function that checks the fields for their data which I used to use for both buttons. I therefor refer to the js function in the form as below:
<form action='bla.php' method='post' name='form' onSubmit='return CheckFields()'>
The js function looks like this:
function CheckFields() {
var formname = "form";
var x = document.forms[formname]["someTextField1"].value;
var result = true;
var text = "";
if (x == null || x == "") {
text += "Dont forget about the someTextField1.\n";
result = false;
}
if(!result)
alert(text);
return result;
}
Now I want this js function to only run when using the submit and not the cancel button. When I try to move the call to the function to the submit button as below it doesn't work:
<input type='submit' name='submit' onClick='return CheckFields()'>
<input type='submit' name='cancel'>
Why? What is the smartest way of solving this? Should I leave the call to CheckFields() in the form and check within the script what button was clicked or should I remake the function to somewhat work with a button instead? Anyone have an idea or an example?
replace <input type='submit' name='cancel'> by <input type='button' name='cancel'>.Your Version actually has two submit-buttons, both of which will submit the form.
Watch this sample http://jsfiddle.net/355vw560/
<form action='bla.php' method='post' name="form">
<input type='text' name='someTextField1'>
<input type='text' name='someTextField2'>
<input type='text' name='someTextField3'>
<br/>
<input type='submit' name='submit' onclick="return window.CheckFields()">
<input type='submit' name='cancel' value="cancel" onclick="return false;">
anyway it's always better to use jquery or event listeners instead of managing events directly in the dom.
The function didnt worked because its scope was the element, if u specify window as context your function works.
First at all, it's not needed have submit button on a form if you want to use javascript to check all the fields before submitting.
I think the smartest way of doing it will be as follow:
Your form (without action, submit button, and method. Only identifing each component with id's):
<form id="formId">
<input type='text' id="text1">
<input type='text' id="text2">
<input type='text' id="text3">
<input type='button' id="accept">
<input type='button' id="cancel">
</form>
Your javascript (you have to have jQuery added):
jQuery("#formId").on("click", "#accept", function(){ //listen the accept button click
if(CheckFields()){ //here you check the fields and if they are correct
//then get all the input values and do the ajax call sending the data
var text1 = jQuery("#text1").val();
var text2 = jQuery("#text2").val();
var text3 = jQuery("#text3").val();
jQuery.ajax({
url: "bla.php",
method: "POST",
data: {
"someTextField1":text1, //In your example "someTextField1" is the name that the bla.php file is waiting for, so if you use the same here, it's not needed to change anything in your backend.
"someTextField2":text2,
"someTextField3":text3
},
success: function(){
//here you can do whatever you want when the call is success. For example, redirect to other page, clean the form, show an alert, etc.
}
});
}
});
jQuery("#formId").on("click", "#cancel", function(){ //here listen the click on the cancel button
//here you can clean the form, etc
});
function CheckFields() { //here I did a little change for validating, using jQuery.
var x = jQuery("#text1").val();
var result = true;
var text = "";
if (x == null || x == "") {
text += "Dont forget about the someTextField1.\n";
result = false;
}
if(!result)
alert(text);
return result;
}
I hope it helps you!
I handle it with this way , Hope it will help.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>JS Bin</title>
</head>
<body>
<form method="post" action="/">
<div class="container" style="background: #efefef; padding: 20px;">
<label>Encrypt and decrypt text with AES algorithm</label>
<textarea name="inputText" id = "inputText" rows="3" cols="100" placeholder="Type text to Encrypt..." maxlength="16" ></textarea>
<br>
<br>
<textarea name="inputKey" id = "inputKey" rows="1" cols="100" placeholder="Type key to Encrypt\Decrypt text with..." maxlength="16"></textarea>
<br>
<br>
<label>SBox :</label>
<div>
<div class="s-box-radios">
<ul class="sbox">
<li>
<label>SBox 1
<input id="sbox1" name="sboxOption" type="radio" value="option1" required/>
</label>
</li>
<li>
<label>SBox 2
<input id="sbox2" name="sboxOption" type="radio" value="option2" />
</label>
</li>
<li>
<label>SBox 3
<input id="sbox3" name="sboxOption" type="radio" value="option3" />
</label>
</li>
<li>
<label>SBox 4
<input id="sbox4" name="sboxOption" type="radio" value="option4" />
</label>
</li>
</ul>
</div>
<div class="s-box-display">
<textarea rows="5" cols="10"></textarea>
</div>
</div>
<div class="clear"></div>
<br>
<label>Result of Decryption in plain text</label>
<textarea name="inputCipher" rows="3" cols="100" placeholder="Encrypted Texts..." name="decrpyted"></textarea>
<br>
<input type="submit" value="Encrypt" name="Encrypt" id ="encrypt" onclick="valEncrypt()" />
<input type="submit" value="Decrypt" name="Decrypt" id ="decrypt" onclick="valDncrypt()" />
</div>
</form>
<script>
function valEncrypt()
{
var inputText = document.getElementById('inputText');
var inputkey = document.getElementById('inputKey');
if (inputText.value.length <16)
{
doAlert(inputText);
return false;
}
else
{
removeAlert(inputText);
}
if (inputkey.value.length <16)
{
doAlert(inputkey);
return false;
}
else
{
removeAlert(inputkey);
}
}
function valDncrypt()
{
var inputkey = document.getElementById('inputKey');
if (inputkey.value.length <16)
{
doAlert(inputkey);
return false;
}
alert('!Success');
}
function doAlert(element){
element.style.border = "1px solid #FF0000";
}
function removeAlert(element){
element.style.border = "1px solid #000000";
}
</script>
</body>
</html>

Why is not my HTML form sending the data to my JS file?

I am working on a simple ASP.NET project. I have HTML and a JS file. I am trying to send the values of the form inputs to the JS file, but it seems to be broken for some reason.
My form looks like:
<div class="set-the-clock">
<form name="settheclock">
<span>Hours: </span><input type="text" id="fhours" value=""><br>
<span>Minutes: </span><input type="text" id="fminutes" value=""><br>
<span>Seconds: </span><input type="text" id="fseconds" value=""><br>
<input type="button" id="send" value="Enter">
</form>
and my JS is:
var setHour = document.getElementById("fhours").value;
var setMinute = document.getElementById("fminutes").value;
var setSecond = document.getElementById("fseconds").value;
and the function that meant to use it:
function setTheClockByButton() {
setTheClock(setHour, setMinute, setSecond);
alert(setHour);
}
If I put a number to the value in the HTML form it works fine(like this)
<span>Hours: </span><input type="text" id="fhours" value="3"><br>
but it not accepting any data from the keyboard.
And of course I have the onclick function associated to the form:
document.getElementById("send").onclick = setTheClockByButton;
(otherwise it'd make no sense).
Move those assignment statements inside the function:
function setTheClockByButton() {
var setHour = document.getElementById("fhours").value;
var setMinute = document.getElementById("fminutes").value;
var setSecond = document.getElementById("fseconds").value;
setTheClock(setHour, setMinute, setSecond);
alert(setHour);
}
Now each time the button is clicked (and note that I'm assuming that part works, since you say it does), the values of the input fields will be fetched so that the clock update function is working with up-to-date values.
You need an onclick event:
<div class="set-the-clock">
<form name="settheclock">
<span>Hours: </span><input type="text" id="fhours" value=""><br>
<span>Minutes: </span><input type="text" id="fminutes" value=""><br>
<span>Seconds: </span><input type="text" id="fseconds" value=""><br>
<input type="button" id="send" value="Enter" onclick="setTheClockByButton()">
</form>
</div>
<script>
function setTheClockByButton() {
var setHour = document.getElementById("fhours").value;
var setMinute = document.getElementById("fminutes").value;
var setSecond = document.getElementById("fseconds").value;
alert(setHour);
}
</script>

Categories