Built an array but can't figure to the linking code - javascript

Okay so I've built this array but I would like it so when they type their post code into the "post code" text box that it reads the array and if their post code is within the array it adds 2 to the amount/ "total" text box.... how would I go about this as I've been stuck for about 2 weeks now....? Any help is appreciated! thank you!
<!DOCTYPE html>
<html>
<body>
<b>Post Code</b><input type="text" myfunction()">
<p>
<b>Total: £ </b><input name="amount" size=8 value="0">
</p>
<p id="demo"></p>
<script>
function myFunction() {
var postcode = ["ZE", "KW","IV","HS","AB","DD","PH","PA","FK","KY","G","BT","IM,"GY","JE","EH","ML","KA"];
var a = postcode.indexOf("CV","LE");
document.getElementById("value").innerHTML = a;
}
</script>
</body>
</html>

There are a few typos in the above code. I have assumed that first two letters of the pincode are mentioned in the array. Following is the code that I have come up with. Hope it helps..
<!DOCTYPE html>
<html>
<body>
<b>Post Code</b><input name="postcode" type="text" onblur="myFunction(this.value);">
<p>
<b>Total: £ </b><input id="amount" name="amount" size=8 value="0">
</p>
<p id="demo"></p>
<script>
function myFunction(pc) {
var postcode_arr = ["ZE", "KW","IV","HS","AB","DD","PH","PA","FK","KY","G","BT","IM","GY","JE","EH","ML","KA"];
var firsttwo = pc.substr(0,2);
firsttwo = firsttwo.toUpperCase();
//alert(firsttwo);
var a = postcode_arr.indexOf(firsttwo);
if(a!= -1) {
var amt = parseFloat(document.getElementById("amount").value);
amt +=2;
document.getElementById("amount").value = amt;
}
document.getElementById("demo").innerHTML = a;
}
</script>
</body>
</html>

Related

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

TextCounter & Trigger innerHTML in two separate input areas

I just started to learn Javascript. I have two questions regarding TextCounter & Trigger innerHTML.
My code below, how to separately trigger innerHTML for two inputs?
Why the alert info which is "over!!" still shows while deleting the number of words in the textarea?
Can someone please help? Much appreciated!
HTML
<html>
<head>
</head>
<body>
<form>
<textarea name="line01" rows="3" style="width:340px;"
onKeyUp="textCounter(this.form.01,this.form.countDisplay01,10);"
onKeyDown="textCounter(this.form.01,this.form.countDisplay01,10);">
</textarea>
<br>
<input readonly type="text" name="countDisplay01" width: 25px"
value="10">characters remaining
<p id="go1"></p>
</form>
<form>
<textarea name="line02" rows="3" style="width:340px;"
onKeyUp="textCounter(this.form.02,this.form.countDisplay02,8);"
onKeyDown="textCounter(this.form.02,this.form.countDisplay02,8);">
</textarea>
<br>
<input readonly type="text" name="countDisplay02" width: 25px"
value="8">characters remaining
<p id="go2"></p>
</form>
</body>
</html>
Javascript
<script>
function textCounter(textField, showCountField, maxAmount) {
if (textField.value.length <= maxAmount) {
showCountField.value = maxAmount - textField.value.length;
} else {
document.getElementById("go1").innerHTML = "<span
style='color:red'>Over!!</span>";
document.getElementById("go2").innerHTML = "<span
style='color:red'>Over!!</span>";
textField.value = textField.value.substring(0,maxAmount);
}
</script>
Try with the following code
HTML
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Text Counter</title>
</head>
<body>
<form>
<textarea name="01" rows="3" style="width:340px;"
onKeyUp="textCounter(this.form['01'],this.form.countDisplay01,10,1);"
onKeyDown="textCounter(this.form['01'],this.form.countDisplay01,10,1);">
</textarea>
<br>
<input readonly type="text" name="countDisplay01" style="width: 25px;" value="28"> characters remaining
<p id="go1"></p>
</form>
<form>
<textarea name="02" rows="3" style="width:340px;"
onKeyUp="textCounter(this.form['02'],this.form.countDisplay02,8,2);"
onKeyDown="textCounter(this.form['02'],this.form.countDisplay02,8,2);">
</textarea>
<br>
<input readonly type="text" name="countDisplay02" style="width: 25px" value="15">characters remaining
<p id="go2"></p>
</form>
</body>
</html>
SCRIPT
<script>
function textCounter(textField, showCountField, maxAmount,id) {
if (textField.value.length <= maxAmount) {
showCountField.value = maxAmount - textField.value.length;
document.getElementById('go'+id).innerHTML = '';
} else {
document.getElementById('go'+id).innerHTML = '<span style="color:red">Over!!</span>';
textField.value = textField.value.substring(0,maxAmount);
}
}
</script>
As you have used a name that starts with number, it's not a valid variable. You should access it through dictionary lookup:
textCounter(this.form['01'],this.form.countDisplay01,10);
For the alert text, you should reset the innerHTML in the first if clause:
if (textField.value.length <= maxAmount) {
showCountField.value = maxAmount - textField.value.length;
document.getElementById("go1").innerHTML = "";
document.getElementById("go2").innerHTML = "";
} else {
document.getElementById("go1").innerHTML = "<span style='color:red'>Over!!</span>";
document.getElementById("go2").innerHTML = "<span style='color:red'>Over!!</span>";
textField.value = textField.value.substring(0,maxAmount);
}
This will remove the alert text, on the next keypress. If you want to remove the text immediately, you have two options:
Forget about showing an error.
Show the error for about a fraction of second and then remove it. Using something like a setTimeout. But you should remember, the window won't redraw before returning from your function. So, setting the alert text first, and then removing it at the end of your function, will be the same as doing option 1.

HTML onsubmit event is not calling the JavaScript function

I have two buttons in my form for calling two JavaScript functions. The first button works good in its onclick event calling the payroll() function successfully but the second button is of type submit and it never calls the send() function on form submission. I don't know why this issue occurs.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<!DOCTYPE html>
<html >
<head>
<title>hr page</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<script type="text/javascript"
src="/static/js/sijax/sijax.js"></script>
<script type="text/javascript">
{{ g.sijax.get_js()|safe }}</script>
<link rel="stylesheet" href="{{url_for('static', filename='styles/signupcss.css')}}">
<script type="text/javascript" >
function payroll() {
var basic=document.forms["salary"]["bsalary"].value;
var empid=document.forms["salary"]["empid"].value;
var ta,hra,da,pf,netsalary,grosssalary;
if (empid == ""||basic == "") {
alert("Employee ID and Salary details must be filled out");
return false;
}
if(isNaN(basic))
{alert("Salary must be in Numbers");
return false;
}
hra=basic*40/100;
da=basic*15/100;
pf=basic*12/100;
basic=parseInt(basic);
hra=parseInt(hra);
da=parseInt(da);
grosssalary=basic + hra + da;
ta=basic*6.2/100;
netsalary=grosssalary-ta;
document.getElementById("hra").innerHTML=hra;
document.getElementById("ta").innerHTML=ta;
document.getElementById("da").innerHTML=da;
document.getElementById("netsalary").innerHTML=netsalary;
document.getElementById("pf").innerHTML=pf;
document.getElementById("grosssalary").innerHTML=grosssalary;
window.alert("HI"+grosssalary);
return true;
}
function send()
{
var id = document.forms['salary']['empid'].value;
var basic = document.forms['salary']['bsalary'].value;
var hra = document.forms['salary']['hra'].value;
var da = document.forms['salary']['da'].value;
var ta = document.forms['salary']['ta'].value;
var pf = document.forms['salary']['pf'].value;
var gross_sal = document.forms['salary']['grosssalary'].value;
window.alert("HI"+gross_sal);
var net_sal = document.forms['salary']['netsalary'].value;
Sijax.request('send',[id, basic, hra, ta, da, pf, gross_sal, net_sal]);
}
</script>
</head>
<body style="font-family:Lato">
<div style="padding-left:5%;padding-top:0.2%;height:1%;width:100%;background-color:#11557c">
<h2>Welcome to HR Department</h2><br>
</div>
<div style="margin-left:15%" >
<h2>Name</h2>
<form id="salary" name="salary" style="margin-top: 2%" method="post" onsubmit="return send()" >
<label id = "empid">Employee ID</label><br>
<input type = "text" name = "empid" placeholder = "Employee ID" /><br><br>
<label id = "bsalary">Basic Salary</label><br>
<input type = "text" name = "bsalary" placeholder = "Basic salary" /><br><br>
<input type="button" value="Calculate" onclick="return payroll()"><br><br>
<label for ="hra">House Rent Allowance(HRA)</label>
<p id="hra" name="hra"></p><br>
<label for ="ta">Travel Allowance(TA)</label>
<p id="ta" name="ta"></p><br>
<label for ="da"> Dearness Allowance(DA)</label>
<p id="da" name="da"></p><br>
<label for ="netsalary">Net Salary</label>
<p id="netsalary" name="netsalary"></p><br>
<label for ="pf">Provident Fund(PF)</label>
<p id="pf" name ="pf"></p><br>
<label for ="grosssalary">Gross Salary</label>
<p id="grosssalary" name="grosssalary"></p><br><br>
<input type="submit" value="Upload Salary">
</form>
</div>
</body>
</html>
You can't act with <p> elements like as a form-elements. You may create a respective <input type="hidden"> elements and fill them in payroll(), or get values by .innerHtml on paragraphs.
P.S. You have actually a TypeError exception, calling undeclared form elements like document.forms['salary']['grosssalary'] and so on.
okay, quick fix, since you are using python flask library Sijax for ajax and therefore jQuery, you can alter your javascript send function like this:
function send(e){
e.preventDefault(); //it is as good as returning
//false from the function in all cases
var id = document.forms['salary']['empid'].value;
...
}
and change your onsubmit handler declaration like this:
<form id="salary" name="salary" style="margin-top: 2%" method="post"
onsubmit="return send(event)" >
please note that when you stop the event chain propagation, you will have to do a manual submission of the form.
So, you can modify your send function to do .preventDefault based on your custom criterias, otherwise, let the form submit
Your code actually works, if you're running this code as a snippet here in stack overflow, Form submission is actually blocked by default. Try running your code in codepen. I tried it and it's actually working.
http://codepen.io/jhonix22/pen/VPZagb
Check this out. It is nowhere close to a perfect solution but I think it helps. You can not access the paragraphs as if you would the form input elements. Im not entirely sure what Sijax thing is. I believe it is just a normal AJAX HTTP thing with some sort of CSRF security filters.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<!DOCTYPE html>
<html>
<head>
<title>hr page</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<script type="text/javascript"
src="/static/js/sijax/sijax.js"></script>
<script type="text/javascript">
{
{
g.sijax.get_js() | safe
}
}</script>
<link rel="stylesheet" href="{{url_for('static', filename='styles/signupcss.css')}}">
<script type="text/javascript">
function payroll() {
var basic = document.forms["salary"]["bsalary"].value;
var empid = document.forms["salary"]["empid"].value;
var ta, hra, da, pf, netsalary, grosssalary;
if (empid == "" || basic == "") {
alert("Employee ID and Salary details must be filled out");
return false;
}
if (isNaN(basic)) {
alert("Salary must be in Numbers");
return false;
}
hra = basic * 40 / 100;
da = basic * 15 / 100;
pf = basic * 12 / 100;
basic = parseInt(basic);
hra = parseInt(hra);
da = parseInt(da);
grosssalary = basic + hra + da;
ta = basic * 6.2 / 100;
netsalary = grosssalary - ta;
document.getElementById("hra").innerHTML = hra;
document.getElementById("ta").innerHTML = ta;
document.getElementById("da").innerHTML = da;
document.getElementById("netsalary").innerHTML = netsalary;
document.getElementById("pf").innerHTML = pf;
document.getElementById("grosssalary").innerHTML = grosssalary;
window.alert("HI" + grosssalary);
return true;
}
function send() {
var id = document.forms['salary']['empid'].value;
var basic = document.forms['salary']['bsalary'].value;
var hra = document.getElementById('hra').innerHTML;
var da = document.getElementById('da').innerHTML;
var ta = document.getElementById('ta').innerHTML;
var pf = document.getElementById('pf').innerHTML;
var gross_sal = document.getElementById('grosssalary').innerHTML;
window.alert("HI" + gross_sal);
var net_sal = document.getElementById('netsalary').innerHTML;
// I think you are missing something here.
Sijax.request('send', [id, basic, hra, ta, da, pf, gross_sal, net_sal]);
}
</script>
</head>
<body style="font-family:Lato">
<div style="padding-left:5%;padding-top:0.2%;height:1%;width:100%;background-color:#11557c">
<h2>Welcome to HR Department</h2><br>
</div>
<div style="margin-left:15%">
<h2>Name</h2>
<form id="salary" name="salary" style="margin-top: 2%" method="post" onsubmit="return false">
<label id="empid">Employee ID</label><br>
<input type="text" name="empid" placeholder="Employee ID"/><br><br>
<label id="bsalary">Basic Salary</label><br>
<input type="text" name="bsalary" placeholder="Basic salary"/><br><br>
<input type="button" value="Calculate" onclick="return payroll()"><br><br>
<label for="hra">House Rent Allowance(HRA)</label><br>
<p id="hra" readonly name="hra"></p>
<label for="ta">Travel Allowance(TA)</label><br>
<p id="ta" readonly name="ta"></p>
<label for="da"> Dearness Allowance(DA)</label><br>
<p id="da" readonly name="da"></p>
<label for="netsalary">Net Salary</label><br>
<p id="netsalary" readonly name="netsalary"></p>
<label for="pf">Provident Fund(PF)</label><br>
<p id="pf" readonly name="pf"></p>
<label for="grosssalary">Gross Salary</label><br>
<p id="grosssalary" readonly name="grosssalary"></p><br>
<input type="button" onclick="send()" value="Upload Salary">
</form>
</div>
</body>
</html>

Input text needs a case change when button is clicked. Having trouble creating JS for this

I need to create two input text boxes that when the UpperCase button is clicked the input text is returned all in caps and when the LowerCase button is clicked the input text is returned in lower case. So for example:
Text: SuNsHiNe ToDaY
(upper case button)= SUNSHINE TODAY
(lower case button)= sunshine today
I have pasted the html code below and need help creating the JS code:
<!doctype html>
<html>
<head>
<script src='../p3-case.js'></script>
</head>
<body>
<form action="demo_form.asp" id="demo_form">
Phrase:
<input type="text" id="input1" name="changeCase" placeholder="Put Phrase Here">
<br>
<input type="button" id="btn1" value="upperCase"/>
<input type="button" id="btn2" value="lowerCase"/>
</form>
</body>
</html>
I think you not need to use any external js just using Jquery
You need to use toLowerCase() and toUpperCase()
$("#btn1").click(function(){
var input = $("#input1");
input.val(input.val().toUpperCase());
});
$("#btn2").click(function(){
var input = $("#input1");
input.val(input.val().toLowerCase());
});
Here is sample of jsbin JSBIN
Here you go:
<!doctype html>
<html>
<head>
<script>
function upper()
{
var uc = document.getElementById('input1').value;
document.getElementById('input1').value = uc.toUpperCase();
}
function lower()
{
var lc = document.getElementById('input1').value;
document.getElementById('input1').value = lc.toLowerCase();
}
</script>
</head>
<body>
<form action="demo_form.asp" id="demo_form">
Phrase:
<input type="text" id="input1" name="changeCase" placeholder="Put Phrase Here">
<br>
<input type="button" id="btn1" value="upperCase" onclick="upper();">
<input type="button" id="btn2" value="lowerCase" onclick="lower();">
</form>
</body>
</html>
writing from my tablet but i try my best! :)
Pure JavaScript:
Add onclick event to the button:
<input type="button" onclick="toupp()" id="btn1" value="upperCase";">
Then the functions
<script>
var toupp = function(){
var text = document.getElementById("input1").value;
document.getElementById("input1").value = text.value.toUpperCase();
}
and the other function:
var tolow = function(){
var text = document.getElementById("input1").value;
document.getElementById("input1").value = text.toLowerCase();
}
</script>
This code works perfectly for me
<!doctype html>
<html>
<head>
<script >
function toUpper(){
var obj = document.getElementById("input1");
var str = obj.value;
var res = str.toUpperCase();
obj.value = res;
}
function toLower(){
var obj = document.getElementById("input1");
var str = obj.value;
var res = str.toLowerCase();
obj.value = res;
}
</script>
</head>
<body>
<form action="demo_form.asp" id="demo_form">
Phrase:
<input type="text" id="input1" name="changeCase" placeholder="Put Phrase Here">
<br>
<input type="button" id="btn1" onClick='toUpper()' value="upperCase";">
<input type="button" id="btn2" onClick='toLower()' value="lowerCase">
</form>
</body>
</html>

Trying to get the result of javascript function using innerHTML

I have a simple program that takes in an input and then should show that input multiplied up to 100. I am new to this, but have tried to get it to work before posting here. I have the link to the program that I am referring to.
I want the result to be shown, but I cannot figure out why it is not showing.
You can see what I have below. I think I do not have the html and javascript hooked up properly.
Here is my html:
<body>
<input type="number" id="NumToBMultiplied" class="value" placeholder="Enter an integer" />
<input type='submit' id='RunProg' class='button' />
<p> id='result'</p>
</body>
Here is my Javascript:
h = document.getElementByID('NumToBMultiplied');
var result = document.getElementbyID('RunProg').addEventListener('click', function () {
for (i = 0; i < 100; i++)
return i * h;
}
});
document.getElementByID('result').innerHTML = result;
http://jsbin.com/wayejequxu/1/edit?html,js,output
Any help is appreciated!
From how I understand your code, you are wanting to multiply the input 100 times, then output that into a HTML tag. The result in your example is not being added to the result paragraph as it isn't in the loop.
HTML
This is changed only slightly. Notice the onClick="solve()" to the button instead of adding an event listener.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>JS Bin</title>
</head>
<body>
<input type="number" id="NumToBMultiplied" class="value" placeholder="Enter an integer"/>
<input type="submit" id="RunProg" onClick="solve()" class="button"/>
<p id="result"> </p>
</body>
</html>
Javascript
I've added a line break after each result of the for loop so the result is easier to read. And the output is cleared before a new solve() is run.
var output = document.getElementById("result");
function solve() {
var input = document.getElementById("NumToBMultiplied").value;
output.innerHTML = "";
for(i=0; i < 100; i++) {
output.innerHTML += i * input + "<br/>";
}
}
Result here: http://jsbin.com/foduyofewi/1/
You need to store your result in variable inside a callback and set innerHTML also in callback:
document.getElementById('RunProg').addEventListener("click", function() {
var result = 1;
var input = +h.value;
for (var i = 1; i < 100; i++) {
result *= i * input;
}
document.getElementById("result").innerHTML = result;
});
DEMO
Pure Javascript version:
function multiply(x) {
var result = document.getElementById('result');
result.innerHTML = x.value * 100;
}
<input type="number" id="NumToBMultiplied" class="value" onchange="multiply(this)" placeholder="Enter an integer"/>
<p id="result"></p>
This is the jQuery version:
$(document).ready(function() {
$('#NumToBMultiplied').on('change',function(){
$('#result').text($(this).val()*100);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="number" id="NumToBMultiplied" class="value" placeholder="Enter an integer"/>
<p id="result"></p>
Just some modification to your code to remove some of the typos and errors. I'm not sure you can return the result like how you have done it, a more traditional approach is shown below.
Full code
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<input type="number" id="NumToBMultiplied" class="value" placeholder="Enter an integer" />
<input type='submit' id='RunProg' class='button' />
<p id='result'> </p>
</body>
<script>
h = document.getElementById('NumToBMultiplied').value;
document.getElementById('RunProg').addEventListener('click', function () {
for (i = 0; i < 100; i++){
var result = h*i;
}
document.getElementById('result').innerHTML = result;
});
</script>
</html>

Categories

Resources