Javascript function with substrings - javascript

I attend a Javascript course and I have some exercises as homework. In one of them I have to create a Javascript function with the following role: when I press the button, the function should take the data from the first field of text and put it in the next 3 input fields (day, month and year).
I wrote the function, but it doesn't work. Can you tell me why? Thank you.
<!DOCTYPE html>
<html>
<head></head>
<body>
<input type="text" value="20/12/2015" />
<button onclick="calendar()">Push the button</button><br/>
<input type="text" placeholder="day" /><br />
<input type="text" placeholder="month" /><br />
<input type="text" placeholder="year" />
<script>
function calendar() {
var x = "20/12/2015";
var day = x.substring(0, 2);
var month = x.substring(3, 5);
var year = x.substring(6);
document.getElementsByTagName("input")[1].innerHTML = day;
document.getElementsByTagName("input")[2].innerHTML = month;
document.getElementsByTagName("input")[3].innerHTML = year;
}
</script>
</body>
</html>

You need to use the value property to set/get the value of an <input> element.
function calendar() {
var x = "20/12/2015";
day = x.substring(0, 2);
month = x.substring(3, 5);
year = x.substring(6),
inputs = document.getElementsByTagName("input");
inputs[1].value = day;
inputs[2].value = month;
inputs[3].value = year;
}
<input type="text" value="20/12/2015" />
<button onclick="calendar()">Push the button</button><br/>
<input type="text" placeholder="day" /><br />
<input type="text" placeholder="month" /><br />
<input type="text" placeholder="year" />

To set an input element's value, you have to assign to its value. This is also true for textarea elements.
Assign to innerHTML when dealing with pretty much any other kind of element, but not for inputs.
<!DOCTYPE html>
<html>
<head></head>
<body>
<input type="text" value="20/12/2015" />
<button onclick="calendar()">Push the button</button><br/>
<input type="text" placeholder="day" /><br />
<input type="text" placeholder="month" /><br />
<input type="text" placeholder="year" />
<script>
function calendar() {
var x = "20/12/2015";
var day = x.substring(0, 2);
var month = x.substring(3, 5);
var year = x.substring(6);
document.getElementsByTagName("input")[1].value = day;
document.getElementsByTagName("input")[2].value = month;
document.getElementsByTagName("input")[3].value = year;
}
</script>
</body>
</html>

Related

Uncaught TypeError: (sales_total + sales_vat).toFixed is not a function"

Every time I input a quantity it will always give me an error: (sales_total + sales_vat).toFixed is not a function. Can you please check my code? Here's my full code: https://jsfiddle.net/yv6zks1g/1/
Thanks!
$('#sales_qty').keyup(function(){
var qty = parseFloat($('#sales_qty').val()) || 0;
var sub_total = parseFloat($('#sales_sub_total').val()) || 0;
var vat = 0.12;
var sales_total = $('#sales_total').val((qty * sub_total).toFixed(2)).val();
var sales_vat = $('#sales_vat').val((sales_total * vat).toFixed(2));
$('#sales_amount_due').val((sales_total + sales_vat).toFixed(2));
});
The issue is because sales_total is a string, as returned from val(), and sales_vat is a jQuery object. Presumably the latter is missing the call to val(), but would then have the same issue as the preceding variable.
To fix this, add the val() call on #sales_vat to set the variable to the string, then convert them to Number types before making the #sales_amount_due calculation. Try this:
$('#sales_qty').keyup(function() {
var qty = parseFloat($('#sales_qty').val()) || 0;
var sub_total = parseFloat($('#sales_sub_total').val()) || 0;
var vat = 0.12;
var sales_total = $('#sales_total').val((qty * sub_total).toFixed(2)).val();
var sales_vat = $('#sales_vat').val((sales_total * vat).toFixed(2)).val();
$('#sales_amount_due').val((+sales_total + +sales_vat).toFixed(2));
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
Qty: <input type="text" id="sales_qty" /> <br />
Sub total: <input type="text" id="sales_sub_total" value="50" /> <br /><br />
Total: <input type="text" id="sales_total" /> <br />
VAT: <input type="text" id="sales_vat" /> <br /><br />
Due: <input type="text" id="sales_amount_due" value="1.2" /> <br /><br />
Better still would be to perform the calculations and store them in variables instead of the DOM elements. That way you're not wasting time by calculating a value as a number, storing it as a string, retrieving it as a string then converting it back to a number again. Try this:
$('#sales_qty').keyup(function() {
var qty = parseFloat($('#sales_qty').val()) || 0;
var sub_total = parseFloat($('#sales_sub_total').val()) || 0;
var vat = 0.12;
var sales_total = qty * sub_total;
var sales_vat = sales_total * vat;
var sales_due = sales_total + sales_vat;
$('#sales_total').val(sales_total.toFixed(2))
$('#sales_vat').val(sales_vat.toFixed(2));
$('#sales_amount_due').val(sales_due.toFixed(2));
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
Qty: <input type="text" id="sales_qty" /> <br />
Sub total: <input type="text" id="sales_sub_total" value="50" /> <br /><br />
Total: <input type="text" id="sales_total" /> <br />
VAT: <input type="text" id="sales_vat" /> <br /><br />
Due: <input type="text" id="sales_amount_due" value="1.2" /> <br /><br />

html form to javascript and back to html

Please let me know why this doesn't work and how I can achieve this as simple as possible. my professor wants the simplicity to reflect 15 minutes or work. I just don't grasp it though. Thanks in advance!
<script language="JavaScript">
var obj = {
name = "",
address = "",
ccNumber = "",
}
function printObj() {
document.getElementById("display").innerHTML = obj.name + " " + obj.address + " " + obj.ccNumber;
}
function storeInput(user_input1, user_input2, user_input3) {
name = document.getElementById("myObject").form.user_input1;
address = document.getElementById("myObject").form.user_input2;
ccNumber = document.getElementById("myObject").form.user_input3;
}
</script>
<form>
<label><b>Enter full name</b></label>
<input type="text" name="message" id="user_input1">
</form>
<form>
<label><b>Enter billing address</b></label>
<input type="text" name="message" id="user_input2">
</form>
<form>
<label><b>Enter CC number</b></label>
<input type="text" name="message" id="user_input3">
</form>
<input type="submit" onclick="obj.storeInput(user_input1, user_input2, user_input3);obj.showInput()"><br />
<p id='display'></p>
Ok! You need your storeInput() to reference the declared object. Currently with your code as it is storeInput() is an independent function but for you event handler (onclick) to work. You need to redefine the storeInput() as
obj.storeInput() = function(user_input1, user_input2, user_input3) {.....};
This will get the job done. It will not store the values, but will display them.
<!DOCTYPE html>
<html>
<body>
<form>
<label><b>Enter full name</b></label>
<input type="text" name="message" id="user_input1">
<label><b>Enter billing address</b></label>
<input type="text" name="message" id="user_input2">
<label><b>Enter CC number</b></label>
<input type="text" name="message" id="user_input3">
</form>
<input type="submit" onclick="aFunction();"><br />
<p id='display'></p>
<script>
function aFunction(){
var x = document.querySelector('#user_input1').value; // gets value of user_input1 field
var y = document.querySelector('#user_input2').value; // gets value of user_input2 field
var z = document.querySelector('#user_input3').value; // gets value of user_input3 field
document.querySelector('#display').innerHTML = x + ' ' + y + ' ' + z; // puts the values in <p> with id of 'display'
}
</script>
</body>
</html>
Hope this helps you understand.

Superscript Calculation Javascript Variables

I'm exercising in calculations with variables using javascript and i can't figure out how to use superscripts in variables. With some help Javascript calculations holding variables i learned how to do calculations in general but my new question is how to use superscripts?
<form name="Calcultor" Method="Get" id='form1'>First Number:
<input type="text" name="first" size="35" id="first">+ Second Number:
<input type="text" name="second" size="35" id="second">
<br>Answer:
<input type="text" name="ans" size="35" id="ans" />
<input type="text" name="ans2" size="35" id="ans2" />
<button type="button" onclick="Calculate();">Calculate</button>
</form>
<script>
function Calculate() {
var first = document.getElementById('first').value;
var second = document.getElementById('second').value;
var ans = document.getElementById('ans').value;
var ans2 = document.getElementById('ans2').value;
document.getElementById('ans').value = parseInt(first) + parseInt(second);
document.getElementById('ans2').value = 1.112 - 0.00043499 * parseInt(document.getElementById('ans').value)/*insert ans into a parenthensis*/ + 0.00000055 * parseInt(document.getElementById('ans').value)/*insert ans into a parenthensis and ^2 outside the parenthesis*/ - 0.00028826;
}
</script>
Thanks in advance
There is a function in javascript Math.pow();
Math.pow(2,4) gives you 2^4 = 16.
Math.pow(2,4);
>16
Math.pow(2,4.1);
>17.148375400580687
<form name="Calcultor" Method="Get" id='form1'>First Number:
<input type="text" name="first" size="35" id="first">+ Second Number:
<input type="text" name="second" size="35" id="second">
<br>Answer:
<input type="text" name="ans" size="35" id="ans" />
<input type="text" name="ans2" size="35" id="ans2" />
<button type="button" onclick="Calculate();">Calculate</button>
</form>
<script>
function Calculate() {
var first = document.getElementById('first').value;
var second = document.getElementById('second').value;
var ans = document.getElementById('ans').value;
var ans2 = document.getElementById('ans2').value;
document.getElementById('ans').value = parseInt(first) + parseInt(second);
document.getElementById('ans2').value = 1.112 - 0.00043499 * parseInt(document.getElementById('ans').value) + 0.00000055 * Math.pow(parseInt(document.getElementById('ans').value), 2) - 0.00028826;
}
</script>
Updated Snippet according to answers works now!

I am having trouble with HTML Javascript inclusion

I'm trying to use the information that I obtain through a form via a submit button, do a little processing, and print it out onto the web page, preventing it from being submitted to a web server by including (return false).
Here is the code to the page:
<html>
<head>
<title>SmithSellsStuff</title>
</head>
<body>
I'm too cheap to buy something nice
<script>
var myData = {
price: "4.25",
taxRate: "0.07",
shipRate: "0.02"
};
myData.calculateTotal = function() {
myData.name = document.getElementById("name");
myData.date = document.getElementById("date");
myData.numItems = document.getElementById("number of items");
var itemTotal = myData.numItems * myData.price;
var taxTotal = (myData.numItems * myData.price) * myData.taxRate;
var shipTotal = (myData.numItems * myData.price) * myData.shipRate;
document.writeln(itemTotal);
document.writeln(taxTotal);
document.writeln(shipTotal);
};
</script>
<form>
</p>
<label>Name: <input type="text" name="name" id="name" tabindex="1"/> </label>
</p>
<label>Delivery Date: <input type="date" name="date" id="date" tabindex="2"/></label>
</p>
<label>Number of items: <input type="number" name="number of items" id="number of items" tabindex="3"/></label>
</p>
<input type="submit" onclick="calculateTotal(); return false;"/>
</form>
</body>
</html>
On the first page, I have a simple form with a field for name, date, number of items total, and a submit button. One error I'm getting is in the onclick tag. It says '_kof_1' is defined but never used. I don't think it is allowing my calculateTotal function to call.
It's because the function was not declared in the global scope, but rather as a property of myData.
myData.calculateTotal = function() {
To solve this, simply change the call to:
<input type="submit" onclick="myData.calculateTotal(); return false;"/>
Furthermore, since you want to get the name, date, and number of items from the text fields, you have to get the .value property to get the contents of the input fields, like so:
myData.name = document.getElementById("name").value;
myData.date = document.getElementById("date").value;
myData.numItems = parseInt(document.getElementById("number of items").value);
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
I'm too cheap to buy something nice
<script>
function calculateTotal()
{
alert("hai");
var price="4.25";
var taxRate="0.07";
var shipRate="0.02";
var name = document.getElementById("name");
var date = document.getElementById("date");
var numItems = document.getElementById("number_of_items").value;
alert(numItems);
var itemTotal = numItems * price;
var taxTotal = (numItems * price) * taxRate;
var shipTotal = (numItems * price) * shipRate;
document.writeln("Total Items:"+itemTotal+"\tTax :"+taxTotal+"\tshipTotal:"+shipTotal);
}
</script>
<form>
<p>
<label>Name: <input type="text" name="name" id="name" tabindex="1"/> </label>
</p>
<label>Delivery Date: <input type="date" name="date" id="date" tabindex="2"/></label>
<p>
<label>Number of items: <input type="number" name="number_of_items" id="number_of_items" tabindex="10"/></label>
</p>
<input type="submit" onclick="calculateTotal()"/>
</form>
</body>
</html>
alert is just for to know method is calling or not, Hope this will help you

Phonegap - events such as focus(),blur() not called in JavaScript

I have just started using Phonegap, I wanted to clear the textbox content when the user clicks on the textbox.
HTML:
<input type="text" class="clear" id="dateVal" name="date" value="date" onblur="clear();"/>/
JavaScript
function clear() {
document.getElementsByTagName('input').value = '';
}
But the clear function is not getting called. Also, just tried putting alert in clear()
function(did not help). Everything else working okay. Any help would be appreciated.
Full HTML Code:
<!DOCTYPE html> <html> <head>
<title>Age Calculator</title>
<script type="text/javascript" charset="utf-8" src="cordova-1.8.1.js"></script>
<script type="text/javascript" charset="utf-8">
document.addEventListener("deviceready",onDeviceReady,false);
function onDeviceReady() {
alert('welcome');
}
function calAge() {
var x = confirm('Click here to calculate the age');
if(x == true) {
document.getElementById('ageId').style.display = block';
} else {
navigator.app.exitApp(); }
}
function submitValues() {
var todaysDate = new Date();
var y = todaysDate.getFullYear();
var m = todaysDate.getMonth() + 1;
var d = todaysDate.getDate() + 1;
var myYear = document.getElementById('yearVal').value;
var myMonth = document.getElementById('monthVal').value;
var myDate = document.getElementById('dateVal').value;
var myYear = (y-myYear);
var myMonth = (m-myMonth);
var myDate = (d-myDate);
document.getElementById('ageId').style.display = 'none';
document.getElementById('result').innerHTML = 'You are '+myYear+'years '+myMonth+' months and '+myDate + ' days old :-)';
} function clear() { document.getElementsByTagName('input').value = ''; }
</script> </head> <body>
<button onclick="calAge();">Age Calculator</button> <br>
<div id="ageId" style="display:none;">
<b>Please Enter your Date Of Birth in (dd/mm/yyyy) format:</b>
<input type="text" class="clear" id="dateVal" name="date" value="date" onblur="clear();"/>/
<input type="text" class="clear" id="monthVal" name="month" value="month" />/
<input type="text" class="clear" id="yearVal" name="year" value="year" />
<input type="button" value="submit" onclick = "submitValues();" />
</div>
<div id="result">
</div> </body> </html>
In HTML5 there is a placeholder attribute.
Ex:
<input type="text" placeholder="Enter Date" id="dateVal" name="date" />
We could use this to get what I desired.
Thanks, might be helpful to somebody.

Categories

Resources