Trouble setting variables from form inputs. Radio and Text entries - javascript

I am attempting to create an equation using people's pay rates and some other information from a from. However, I can't even get variables to set based on information from the form. The form includes 1 set of radio buttons and 2 text input forms.
<form id="userInfo" action="" method="post">
<p>Pay Frequency: <select name="payFreqS">
<option>Hourly</option>
<option>Weekly</option>
<option>Bi-Weekly</option>
<option>Monthly</option>
</select></p>
<p>Pay Rate:<input type="text" name="payRateS" value="0000.00">
</p>
<p>Cost of Item:<input type="text" name="costS" value="000.00">
</p>
</form>
<p><input name="submit" type="submit" class="btn" value="Submit" onclick="shouldIBuy()"/></p>
Javascript:
function shouldIBuy()
{
// attempt to find error with console statements
console.log("How far can we get?");
// setting variables for my function
var payRate = document.getElementByIds("payRateS").value;
var cost = document.getElementById("costS").value;
// pay frequency variable
var payFreq = document.forms[0].payFreqS;
var i;
for (i=0;i<payFreq.length;i++)
{
if (payFreq[i].checked)
{
payFreqVal = i;
}
}
//more console.log statements to troubleshoot
console.log(cost);
console.log(payRate);
console.log(payFreq);
// setting what I hoped were strings to integers.
var payRateInt = parseInt(payRate);
var costInt = parseInt(cost);

There should be errors in your console because you are using the non-existent getElementByIds.

I went back and broke it down to the very basic elements to figure out was going on. I was not referencing the right things. You were right. Thanks.

Related

Passing variables between pages using localStorage and passing variables in a link

I am learning js, recently, I apologize for my English and for the obviousness of my questions. I have two problems, I would appreciate solutions in pure JavaScript.
Following several tutorials, I installed a localStorage script in an HTML page.
pag1.html
<p> Hello! what's your name?</p>
<form action="pag2.html">
<input type="text" id="txt"/>
<input type="submit" value="nome" onClick="passvalues();"/>
</form>
// the form has a link to pag2.html
<script>
function passvalues()
{
var nme=document.getElementById("txt").value;
localStorage.setItem("textvalue",nme);
return false;
}
</script>
Let's say the user enters the name "Lucy":
pag2.html
<p>Hi <span id="result">Lucy<span> nice to meet you!</p>` // the name appears
<p>How are you today <span id="result">NOTHING</span>?</p>` // the name does not appear
pag3
<script>
document.getElementById("result").innerHTML = localStorage.getItem("textvalue");
</script>
First Question
the NAME appears only once for my mistake or must it be so? Should I use another syntax to make it appear several times?
pag3.html
<p><span id="result">Lucy</span>which gender designation do you prefer to be used with you?</p>
<p>male</p>
<p>female</p>
<p>neutral</p>
<script>
document.getElementById("result").innerHTML = localStorage.getItem("textvalue");
</script>
Second Question
In pag 3 the user has to choose whether he wants to be called male, female or neutral.
One solution is to set three different pages according to the genre chosen. But this solution is not elegant and inflates the number of pages.
I seem to have read somewhere that with js it is possible to go to another page and at the same time set the value of a Boolean variable (true / false) through a link.
Something like this (the syntax is invented):
<a href="female.html" set var f true> female</a>
This would allow you to create a single landing page with the insertion of three "if":
if (female true) {
text = "brava";
} else if (male true) {
text= "bravo";
} else {
text = "bene";
}
Is it possible to do this? How?
I have tried this script htmlgoodies several times but it is too difficult for me.
Hello,
First of all I'd thank #cssyphus and #Shahnawazh for the answers.
Question 1
I managed to show the name several times on the same page with the script:
<script>
var result = document.getElementsByClassName('result');
[].slice.call(result).forEach(function (className) {
className.innerHTML = localStorage.getItem("textvalue");
});
</script>
But, do I really need to include it on all pages that need to show the name?
I also tried to insert the script into an external js page but the name did not appear even once.
Question 2
As for the second question, I did not get positive results.
Rather than using id, you can use class for showing result because id is unique. Also for storing male, female or neutral you can use radio buttons, and when you click any of them, just save the result in the localStorage. Here are the three pages.
page1.html
<body>
<p> Hello! what's your name?</p>
<form action="page2.html">
<input type="text" id="txt" />
<input type="submit" value="name" onClick="passvalues();" />
</form>
<script>
function passvalues() {
var nme = document.getElementById("txt").value;
localStorage.setItem("textvalue", nme);
return false;
}
</script>
</body>
page2.html
<body>
enter code here
<p>Hi <span class="result">Lucy<span> nice to meet you!</p>
<p>How are you today <span class="result"></span>?</p>
page3
<script>
var result = document.getElementsByClassName('result');
[].slice.call(result).forEach(function (className) {
className.innerHTML = localStorage.getItem("textvalue");
});
</script>
</body>
page3.html
<body>
<p><span class="result"></span> which gender designation do you prefer to be used with you?</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>You've selected <span class="selectedGender"></span></p>
<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>
</body>
You have just discovered why you cannot have two elements on the same page with the same ID - only the first one will work. However, classes work almost exactly like IDs, so just use the same className at both locations:
<p>Hi <span class="result">Lucy<span> ...
...
<p>How are you today <span class="result">Lucy</span> ...
As to your second problem, just use localStorage again. Set a different localStorage variable and read/write that.
However, what you are probably thinking of is using a query string, like this:
female
See this SO question for information and code examples.

how to get the current values of an input on button click event

I have a bunch of div's that have the same functionality and I'm trying to write a function for them.
Basically they have a predetermined value and a user input value and those need to be multiplied.
I've looked through a bunch of other questions and this is the closest one I could find. Almost exactly, but none of those answers work.
Any help would be great. Thanks in advance!
<div>
<label>enter value for multiple here</label>
<input type="text" class="multiple" factor="foo1"/>
<button type="button" class="multiplyBtn">Click here to multiply these numbers</button>
<label>enter value for multiple here</label>
<input type="text" class="multiple" factor="foo2"/>
<button type="button" class="multiplyBtn">Click here to multiply these numbers</button>
</div>
Here's the JS:
$('.mulitplyBtn').click(function() {
var factor = $(this).closest('attr.factor').val();
var multiple = $(this)closest('.multiple').val();
answer = (factor * multiple);
};
This would work:
$('.multiplyBtn').click(function() { // you had multiplyBtn spelled wrong here
var cur = $('.multiplyBtn').index($(this)); // get index of clicked btn
var factor = $('.multiple').eq(cur).data('factor'); // get factor from matching input
var multiple = $('.multiple').eq(cur).val(); // get value from matching input
answer = (Number(factor) * Number(multiple)); // make sure both are numbers then multiply
alert(answer);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
<label>enter value for multiple here</label>
<input type="text" class="multiple" data-factor="4" />
<button type="button" class="multiplyBtn">Click here to multiply these numbers</button>
<br>
<label>enter value for multiple here</label>
<input type="text" class="multiple" data-factor="7" />
<button type="button" class="multiplyBtn">Click here to multiply these numbers</button>
</div>
In the first line you used " and ' try using the same quotes (I mean using ".multiplyBtn" or '.multiplyBtn' )
Second time, 3rd line you didn't use any quote when calling .multiple. So turn it in that format : var multiple = $(this)closest('.multiple').val()
let me know the result
You have at least two typos and are using the wrong jQuery function.
Typos:
$('.mulitplyBtn') should be $('.mulitplyBtn')
$(this)closest should be $(this).closest
Wrong function:
closest() searches the parents, and the only parent here is the DIV with no class. What you probably want is to use parent() to go up to the DIV, then find() to search the parent's children for a specific element:
$(this).parent().find('.multiple').val()
attr.factor does not work like this.
try it like this:
$('.multiplyBtn').click(function() {
var container = $(this).prev('.multiple'); //don't forget the "dot"
var multiple = container.val();
var factor = container.attr('factor'); //since it is the same container.
var answer = (factor * multiple); //what exactly are you tryin to multiply?
};

Dropdown list to JavaScript array to fill text boxes

I am trying to display a MySQL table on a job sheet system form that I am making the drop down list shows the customer details and then once selected the fields should be filled in on the main form.
I know people tend to use AJAX but this is to be used on a tablet tethered to a mobile and want to ask the server as little as possible.
Because I have already got the details from the SQL to display the drop down I thought I could use this. I found the original code at:
http://board.phpbuilder.com/showthread.php?10372137-RESOLVED-How-do-I-populate-multiple-text-boxes-from-a-dropdown-(I-can-populate-1-text-box!)
but I also want to display items that aren't on the dropdown list. Someone said it works but the more I have learned I couldn't see how because the array it was building just didn't seem to be in a JavaScript format.
I have the drop down working and also it fills a JavaScript array using names but I just cannot work out how to use the array to show in the fields.
It seems to be the named indexes used in the array. I can get a test array to display when I use the normal static array but I have commented them out but as soon as I try to use the names on the array I get undefined errors.
<html>
<head>
<script type="text/javascript">
<?php
include_once 'includes/db_connect.php';
$query1 = "SELECT * FROM customer";
$result1 =($mysqli-> query($query1));
// build javascript array building an object
// build javascript array
while($row=mysqli_fetch_array($result1)){
echo 'customer['.$row['customer_id'].'] = new Array(';
echo 'customer['.$row['customer_id'].'][customer_id] = "'.$row['customer_id'].'";';
echo 'customer['.$row['customer_id'].'][post_code] = "'.$row['post_code'].'";';
echo 'customer['.$row['customer_id'].'][company_name] = "'.$row['company_name'].'");';
}
?>
</script>
</head>
<body>
<form name="customerform" form id="customerform">
<p>
<select name="customerselect" id="customerselect" onChange="showname()">
<option value="">Select customer</option>
<?php
$query1 = "SELECT * FROM customer";
$result1 =($mysqli-> query($query1));
// build javascript array
while($row=mysqli_fetch_array($result1)){
echo'<option value="'.$row['customer_id'].'">'.$row['forename'].'">'.$row['surname'].'">'.$row['customer_name'].'</option>';
}
?>
</select>
</p>
<p>
<input type="text" name="cust" value="" id="cust" />
<input type="text" name="cust" value="" id="customerselected" />
<input type="text" name="post_code" value="" id="post_code" />
</p>
<p>update
<input type="button" name="update" id="update" value="update" onClick="showname()">
<p> </p>
<p>
<input name="submit" type="submit" id="submit" value="submit" />
</p>
</form>
</body>
<script>
//var customer = Array();
var customer = Array();
//This below is a test multi dimensional Array which does work. //
//customer['CCS'] = Array[{forename:'Robert', surname:'Grain', company:'HOMS'}];
function showname() {
//this var takes the result of the selected drop down list and shows the correct part of the array.
var customerselected = document.getElementById('customer');
customername = customerselected.value;
// this does work but not from the array just fills the details up
document.customerform.customerselected.value = customername;
// the next part takes the selected dropdown data and calls for the correct place in the array
// document.getElementById("cust").value = customer['CCS'][0];
// document.getElementById("cust").value = customer[CCS]["forename"] ;
// (customer[''][forename]);
document.customerform.post_code.value = customer[customerselect]["post_code"];
}
window.onload=function() {
showname();
}
</script>
</html>
This is the source code from Explorer in the console. from the JavaScript Array.
</body>
</html>customer[118] = new Array(customer[118][customer_id] = "118";customer[118][post_code] = "L37 4RG";customer[118][company_name] = "jc knight");customer[119] = new Array(customer[119][customer_id] = "119";customer[119][post_code] = "DE56 7HG";customer[119][company_name] = "farm Customer giles");customer[122] = new Array(customer[122][customer_id] = "122";customer[122][post_code] = "LE67 8FH";customer[122][company_name] = "a test company");
Also this dropdown list creates:
<select name="customerselect" id="customer" onChange="showname()">
<option value="">Select customer</option>
<option value="118">John">Knight"></option><option value="119">Bill">Giles"></option><option value="122">Robert">Grain"></option> </select>
</p>
Maybe I should move the code to the bottom of the HTML for the JavaScript array although I wasn't sure if this wouldn't be initialised when required because it has ran the HTML first. I'm a little unsure if the order of things were correct.
The error I receive happens as soon as I change the drop downlist and it shows the following:
document.customerform.post_code.value = customer['customerselect'][post_code];
}
X 'post_code' is undefined
I think somewhere I am getting my document.value wrong when showing my array ?
Rather don't hope that a constant will work here.
Instead try the below as a replacement:
// build javascript array
while($row=mysqli_fetch_array($result1)){ ?>
var customer["<?=$row['customer_id']?>"] = [];
customer["<?=$row['customer_id'];?>"]['customer_id'] = "<?=$row['customer_id'];?>";
customer["<?=$row['customer_id'];?>"]['post_code'] = "<?=$row['post_code'];?>";
customer["<?=$row['customer_id'];?>"]['company_name'] = "<?=$row['company_name'];?>";
<? }
Thanks smftre for that. In the end I have opted for the jquery and ajax. and I think it has worked out betted for it originally I was trying to make the code as efficient as possible on bandwidth because the system is to be used but ajax seems to be the standard for a reason and works very well.

Creating a form entry calculator with jQuery

I am trying to build a calculator using form entries as the figures to be calculated and returned to corresponding form fields in another field set. I am fairly new to jQuery and I am following the advice of a book but I must be honest, I do need to rush this a bit and I'm having some problems.
Here is the jfiddle if you need to visualise it: http://jsfiddle.net/u3xx4ubv/14/
EDIT: Not sure on the appropriate form action for this, which may be causing some problems.
HTML:
<form action="" method="get" id="ATSCalc">
<fieldset>
<legend>Return on Investment Calculator</legend>
<label for="aptsBooked" class="label">Avg. Appointments Booked</label>
<input name="aptsBooked" type="text" id="aptsBooked">
<br />
<label for="aptsAttended" class="label">Avg. Appointments Attended</label>
<input name="aptsAttended" type="text" id="aptsAttended">
<br />
<label for="reqMeetings" class="label">Meetings per deal</label>
<input name="reqMeetings" type="text" id="reqMeetings">
<br />
<label for="orderVal" class="label">Avg. order value</label>
<input name="reqMeetings" type="text" id="reqMeetings">
<br />
<input type="submit" value="Submit" />
</fieldset>
<br />
<fieldset>
<legend>Results</legend>
<label for="convRate" class="label">Appointment conversion rate</label>
<input name="convRate" type="text" id="convRate">
<br />
<label for="meetingsPerDeal" class="label">No. of meetings per deal</label>
<input name="meetingsPerDeal" type="text" id="meetingsPerDeal">
<br />
<label for="meetingVal" class="label">Value of each meeting</label>
<input name="meetingVal" type="text" id="meetingVal">
<br />
</fieldset>
</form>
JavaScript:
$(document).ready(function(){
$('#ATSCalc').submit(function(){
var aptsBooked = $('#aptsBooked').val();
var aptsAttended = $('#aptsAttended').val();
var reqMeetings = $('#reqMeetings').val();
var orderVal = $('#orderVal').val();
//Collects values of form input
var aptsConvRate = aptsAttended / aptsBooked * 100;
$('#convRate').val(aptsCovRate); //Outputs meeting conversion rate to form field.
var meetingsPerDeal = aptsBooked / reqMeetings;
$('#meetingsPerDeal').val(meetingsPerDeal); //Outputs meeting per deal value to form field.
var meetingVal = orderVal / meetingsPerDeal;
$('#meetingVal').val(meetingVal); //Outputs value of each meeting to form field.
//Variables for calculation of Return on Investment figures
}}; // end submit()
}}; // end ready ()
I am trying to run the second group of variables and return the outputs in the fields seen in the second fieldset. I imagine it is just syntax errors or misplaced code but I am really struggling to fix it. Any help would be much appreciated.
Fiddle example
You missed
}}; instead of }); as your closing brackets
variable name aptsCovRate instead of aptsConvRate ( missing n )
$(document).ready(function () {
$('#ATSCalc').submit(function (e) {
e.preventDefault();
var aptsBooked = parseInt($('#aptsBooked').val(), 10);
var aptsAttended = parseInt($('#aptsAttended').val(), 10);
var reqMeetings = parseInt($('#reqMeetings').val(), 10);
var orderVal = parseFloat($('#orderVal').val());
//Collects values of form input
var aptsConvRate = aptsAttended / aptsBooked * 100;
$('#convRate').val(aptsConvRate); //Outputs meeting conversion rate to form field.
/* ^^^^ Conv !! not Cov */
var meetingsPerDeal = aptsBooked / reqMeetings;
$('#meetingsPerDeal').val(meetingsPerDeal); //Outputs meeting per deal value to form field.
var meetingVal = orderVal / meetingsPerDeal;
$('#meetingVal').val(meetingVal); //Outputs value of each meeting to form field.
//Variables for calculation of Return on Investment figures
}); // end submit()
}); // end ready ()
Also, it would be good to use parseInt() (value to integer Docs) with radix parameter and parseFloat() (value to floating-point number Docs) methods while getting your Number values from your inputs.
To round your results take a look at the toFixed() method.
There are a few things wrong with your javascript/HTML, and a few things you missed.
$('#convRate').val(aptsCovRate); should be $('#convRate').val(aptsCo**n**vRate);
The end submit and end ready should be }); not }};
You do not have a HTML input with orderVal as an ID. It needs to be changed.
Finally, what you missed - your form will submit and refresh and you'll lose the calculated values. You can fix this by using e.stopPropagation(); and e.preventDefault();
Updated fiddle should be working for you: http://jsfiddle.net/u3xx4ubv/17/

Passing the value of a button into a text field

I'm having some trouble with getting Javascript to pass a value (which is stored in local storage) into a textfield. Ideally, I'd like for someone to be able to click the 'apply here' button on one page, have the job number stored in local storage and then have it auto-populate the job number field on my application page with the job number.
This is what I've got so far, I have a feeling that I haven't assigned things correctly.
html (on submit page)
<p>
<form id="applyjob1" action="enquire.html" method="get">
<input type="submit" id="job1" value="Apply for Job" />
</form>
</p>
html (field I'm trying to put data into)
Job Reference Number <input required="required" id="jobNo" name="jobno" type="text" /> </br />
Javascript
window.onload = function init() {
var jobID = document.getElementById("job"); /*button name */
jobID.onsubmit = passJob; /*executes passJob function */
}
function passJob(){
var jobSubmit = localstorage.jobID("1984"); /*assigns localstorage*/
if (jobSubmit != undefined){
document.getElementById("jobNo").value = localstorage.jobID;
}
I think this code would work for your fuction.
function passJob(){
localStorage.setItem("jobID", "1984");
if (localStorage.jobID != undefined) {
document.getElementById("jobNo").value = localStorage.jobID;
}
}
You are assigning the jobSubmit wrongly. To set item, use localStorage.setItem('key', value). Note the casing as it matters.
So basically you should do
var jobSubmit = localStorage.setItem(,"jobID", "1984"); // assigns jobSubmit
And I don't see any element with id="job"

Categories