Javascript function not returning a value - javascript

I have a javascript function that check for a value from a text box and the if the text box is not blank it outputs a statement. The text box take a numeric value, i want to include that numeric value that is output to html.
here is the html
<br><label id="cancelphoneLabel">1-800-555-1111</label>
<br><label id="mdamountLabel">Monthly Donation:
<td>
<input type="text" id="mdamountBox" style="width:50px;" name="md_amt" value="" placeholder="Monthly" onkeyup="monthlycheck()" autocomplete="off">
<br><label id="mnthlychkdiscoLabel"> </label>
and the Javascript
function monthlycheck() {
var mnthchk = document.getElementById("mdamountBox").innerHTML; <---i want to pass the value of this box
var cancelPhone = document.getElementById("cancelphoneLabel").innerHTML;
if (mnthchk.value != "") {
var newHTML = "<span style='color:#24D330'> Your Monthly pledge in the amount of $<label id='dollarLabel'> </label> is valid and will be deducted this time every month<br> untill you notify us of its cancellation by calling <label id='cancelphonelistLabel'> </label> </span>";
document.getElementById("mnthlychkdiscoLabel").innerHTML = newHTML;
document.getElementById("cancelphonelistLabel").innerHTML = cancelPhone;
document.getElementById("dollarLabel").innerHTML = mnthchk; <----passed to here
i cant get the value passed, it only shows blank, i can hardcode a value and will output fine, which is how the jsfiddle is currently http://jsfiddle.net/rn5HH/4/
thanks in advance

Input elements don't have child nodes, therefore innerHTML is blank. If you want to read their value, use the value property.

Your line:
var mnthchk = document.getElementById("mdamountBox").innerHTML;
Should be:
var mnthchk = document.getElementById("mdamountBox");
Then you can get the value of the text input like this:
var newmnthchk = mnthchk.value;
Working JS Fiddle here: http://jsfiddle.net/rn5HH/10/

use document.getElementById("mdamountBox").value

The problem here is you are trying to get the innerHtml, where you want the value. From your fiddle, just change this line:
var mnthchk = document.getElementById("mdamountBox").innerHTML;
...to this:
var mnthchk = document.getElementById("mdamountBox").value;

check below code :
HTML Code
<br><label id="cancelphoneLabel">1-800-555-1111</label>
<br><label id="mdamountLabel">Monthly Donation:
<td>
<input type="text" id="mdamountBox" style="width:50px;" name="md_amt" value="" placeholder="Monthly" onkeyup="monthlycheck()" autocomplete="off">
<br><label id="mnthlychkdiscoLabel"> </label>
Javascript Code
function monthlycheck() {
var mnthchk = document.getElementById("mdamountBox").value;
var cancelPhone = document.getElementById("cancelphoneLabel").innerHTML;
if (mnthchk.value != "") {
var newmnthchk = '5';
newmnthchk = mnthchk;
var newHTML = "<span style='color:#24D330'> Your Monthly pledge in the amount of $<label id='dollarLabel'> </label> is valid and will be deducted this time every month<br> untill you notify us of its cancellation by calling <label id='cancelphonelistLabel'> </label> </span>";
document.getElementById("mnthlychkdiscoLabel").innerHTML = newHTML;
document.getElementById("cancelphonelistLabel").innerHTML = cancelPhone;
document.getElementById("dollarLabel").innerHTML = newmnthchk;
}
}
This is working code perfectly checked on Fiddle
,you need to get DOM value using
var mnthchk = document.getElementById("mdamountBox").value;

Related

javascript how to calculate values in dynamically added fields with multiple rows

I had one row with three fields: received, issue, balance
<input type="text" name="rcv" class="rcv"/>
<input type="text" name="issue" class="issue"/>
<input type="text" name="blnc" class="balance"/>
I calculated the balance for each row easily, but how do I calculate more than one row?
Each row has receive, issue and balance fields.
How do I calculate each row's balance field?
I tried like this for multiple row but it's not working:
$('.t_rtn, .t_rcv').each(function(){
$(this).on('blur',function(){
var totalRcv = $('.t_rcv').val();
var totalRtn = $('.t_rtn').val();
// console.log( $('t_rtn').next('.consume').val() );
$('t_rtn').next('.consume').val(totalRcv-totalRtn);
});
you need to parse The value of textbox as it returns string not int
$('.t_rtn, .t_rcv').each(function(){
$(this).on('blur',function(){
var totalRcv = parseInt($('.t_rcv').val()) || 0;
var totalRtn = parseInt($('.t_rtn').val()) || 0;
// console.log( $('t_rtn').next('.consume').val() );
$('t_rtn').next('.consume').val(totalRcv-totalRtn);
});
If your code is being run on document.ready it will only be applied to elements which exist at that point.
You'd be better with :
$(document).on('blur','.t_rtn, .t_rcv',function(){
var val = $(this).val();
...
});
try this..
$(document).on('blur','.receive, .return', function()
{
var $row = $(this).closest(".row");
var totalRcv = parseInt($row.find('.receive').val()) || 0;
var totalRtn = parseInt($row.find('.return').val()) || 0;
$row.find('.balance').val(totalRcv - totalRtn);
});
In addition to parsing the string values into integers you also need to use the correct selectors for those input elements. t_rtn is not the right class name, for example. And if doing this in rows you will want to grab the correct element from the current row (you already did this correctly for the consume field)
Fixed html (Example.. I chose to use div with class name = row):
<div class='row'>
<input type="text" name="rcv" class="receive"/>
<input type="text" name="issue" class="return"/>
<input type="text" name="blnc" class="balance"/>
</div>
<div class='row'>
<input type="text" name="rcv" class="receive"/>
<input type="text" name="issue" class="return"/>
<input type="text" name="blnc" class="balance"/>
</div>
<div class='row'>
<input type="text" name="rcv" class="receive"/>
<input type="text" name="issue" class="return"/>
<input type="text" name="blnc" class="balance"/>
</div>
Fixed code:
$(document).on('blur','.receive, .return', function()
{
var $row = $(this).closest(".row");
var totalRcv = parseInt($row.find('.receive').val()) || 0;
var totalRtn = parseInt($row.find('.return').val()) || 0;
$row.find('.balance').val(totalRcv - totalRtn);
});
I took the liberty of fixing some inconsistencies with the class names used. I tried to match them up to the variables for totalRcv and totalRtn so that now the balance shows as receipt minus return. If the user enters non-numeric data, it defaults the value to 0 before calculating.
Example fiddle here: http://jsfiddle.net/cp81g4nf/1/
I think problem is because you are subtracting 2 Strings. .val returns an String.
Convert them in number before subtracting like bellow
$('t_rtn').next('.consume').val((+totalRcv)-(+totalRtn));

Javascript: Cant fetch value of input number box

Hello almighty internetz!
Im totally new on javascript, and i cant get the script to fetch numbers from input boxes, plus the sums together and write it out.
Have been sitting on Google for an hour now, so im asking you guys/girls for help!
http://jsfiddle.net/heWM2/5/
<form action="" id="brod">
<p>Pris per kartong
<input name="Prisperkartong" type="number" id="priskart" name="pris">
</p>
<p>Antal kartonger i leverans
<input name="Kartongilev" type="number" id="kartilev">
</p>
<input type="button" onClick="calculateTotal()" value="Räkna">
<div id="print"></div>
</form>
And the Javascript:
function getPrisperkartong() {
var Prisperkartong = parseInt(document.brod.priskart.value, 10);
if (isNaN(Prisperkartong)) return;
document.bord.priskart.value = Prisperkartong;
}
function getKartongilev() {
var Kartongilev = parseInt(document.brod.kartilev.value, 10);
if (isNaN(Kartongilev)) return;
document.bord.kartilev.value = Kartongilev;
}
function calculateTotal() {
var total = getPrisperkartong() + getKartongilev();
var divobj = document.getElementById('print');
divobj.style.display = 'block';
divobj.innerHTML = "Pris $" + total;
}
If you are accessing the input boxes through the form, you need to use the name field to identify the form as well as the input boxes. Your get functions should also return the value, not assign it back to the original input box. See this updated fiddle for a fixed, working example.
http://jsfiddle.net/heWM2/6/

Using join() to create a HTML id?

I have 6 Hidden fields which are to hold a latitude and longitude for 3 different postcodes:
<input type="hidden" id="geo_lat1" name="geo_lat1">
<input type="hidden" id="geo_lon1" name="geo_lon1">
<input type="hidden" id="geo_lat2" name="geo_lat2">
<input type="hidden" id="geo_lon2" name="geo_lon2">
<input type="hidden" id="geo_lat3" name="geo_lat3">
<input type="hidden" id="geo_lon3" name="geo_lon3">
I also have the three input fields for the postcodes:
<input type="text" name="search_postcode1" id="search_postcode1">
<input type="text" name="search_postcode2" id="search_postcode2">
<input type="text" name="search_postcode3" id="search_postcode3">
The geocoding function I have works fine, but only for the first set of lat/longs. If I want to produce the lat/longs for the other two postcodes, I would have to copy and paste the geocoding function for each postcode, just changing the number at the end of the input name in the following line:
var sAddress1 =document.getElementById("search_postcode1").value ;
Instead of copying/pasting I want to use the same code but in a loop, which means changing the reference from search_postcode1 to search_postcode2 and search_postcode3
I know I can use join() to join data in an array and assign it to another variable like so:
var a = new Array("search_postcode","1");
var pcname = a.join(""); // pcname would be assigned "search_postcode1"
My question is how do I assign it so that it would appear in the line of code above rather than a value in a variable?
EDIT
I also need to assign it to the hidden fields using:
geo_lat1.value = loc[0];
geo_lon1.value = loc[1];
How do I change the '1's in this to a '2' and a '3' in a loop? It must be a different way to the getElementById("search_postcode" + "1") way?
You could do something like this:
for (var i = 1; i <= 3; i++) {
var address = document.getElementById('search_postcode' + i);
// Do something with address. Each time through the loop, it will
// reference the "i" search_postcode input, 1-3. Maybe something like:
var loc = geoCodePostCode(address.value);
document.getElementById('geo_lat' + i).value = loc[0];
document.getElementById('geo_long' + i).value = loc[1];
}

Grabbing User Input

First name: <input type="text" name="firstname"></input>
<input type="submit" value="Submit" />
Let's say I have the simple form above. How would I grab what the user inputted in the First Name field in JS. I tried:
document.getElementsByTagName("input")[1].onclick = function() {
inputted = document.getElementsByTagName("input")[0].innerHTML;
}
But that doesn't work. How would I do this?
Use value for text inputs:
inputted = document.getElementsByTagName("input")[0].value;
Also make sure to add var keyword to your variables so that you don't create a global variable:
var inputted = document.getElementsByTagName("input")[0].value;
You should also not put closing </input> tag since it is self-closing tag:
<input type="text" name="firstname" />
By the way you can also get elements value using below syntax:
formName.elementName.value;
Or
document.forms['formName'].elementName.value;
In your case it would be:
var inputted = formName.firstname.value;
Or
var inputted = document.forms['formName'].firstname.value;
Replace formName with whatever name is of your <form> element.
Lastly you can also get element's value if you apply id to it:
<input type="text" name="firstname" id="firstname" />
and then use getElementById:
var inputted = document.getElementById('firstname');
var inputs=document.getElementsByTagName("input"),
i=inputs.length;
//
while(i--){
inputs[i].onclick=myClickEventHandler;
};
//
function myClickEventHandler(evt){
var myVal;
switch (this.name) {
case 'firstname':
myVal = this.value;
break;
};
};
If you are using a form, you could try something like this instead :
var input = document.forms["formName"]["fieldName"].value;
Else, make use of the .value attribute :
var input = document.getElementsByTagName("input")[0].value;

Fill data in input boxes automatically

I have four input boxes. If the user fills the first box and clicks a button then it should autofill the remaining input boxes with the value user input in the first box. Can it be done using javascript? Or I should say prefill the textboxes with the last data entered by the user?
On button click, call this function
function fillValuesInTextBoxes()
{
var text = document.getElementById("firsttextbox").value;
document.getElementById("secondtextbox").value = text;
document.getElementById("thirdtextbox").value = text;
document.getElementById("fourthtextbox").value = text;
}
Yes, it's possible. For example:
<form id="sampleForm">
<input type="text" id="fromInput" />
<input type="text" class="autofiller"/>
<input type="text" class="autofiller"/>
<input type="text" class="autofiller"/>
<input type="button"value="Fill" id="filler" >
<input type="button"value="Fill without jQuery" id="filler2" onClick="fillValuesNoJQuery()">
</form>
with the javascript
function fillValues() {
var value = $("#fromInput").val();
var fields= $(".autofiller");
fields.each(function (i) {
$(this).val(value);
});
}
$("#filler").click(fillValues);
assuming you have jQuery aviable.
You can see it working here: http://jsfiddle.net/ramsesoriginal/yYRkM/
Although I would like to note that you shouldn't include jQuery just for this functionality... if you already have it, it's great, but else just go with a:
fillValuesNoJQuery = function () {
var value = document.getElementById("fromInput").value;
var oForm = document.getElementById("sampleForm");
var i = 0;
while (el = oForm.elements[i++]) if (el.className == 'autofiller') el.value= value ;
}
You can see that in action too: http://jsfiddle.net/ramsesoriginal/yYRkM/
or if input:checkbox
document.getElementById("checkbox-identifier").checked=true; //or ="checked"

Categories

Resources