understanding click(),change() and inputs scopes - javascript

I am trying to understand scope as far as inputs and clicks or checks are concerned. I am working on a project and what I am trying to do is. Ask if they work out a lot, they will answer yes or no. then I will ask them 3 question either way. I will ask how much they can bench, how much they can squat, how much they can curl. I have this part set up I will give them feedback based on what they input. What I am trying to do is add a check box to it for them to select if they are male or female. I think I should do it something like this
function one() {
a = 100;
b = 200;
c = 300;
return two();
function two() {
a += a;
b += b;
c += c;
return three();
function three() {
a += 1;
b += 1;
c += 1;
return four();
function four() {
console.log(a, b, c);
}
}
}
}
one()
I guess my question is how would I do this with click and checks and inputs. It seems no matter where I add the check box to what I have, it will not work for some reason. Either there will be a issue with the first question... Do you work out a lot? a the question will not be there. Or I will get a post era. I have a fiddle below. If someone would tell me how to make it work...or even better show me it working, I will be very thankful. I think this would help a lot of people out. I have seen a lot of good answers to this question on here, but no working examples. I think the most helpful thing for some people, is a working example they can see, I know it is for me.
ps in my fiddle i am recycling the same inputs for the questions i'm asking. Whether they work out or not, i would like to do it properly, but not my main issue.
http://jsfiddle.net/vicky1212/G24aQ/10/

I have added some explanation with the code..
$('.myOptions').change(function () {
// Remove the active class
$('.list').removeClass('active');
// Add the active class
// this.value holds the current value that is selected
// No need to use filter
$('.' + this.value).addClass('active');
});
$('#butt').click(function () {
// Better to have Lesser variables ,
var active = $('.list.active'),
$boxOne = active.find('.box1'),
$boxTwo = active.find('.box2'),
$boxThree = active.find('.box3'),
$output = $('#output'),
total = (parseInt($boxOne.val(), 10) + parseInt($boxTwo.val(), 10) + parseInt($boxThree.val(), 10)),
msg = '';
$output.addClass('error');
var dropdownValue = $('.myOptions').val(),
// you need to select the inputs specifically
// you were trying to access it using $('input') that gives the list of all the inputs
// on your page.. So you need to be more specific
$genderRadio = $('input[name=gender]');
// If dropdown is empty show some message
if (dropdownValue === '') {
msg = 'Please select an option....';
} else if (isNaN(total)) {
msg = 'Input three numbers, please...';
} // If gender is not selected show a specific message
else if ($genderRadio.filter(':checked').length === 0) {
msg = 'Please select your gender....';
} else {
// If it comes to this statemenet it means there is no error
// remove the error class
$output.removeClass('error');
if (total < 14) {
msg = "That's bad, should be higher...";
} else if (total > 15) {
msg = "That's bad, should be lower...";
} else {
msg = "You got it... Nice work.";
}
var genderPrefix = $genderRadio.filter(':checked').val() === 'Male' ? 'Sir..' : 'Miss..';
msg = genderPrefix + msg;
}
$output.text(msg);
});
Check Fiddle

I will give an little introduction to javascript pattern with my example. you can read about them in http://addyosmani.com/resources/essentialjsdesignpatterns/book/ is not a easy reading but when you are ready you will understand pretty much about how to organize you javascript code with that book.
meanwhile I can advise you to read about how to code forms with good practices at http://net.tutsplus.com/tutorials/html-css-techniques/20-html-forms-best-practices-for-beginners/
Ok beside that here are the working example about how to work with click and forms http://jsfiddle.net/ncubica/BQaYz/
HTML
<label><input type="Radio" name="gender" id="male" value="male" /> male</label>
<label><input type="Radio" name="gender" id="female" value="female" />female</label>
<input type="text" id="name" placeholder="name" />
<input type="text" id="lastname" placeholder="lastname" />
<input type="button" id="submit" value="store" />
javascript
var survey = (function(_module){
var modulename = _module;
var user = {};
/*private methods*/
function init(){
observers();
}
function observers(){
$(document).on("click","#submit", survey.store)
}
/*public methods*/
$r = {}
$r.store = function(){
user.name = $("#name").val();
user.lastname = $("#lastname").val();
user.gender = $("input:radio[name=gender]:checked").val();
survey.toString();
}
$r.toString = function(){
var genderStr = (user.gender == "male") ? "Man" : "Girl";
alert(user.name + " " + user.lastname + " is " + genderStr);
}
$r.init = function(){
init();
}
return $r;
})("survey")
survey.init();
Ok, I know at first look a little "big" code but is really simple, in javascript a variable can take any kind of form from a function to a normal string.
here we are working with anonymous functions to create a module will help us to work more clear and structure, this variable will have 2 kind of methods and variable, public and privates.
for make a method public we have to return the methods in an object after we finish to run the code this is why exist the $r variable which is an object who have function by properties, and at the end of the code you return it doing return $r with this pattern now you can easily can navigate throw methods and catch events like click, change, etc....
you only should have to add this event to the method observers create a private or public function which will be activate after the event an you are done.
Read the code and if you have any further question you can ask me anything. I try to solve you problem and structure you code.
best good luck

[Here is below answer as a jsFiddle]
This answer is intended as a starter. I tried to write it at a beginner level, so that you can customize it for yourself. Hopefully, this simple example can give you a starting place. I used the example of a training gym asking some basic questions of their users.
My approach was to create an empty DIV, called #ques, where all Questions and output will be displayed, and a hidden <form> containing hidden fields that will store the responses.
I created a counter, cnt, which is incremented after each question.
There is a function called ask_next_ques() that takes the parameter cnt. Depending on where we are in the survey, it asks the next question (eg. when cnt==3 it asks the third question).
Unfortunately, javascript insists that all strings be on one line. Therefore, I built the html like this:
var qq = '
<ul style="list-style:none">
<li>
What can you curl?<br />
<input type="text" id="curl"> Kg
</li>
<li>
What can you bench?<br />
<input type="text" id="bench"> Kg
</li>
<li>
What can you lift?<br />
<input type="text" id="lift"> Kg
<input type="button" id="cbl_btn" value="Go">
</li>
</ul>
';
and then re-arranged it onto one line, like this:
var qq = '<ul style="list-style:none"><li>What can you curl?<br /><input type="text" id="curl"> Kg</li><li>What can you bench?<br /><input type="text" id="bench"> Kg</li><li>What can you lift?<br /><input type="text" id="lift"> Kg<input type="button" id="cbl_btn" value="Go"></li></ul>';
Much more difficult to read that way, but that's how javascript wants things.
As each question is answered, the responses are read by javascript/jQuery and then saved into hidden fields inside the <form> structure.
When all questions have been asked, you can just POST the form to another (PHP?) file for processing (storage in a MySQL database?), or email the answers to yourself, or re-display them to the user, or... I chose to display the answers in a lightbox.
Here is all the code. Just copy/paste it into a single HTML or PHP file, and run.
SURVEY.PHP
<html>
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<link rel="stylesheet" href="http://code.jquery.com/ui/1.9.1/themes/base/jquery-ui.css" /><!--Lightbox-->
<script src="//ajax.googleapis.com/ajax/libs/jqueryui/1.9.1/jquery-ui.min.js"></script><!--Lightbox-->
<style>
</style>
<script type="text/javascript">
//Declare vars outside document.ready() so they can be accessed globally
var ctr = 1;
var mf = '';
var pl = '';
$(document).ready(function() {
ask_next_ques(ctr);
/* ------------------------------------------------------------ */
$("input:radio[name=gender]").click(function() {
//Note: var mf must be initialized above (outside document.ready() ) so can be used in below fn ask_next_ques()
mf = $('input:radio[name=gender]:checked').val();
$('#hgender').val(mf);
ctr++;
ask_next_ques(ctr);
});
/* ------------------------------------------------------------ */
$(document).on('click', "#cbl_btn", function() {
var cc = $("#curl").val();
var bb = $("#bench").val();
var ll = $("#lift").val();
//alert('Value of cc: ' +cc+ ' Value of bb: ' +bb+ ' Value of ll: ' + ll);
//Check if any one of these fields left empty
if (cc.length<1 || bb.length<1 || ll.length<1) {
alert("Please complete all fields");
}else{
$('#hcurl').val(cc);
$('#hbench').val(bb);
$('#hlift').val(ll);
ctr++;
ask_next_ques(ctr);
}
});
/* ------------------------------------------------------------ */
$(document).on('click', "input:radio[name=plan]", function() {
//Note: var pl must be initialized above so can be used in below fn ask_next_ques()
pl = $('input:radio[name=plan]:checked').val();
$('#hplan').val(pl);
ctr++;
ask_next_ques(ctr);
});
/* ------------------------------------------------------------ */
}); //END $(document).ready()
function ask_next_ques(ctr) {
if (ctr==1) {
var qq = 'Male: <input value="Male" type="radio" name="gender"><br />Female: <input value="Female" type="radio" name="gender">';
$('#ques').html(qq);
}else if (ctr==2){
var qq = '<ul style="list-style:none"><li>What can you curl?<br /><input type="text" id="curl"> Kg</li><li>What can you bench?<br /><input type="text" id="bench"> Kg</li><li>What can you lift?<br /><input type="text" id="lift"> Kg<input type="button" id="cbl_btn" value="Go"></li></ul>';
$('#ques').html(qq);
}else if (ctr==3){
var qq = 'Are you an:<br />Owner: <input value="Owner" type="radio" name="plan"><br />Member: <input value="Member" type="radio" name="plan">';
$('#ques').html(qq);
}else if (ctr==4){
//All questions have been asked; All responses saved into hidden fields
//Can now read all hidden fields and do an AJAX POST into the database, or
//Or can simply POST the form to another page for processing.
alert("All questions have been asked");
var hg = $('#hgender').val();
var hc = $('#hcurl').val();
var hb = $('#hbench').val();
var hl = $('#hlift').val();
var hp = $('#hplan').val();
qq = 'The values saved into all hidden fields are:<br />Gender: ['+hg+ ']<br />Curl: [' +hc+ ']<br />Bench: [' +hb+ ']<br />Lift: [' +hl+ ']<br />Plan: [' +hp+ ']<br />You can now send these values to a<br />database, or email them to yourself.';
$('#ques').html(qq);
//We could just leave it here, but to be interesting we'll display the results in a lightbox
//To remove all lightbox stuff, just delete the next 8 lines and delete the two lightbox references in the header (for jquery-ui)
$('#ques').dialog({
autoOpen:true,
width: 450,
title: "Hidden Field Valuess:",
close: function() {
alert('Thank you for taking our survey');
}
});
}
}
</script>
</head>
<body>
<div id="ques"></div>
<div id="hidden_form">
<form method="POST">
<input type="hidden" id="hgender" name="gender">
<input type="hidden" id="hcurl" name="curl">
<input type="hidden" id="hbench" name="bench">
<input type="hidden" id="hlift" name="lift">
<input type="hidden" id="hplan" name="owner">
</form>
</div>
</body>
</html>

Related

Setting a var in localStorage from button radio and pass it to other pages

This discussion is the spin off of this post:passing-variables-between-pages,
I have edited the question in order to provide More clarity on the scripts, please who will give any answers to use denomination used in this version.
A.html
<form action="b.html"> // username field, let's say "Macbeth"
<input type="text" id="txt"/>
<input type="submit" value="nome" onClick="passvalues();"/>
</form>
<span id="result">Macbeth</span> // display username
<script>
function passvalues()
{
var nme = document.getElementById("txt").value; // set var username nme = textvalue
localStorage.setItem("textvalue", nme);
return false;
}
</script>
It works set localStorage and display it.
B.html
// show the username multiple times in an html text.
<p><strong><span class="result">Macbeth</span></strong>, Nice name!
It's the first time I've heard it! mmm...and tell me<strong>Macbeth<span class="result"></span></strong> which gender you are?</p>
<form name="genderForm" action="">
<input type="radio" name="gender" value="male"> Male<br>
<input type="radio" name="gender" value="female"> Female<br>
<input type="radio" name="gender" value="neutral"> Neutral
</form>
// form to obtain the gender chosen by the user, let's say "male"
`<p>I am a <span class="selectedGender"></span> of course!</p>`
// display the selected gender
<script>
var result = document.getElementsByClassName('result');
[].slice.call(result).forEach(function (className) {
className.innerHTML = localStorage.getItem("textvalue");
});
var rad = document.genderForm.gender;
var prev = null;
for (var i = 0; i < rad.length; i++) {
rad[i].addEventListener('change', function () {
(prev) ? console.log(prev.value) : null;
if (this !== prev) {
prev = this;
}
console.log(this.value);
document.getElementsByClassName("selectedGender")[0].innerHTML = this.value;
localStorage.setItem("gender", this.value);
});
}
</script>
<script>
var selectedGender = document.getElementsByClassName('selectedGender');
{
className.innerHTML = localStorage.getItem("textvalue");
};
</script>
It works, display the selected gender.
C.html
I am really, really sorry but I am completely lost and confused here.
I tried several times one of the suggested by solutions:
<span id="welcome"></span> to page 4 <span id="name"></span>
<script>
var username = localStorage.getItem("textvalue");
var usergender = localStorage.getItem("gender");
document.getElementById('name').innerHTML = username;
document.getElementById('gender').innerHTML = usergender;
if (usergender === 'female'){
document.getElementById('welcome').innerHTML = 'brava';
}else if (usergender === 'male'){
document.getElementById('welcome').innerHTML = 'bravo';
}else{
document.getElementById('welcome').innerHTML = 'bene';
}
</script>
I know I'm a hopeless case, I don't understand it.
In which page do I have to insert this script?
this script replaces the previous ones?
Can't I use the same scripting used for the username?
1 - get the choice:"selectedgender"
2 - display it with (of course changing the elements names)
<script>
function passvalues()
{
var nme = document.getElementById("txt").value; // set var username nme = textvalue
localStorage.setItem("textvalue", nme);
return false;
}
</script>
3 - and show with:
<span id="result">Macbeth</span> // display username
Thanks for the attention.
To make life a little easier for you, I re-wrote your scripts using slightly different variable names that make a little more sense. I tested these; they work. If you print both sets and compare these NEW scripts with the older scripts, you can see a little more clearly how it all works.
Page A:
<form action="b.html">
<input type="text" id="txt"/>
<input type="submit" value="nome" onClick="passvalues();"/>
</form>
<span id="result"></span>
<script>
function passvalues(){
var nme = document.getElementById("txt").value; // set var username nme = youzer
localStorage.setItem("youzer", nme);
return false;
}
</script>
Page B:
<!-- show the username multiple times in an html text. -->
<p>Hello, <strong><span class="uname">Macbeth</span></strong>, Nice name!</p>
<p>It's the first time I've heard it! mmm...and tell me, <strong><span class="uname"></span></strong>, which gender you are?</p>
<form name="genderForm" action="">
<input type="radio" name="gender" value="male"> Male<br>
<input type="radio" name="gender" value="female"> Female<br>
<input type="radio" name="gender" value="neutral"> Neutral
</form>
<p>I am a <span class="selectedGender"></span> of course!</p>
<script>
/* Schlep stored name into all elements with className "uname" */
var unamez = document.getElementsByClassName('uname');
[].slice.call(unamez).forEach(function (className) {
className.innerHTML = localStorage.getItem("youzer");
});
var frmGender = document.genderForm.gender;
var prev = null;
for (var i = 0; i < frmGender.length; i++) {
frmGender[i].addEventListener('change', function () {
(prev) ? console.log(prev.value) : null;
if (this !== prev) {
prev = this;
}
console.log(this.value);
document.getElementsByClassName("selectedGender")[0].innerHTML = this.value;
localStorage.setItem("gender", this.value);
//Delay 2 seconds, then go to page (C)
setTimeout(function(){
window.location.href = 'c.html';
},2000);
});
}
</script>
Page C:
<span id="greetz"></span> to page 4, <span id="name"></span>!
<p></p>Return to page A</p>
<script>
var username = localStorage.getItem("youzer");
var usergender = localStorage.getItem("gender");
document.getElementById('name').innerHTML = username;
// Below commented out because <span id="gender"> does not exist on page
// document.getElementById('gender').innerHTML = usergender;
if (usergender === 'female'){
document.getElementById('greetz').innerHTML = 'Brava';
}else if (usergender === 'male'){
document.getElementById('greetz').innerHTML = 'Bravo';
}else{
document.getElementById('greetz').innerHTML = 'Bene';
}
</script>
Note that these code snippets don't "work" on StackOverflow - the Run Code Snippet buttons won't do anything. I used the Code Snippet system only to allow the three code groups to be hidden until expanded, for neatness. You must copy each one out and paste it into a file in your dev environment to make them work (all three must be present on your system before running them).
Your page3.html can be as below:
<!DOCTYPE html>
<html>
<head>
<title>Page 3</title>
</head>
<body>
<p><span id="name"></span>, please select your gender.</p>
<a id="Male" href="page4.html" onclick="saveSelectedGender(this)">Male</a><br/>
<a id="Female" href="page4.html" onclick="saveSelectedGender(this)">Female</a><br/>
<a id="Neutral" href="page4.html" onclick="saveSelectedGender(this)">Neutral</a><br/>
<script>
document.getElementById('name').innerHTML = localStorage.getItem("textvalue");
function saveSelectedGender(ele) {
localStorage.setItem('gender', ele.id);
}
</script>
</body>
</html>
and your page4.html can be as below:
<!DOCTYPE html>
<html>
<head>
<title>Page 4</title>
</head>
<body>
<p><span id="name"></span>, your selected gender is: <span id="gender"></span>.</p>
<script>
document.getElementById('name').innerHTML = localStorage.getItem("textvalue");
document.getElementById('gender').innerHTML = localStorage.getItem("gender");
</script>
</body>
</html>
Notice this line on page two:
localStorage.setItem("gender", this.value);
It is almost exactly the same as the line on page 1 that stores the user name:
localStorage.setItem("textvalue", nme);
In your hidden localStorage, you now have two variables: gender and textvalue, and each of them stores some information. Check it for yourself - there is a way to view the localStorage area:
INSTRUCTIONS FOR GOOGLE CHROME:
1. Run your app, and enter the data on both page 1 and page 2.
2. Press <kbd>F12</kbd> (or, right-click on the page and choose `Inspect Element`)
3. "Developer Tools" will open.
4. Note the menu at top that begins: `Elements | Console | Sources | Network >>`
If the last menu item is `>>` then click that - additional menu choices will drop-down
5. You want the menu item `Application` - click on that
6. You will see 5 groupings on the left: Application, Storage, Cache, Background... etc
7. In the Storage group, do you see `Local Storage`? That's what we want!
8. Click the drop-down triangle beside (at the left) "Local Storage"
9. Now, in the right side panel, you should see your "hidden" variables, and their current values
No matter what HTML page you are on (of your project), you can see those same variables - so you can tell your script to read those variables.
So, on pages 3 and 4, write some javascript (the code is below) that will:
(a) read a localStorage value and store it in a new variable
(b) select the appropriate element (div, span, p, etc) on that page
(c) stick the variable data into the element.
(d) repeat for the other localStorage entry
The reason why the existing javascript code didn't work is because it was written for page2, where the target element is called class="result". Note the first line of the javascript:
var bob = document.getElementsByClassName('result');
(I changed the name of the variable because that name doesn't matter - what matters is getElementsByClassName('result')). If there is no element on the page with class="result", the javascript will fail right there. So, on pages 3 and 4, death!
On page 4, then, you can do this:
<span id="welcome"></span> to page 4 <span id="name"></span>
<script>
var username = localStorage.getItem("textvalue");
var usergender = localStorage.getItem("gender");
document.getElementById('name').innerHTML = username;
document.getElementById('gender').innerHTML = usergender;
if (usergender === 'female'){
document.getElementById('welcome').innerHTML = 'brava';
}else if (usergender === 'male'){
document.getElementById('welcome').innerHTML = 'bravo';
}else{
document.getElementById('welcome').innerHTML = 'bene';
}
</script>
Final Notes:
The reason you do not need this nifty bit of code:
[].slice.call(result).forEach(function (className)...
is because THIS code var result = document.getElementsByClassName('result')
creates a list (an array) of all the elements with the className result. Then the .slice code loops through that array and schleps the username into each and every element.result. Only on page 2 do you have an element (well, two elements) with the className "result". On page 3 (NO className "result") elements, the code fails.

Compare input text with person name belongs to only one input number id

Im trying to write a validation for 2 groups of fields. I have 6 inputs, 3 for text name and 3 more for id number... the validation should do this "if input name="RE_SignedByID" has an input type name="RE_SignedByName", then other inputs name="RE_SignedByID", should NOT contain the same name="RE_SignedByName" More easy explanation... one ID number should have only one Person Name (Id number is unique for one person name). What can I use for that? Should I map() all the inputs?
Those are my inputs:
<div id="signedBy" class="clearfix">
<label>Signer, person ID & name</label>
<span id="signedByID" class="ids half">
<input type="text" name="RE_SignedByID" placeholder="personID, person1" data-validate="" tabindex="101" required>
<input type="text" name="RE_SignedByID" placeholder="personID, person2" data-validate="" tabindex="103">
<input type="text" name="RE_SignedByID" placeholder="personID, person3" data-validate="" tabindex="105">
</span>
<span class="names half">
<input type="text" name="RE_SignedByName" placeholder="name, person1" tabindex="102" required>
<input type="text" name="RE_SignedByName" placeholder="name, person2" tabindex="104">
<input type="text" name="RE_SignedByName" placeholder="name, person3" tabindex="106">
</span>
</div>
I guess it should also be an "on change" function? or can I make the validation on click? Some ideas...? Im actually compleatley lost here...
Thanks in advance!!!
Maybe use different class names for all 3 of them to make them unique?
<input class="name1">
<input class="name2">
<input class="name3">
I'm not sure what you mean but if you want to make the input types unique and not call them all when you write class="names half", then you should give them all unique class names.
So from my understanding you don't want multiple fields to have the same value.
My approach would be this:
let inputTimeout = null; //set an empty timeout object
let vars = [null, null, null, null]; // create an array containing as many nulls as you have inputs
$('.nameInput').on('keyup', function(){
let self = $(this);
clearTimeout(inputTimeout); //clear the timeout
inputTimeout = setTimeout(function(){ //set a timeout to check whether there is a dupe after the user has stopped typing
if (vars.indexOf(self.val()) == -1){ //check if the vals array contains the newly entered string
vars[self.attr('data-inputnum')] = self.val(); //insert the value into the array
}else{
//handle duplicates here
}
}, 500); //500ms is a sensible value for end of user input, change it if users complain that your app is too fast/slow
});
You then just have to edit your HTML a bit so that all name inputs have a class in common (i used .nameInput) and have a data-inputnum attr.
This would look something like this:
<input type="text" name="RE_SignedByName" placeholder="name, person1" tabindex="102" class='nameInput' data-whichinput='0'/>
<input type="text" name="RE_SignedByName" placeholder="name, person2" tabindex="103" class='nameInput' data-whichinput='1'/>
<!--and so on-->
Of course, never rely on JavaScript verification alone, always also check inside your backend. However this would be out of scope for this answer.
Hi Thanks all for the help, made me realize a couple of things till I got the answer. This is my working code:
var valSignedID = $("[name=SignedByID]").map(function() {
return this.value.trim();
}).get();
var valOwnersID = $("[name=OwnersID]").map(function() {
return this.value.trim();
}).get();
valSignedID.sort();
valOwnersID.sort();
for (var i = 0; i < valSignedID.length - 1; i++) {
if (valSignedID[i] == valSignedID[i + 1] && valSignedID[i] != "") {
alert(" You can not have duplicated signers ID's");
return false;
// break;
}
}
for (var i = 0; i < valSingedName.length; i++) {
if (valSingedName[i] == valSingedName[i + 1] && valSingedName[i] != "") {
alert(valSingedName[i] + " should not have different ID");
//return false;
}
}

how to get the results of an answer and perform calculations on that result

Javascript code:
function suma(){
var sum1 = document.getElementById("sum1");
var sum2 = document.getElementById("sum2");
var input = document.getElementById("resultado");
resultado = (sum1.value * sum2.value);
input.value= resultado;
}
How do I perform a 1% calculation on the answer from the variable resultado and put the answer inside premium?
My code for doing that:
function percentage(){
var resultado = document.getElementById("resultado").value;
var input = document.getElementById("premium");
var premium = (0.01*resultado.value);
input.value = premium;
}
the html codes
<input type="number" class="form-control" required onblur="if(this.value
== ''){this.value='0'}" onKeyUp="suma();" id="sum2" name="Weight"
value="0" />
<input type="text" class="form-control" onblur="if(this.value == '')
{this.value='0'}" onKeyUp="suma();" id="sum1" name="variable"
value="3.25" readonly="readonly" />
<input type="text" class="form-control" name="shipping_subtotal"
id="resultado" value="0" />
<input type="number" class="form-control" id="insurance"
name="insurance" onblur="if(this.value == ''){this.value='0'}"
name="variable" value="0.01" readonly="readonly" >
<input type="number" class="form-control" id="premium" name="premium"
value="0" onKeyUp "percentage();" >
You have quite a few minor errors in the code. Don't worry though, they're easy to overlook in there. One thing to keep in mind when developing is to keep your concerns separated, because your future self and other developers who work with your code will thank you. What I mean by separation of concerns in this context is logic vs templating. HTML is where templating belongs, and JavaScript is your logic. When you write inline JavaScript, like <input onblur="if(this.value == ''){this.value='0'}">, it makes your JavaScript very difficult to follow and maintain. In your JavaScript file, you can use document.getElementById('demo').onblur = if(this.value == ''){this.value='0'}; instead, and now all your logic can be found in one place. Personally, I prefer event listeners, because unlike onblur, you can assign multiple functions to the given event and you run less risk of overwriting any functionality that was written somewhere else.
Assuming var el = document.getElementById('demo');
METHOD 1:
el.onblur = if(this.value == ''){this.value='0'};
// This overwrites the onblur function from the line above
el.onblur = alert('hello');
METHOD 2:
el.addEventListener('blur', function() { if(this.value == ''){this.value='0'} });
// This does not overwrite the function above,
// instead, it just adds another function to the event.
el.addEventListener('blur', function() { alert('hello'); });
That aside, I believe your code will work with a few fixes to your errors. To help you out, I wrote an alternative to your scripts above. I'm not sure if I got everything the way you intended, though, so feel free to tweak it and make it your own.
var sum1 = document.getElementById("sum1");
var sum2 = document.getElementById("sum2");
var resultado = document.getElementById("resultado");
var premium = document.getElementById("premium");
var insurance = document.getElementById("insurance");
function calculateFields() {
var suma = (sum1.value * sum2.value);
resultado.value = suma;
premium.value = (0.01 * suma);
}
var inputs = [sum1, sum2, resultado, premium, insurance];
inputs.forEach(function(el) {
el.addEventListener('blur', function() {
this.value = this.value === '' ? 0 : this.value;
});
el.addEventListener('input', calculateFields);
});
Mess around with the code on jsfiddle.

3 text box Math in Javascript

Hi I am NewBee in Javascript. This is my second week.
Below is the code that has a form with three input fields.
The relationship of the fields is:
the second field is twice the value of the first field
the third field is the square of the first field
I have managed to do the above but i am not able to do the below :
If a user enters a value in the second or third field, the script should calculate the appropriate value in the other fields. Currently the code works well ONLY if I enter the value in the first field.
I hope I explained well in other words : how do I enter say 144 in the last textbox and the other 2 textboxes show 12 and 24 respectively. Or If I enter 24 first and first and the third text boxes show 12 and 144.
Thanks
Vipul
<html>
<head>
<script>
window.onload = init;
function init() {
var button = document.getElementById("usrButton");
button.onclick = save;
onkeyup = doMath;
function doMath(){
var base = document.getElementById("base").value;
var baseNumber_timesTwo = document.getElementById("baseNumber_timesTwo").value = (base*2);
var baseNumber_square = document.getElementById("baseNumber_square").value = (base*base) ;
}
}
</script>
</head>
<body>
<form>
<input type="text" name="base" id="base" onkeyup= "doMath()">
<br><br>
<input type="text" name="baseNumber_timesTwo" id="baseNumber_timesTwo" onkeyup= doMath()>
<br><br>
<input type="text" name="baseNumber_square" id="baseNumber_square" onkeyup= doMath()> <br><br>
</form>
</body>
</html>
take a look at the code below:
<html>
<head>
<script>
window.onload = init;
var init = function(){
var button = document.getElementById("usrButton");
button.onclick = save;
onkeyup = doMath;
}
var doMathbase = function(){
console.log('here');
var base = document.getElementById("base").value;
var baseNumber_timesTwo = document.getElementById("baseNumber_timesTwo").value = (base*2);
var baseNumber_square = document.getElementById("baseNumber_square").value = (base*base) ;
}
var doMathBase2Time = function(){
var baseNumber_timesTwo = document.getElementById("baseNumber_timesTwo").value;
var base = document.getElementById("base").value = (baseNumber_timesTwo/2);
var baseNumber_square = document.getElementById("baseNumber_square").value = (base*base) ;
}
</script>
</head>
<body>
<form>
<input type="text" name="base" id="base" onkeyup= "doMathbase()">
<br><br>
<input type="text" name="baseNumber_timesTwo" id="baseNumber_timesTwo" onkeyup= "doMathBase2Time()">
<br><br>
<input type="text" name="baseNumber_square" id="baseNumber_square" onkeyup= "doMathBaseSquare()">
<br><br>
</form>
</body>
You need to bind another function to the second and third field. I did it to the second. Now if you entered a number in the second field it return the 'base' number and the square of the base.
Try do it for the third :)
This should fit your needs:
Fiddle
//declaring those earlier saves you to get those by ID every
//time you call "doMath()" or something else
var base = document.getElementById("base");
var baseNumber_timesTwo = document.getElementById("baseNumber_timesTwo");
var baseNumber_square = document.getElementById("baseNumber_square");
function clearUp() {
base.value = "";
baseNumber_timesTwo.value = "";
baseNumber_square.value = "";
}
function doMath() {
//check which of the fields was filled
if(baseNumber_timesTwo.value){
base.value = baseNumber_timesTwo.value / 2;
}
if(baseNumber_square.value){
base.value = Math.sqrt(baseNumber_square.value);
}
//fill other fields according to that
baseNumber_timesTwo.value = (base.value*2);
baseNumber_square.value = (base.value*base.value) ;
}
As you see: There is no need to write more than one arithmetic function if you make sure that only one value is given at the time of evaluation (this is achieved by the cleanUp()
method)
However there are still some flaws in this solution! Since you are a js beginner I would suggest you to read the code and think about possible solutions for those problems as a little exercise :-)
- You cannot enter a 2 (or more) digit number in any field, why not? What do you have to change in order to allow such numbers as input?
- Why is it better (in this case!) to set the values to " " instead of '0' in the cleanUp function? Why does the code break when you try using '0' instead of "" ?
- Why does doMath() only check for values in the last two field (baseNumber_timesTwo and baseNumber_square) while ignoring the 'base' field?
Greetings, Tim

Build, Modify, Output Javascript Array

I'm trying to accomplish the following...if it's asking too much in a single question then some simple steps on what events to use will still help.
There are 2 blank textareas sitting next to eachother - Input and Output. Between them are two inputs Before and After. I want to type or paste a list of words into Input separated by line break, for example:
melons
peaches
apples
And then use the Before and After inputs to add in a word/phrase/symbol before and after each keyword. So if I type 'buy' in before and 'today' in after, the Output text area will display:
buy melons today
buy peaches today
buy apples today
I'd like to accomplish this without having any page refreshing. We can assume the form elements are named as follows:
<textarea id="input"></textarea>
<input type="text" id="before" />
<input type="text" id="after" />
<textarea id="output"></textarea>
I've been try to at least get the Input text to display in Output using this code, but that's not even working:
$(document).ready(function(){
$('#input').keyup(function(e){
$('#output').html($(this).val());
});
});
Any guidance would be awesome!
a compact one:
$("#input,#before,#after").on("keyup", function () {
$("#output").val(
$.map($("#input").val().split("\n"), function (n, i) {
return $("#before").val() + " "+ n + " " + $("#after").val();
}).join("\n"));
});
example
This would do the trick:
function update_output(){
//Split input by newline
var input_words = $('#input').val().split('\n');
var output_lines = new Array();
//Iterate over each keyword and prepend and append values
$.each(input_words, function(i, word){
output_lines.push($('#before').val()+' '+word+' '+$('#after').val());
});
//Display output in textarea
$('#output').val(output_lines.join('\n'));
}
You just need to choose when you want to update the output textarea, maybe bind it so it updates every time the #input or #before and #after changes:
$('#input,#before,#after').on('change',update_output);
Alright, I can help you to get started. My answer is not complete, but you can have a very good idea from here. Note I wrote this code to be easy to understand and I am not using sophisticated approaches on purpose.
<html>
<head>
<script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
<script>
$( document ).ready(function() {
$("#input").keypress(function(key){
if(key.which == 13) {
refreshData();
}
});
});
function refreshData() {
var beforeVal = $("#before").val();
var inputLines = $("#input").val().split(/\r\n|\r|\n/g);
var desiredOutputVal = "";
for(var i=0; i<inputLines.length; i++) {
desiredOutputVal += beforeVal + inputLines[i] + "\n";
}
$("#output").val(desiredOutputVal);
}
</script>
</head>
<body>
<form>
<textarea id="input"></textarea>
<input type="text" id="before" />
<input type="text" id="after" />
<textarea id="output"></textarea>
</form>
</body></html>

Categories

Resources