This is a shema in HTML5. HTML5 has attributes like: autofocus, placeholder, date etc. Not all browsers supports these. Therefore I want to make some fallback functions. I'm not that familiar with JS, JQuery, but i really want to learn :)
The fallbackfuntions uses the elementSupportAttribute-function to check wether or not an element can hold a specific attribute. The code works fine when I don't run the methods through this if-statement: if (!(elementSupportsAttribute(element, attribute)), but when I do, the code does not run at all. Can anybody see the problem?
Also, I tried to use the Modernizr-framework, but did not manage that either.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset= "UTF-8" />
<!--[if lt IE 9]>
<script src="http://html5shim.googlecode.com/svn/trunk/html5.js"></script>
<![endif]-->
<link type="text/css" rel="stylesheet" href="Skjema.css"/>
<title>Bestilling av busstur</title>
<link rel="stylesheet" href="http://code.jquery.com/ui/1.10.1/themes/base/jquery-ui.css" />
<script src="//ajax.googleapis.com/ajax/libs/jqueryui/1.9.1/jquery-ui.min.js"></script>
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script src="http://code.jquery.com/ui/1.10.1/jquery-ui.js"></script>
<link rel="stylesheet" href="/resources/demos/style.css" />
<script type="text/javascript">
$(document).ready(function() {
if (!(elementSupportsAttribute('input','autofocus')) {
$("#auto").focus();
}
if(!(elementSupportsAttribute('input','date')){
$("#datepicker").datepicker();
}
});
function elementSupportsAttribute(element,attribute){
var test = document.createElement(element);
if (attribute in test){
return true;
}
else {
return false;
}
}
function finnAlleRequired(){
if (!(elementSupportsAttribute('input', 'required')){
var alle = document.getElementsByClassName("requiredInput");
var print = "";
for (i=0;i<alle.length; i++){
var temp = alle[i];
if (temp.value==""){
print += temp.name + " ";
temp.classList.add("error");
}
else {
temp.classList.remove("error");
}
}
}
if(!(elementSupportsAttribute('input','number')){
numberCheck();
}
}
function numberCheck () {
var number = document.getElementById("number").value;
var min = 1;
var max = 10;
if(number < 1 || number > 10){
alert("Antallet personer du kan bestille til er mellom 1 og 10");
}
}
</script>
</head>
<body>
<header>
<h1>
Bestilling av busstur
</h1>
</header>
<article>
Vennligst fyll ut skjema under for å bestille busstur. Du kan bestille plasser for max 10 personer. Felter markert med <label class="required">*</label> er obligatoriske.
</article>
<form>
<p>
<label for="name">Navn:</label><br/>
<input type="text" name="name" placeholder="Fullt navn" id="auto" autofocus>
</p>
<p>
<label class="required">*</label>
<label for="email">E-post:</label><br/>
<input type="email" name="email" placeholder="nordmann#norge.no" class="requiredInput" required>
</p>
<p>
<label for="phone">Telefon:</label><br/>
<input type="tel" name="phone" placeholder="11223344"> </p>
<p>
<label class="required">*</label>
<label for="date">Dato:</label><br/>
<input type="date" name="date" id="datepicker" class="requiredInput"required>
</p>
<p>
<label class="required">*</label>
<label for="numberPersons">Antall:</label><br/>
<input type="number" name="numberPersons" min="1" max="10" value="2" class="requiredInput" id="number" required>
</p>
<p>
<label for="other">Hvor fant du informasjon om oss?</label><br/>
<input type="text" name="other" placeholder="Facebook, Twitter, venner">
</p>
<p>
<input type="submit" value="Registrer" onclick="finnAlleRequired()">
</form>
</body>
</html>
Your best bet is probably to find polyfill(s) for the features you wish to ensure are supported.
https://github.com/Modernizr/Modernizr/wiki/HTML5-Cross-Browser-Polyfills
Also, I tried to use the Modernizr-framework, but did not manage that
either.
Modernizr doesn't automatically fix unsupported features, but will let you know what features are available and conditionally load fallbacks.
The code works fine when I don't run the methods through this
if-statement: if (!(elementSupportsAttribute(element, attribute)), but
when I do, the code does not run at all.
I ran a quick test using this snippet and several HTML 5 form attributes.
function elementSupportsAttribute(element,attribute){
var test = document.createElement(element);
if (attribute in test){
return true;
}
else {
return false;
}
}
alert(elementSupportsAttribute("input", "required"));
The function does appear to work in Chrome 24: http://jsfiddle.net/eT5Ac/.
However, it would be much better to use one of Modernizr's established tests, specifically the Input Types Test.
Related
Working on an HTML integration with GAS, the following code is not doing anything but generating a white, seemingly empty form upon clicking "Add":
//GLOBALS
let ss = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet();
var lastRow = ss.getLastRow();
var lastCol = ss.getLastColumn();
var ui = SpreadsheetApp.getUi();
var arrEndRow;
var icaoFindMatch = 0;
//Upon opening spreadsheet, menu items are added and a test is made to determine
//if there are any entries and if not, it will load an entry form
function onOpen(e) {
//creates custom menu
ui.createMenu('Catering Menu')
.addItem('Search Locations', 'menuItem1')
.addItem('Add Catering Info', 'menuItem2')
.addToUi();
//test if there is at least one entry
if (lastRow == 1){
loadForm(); //run entry form
} else {
SpreadsheetApp.getActiveSpreadsheet().toast("Use the 'Catering Menu' dropdown on the toolbar to search, add or modify existing catering info.","User Notice",-1);
}
}
function testMe(){
ui.alert("in TestMe");
}
//takes info entered on the uForm.html and enters it under the appropriate ICAO location
function addNewRow(rowData){
ui.alert("in addNewRow");
/*
var icaoResult = ui.prompt("Please input your ICAO");
var resultText = icaoResult.getResponseText();
*/
let icaoRangeInit = ss.getRange(2,1,lastRow-1,1).getValues();
let icaoArr = icaoRangeInit.filter((string) => string != "");
let icaoArrLast = icaoArr[icaoArr.length-1];
<!doctype html>
<html lang="en">
<head>
<!-- Required meta tags -->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<!-- Bootstrap CSS -->
<link href="https://cdn.jsdelivr.net/npm/bootstrap#5.0.0-beta3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-eOJMYsd53ii+scO/bJGFsiCZc+5NDVN2yr8+0RDqr0Ql0h+rP48ckxlpbzKgwra6" crossorigin="anonymous">
<title>Catering Entry Form</title>
</head>
<body>
<form>
<div class="form-floating mb-4">
<input type="text" class="form-control" id="floatingLocation" placeholder="ICAO Location">
<label for="floatingLocation">ICAO</label>
</div>
<div class="form-floating">
<input type="text" class="form-control" id="floatingName" placeholder="Name">
<label for="floatingName">Name</label>
</div>
<div class="form-floating">
<input type="number" class="form-control" id="floatingDistance" placeholder="Distance (mi)">
<label for="floatingDistance">Distance (mi)</label>
</div>
<div class="form-floating">
<input type="number" class="form-control" id="floatingDriveTime" placeholder="Drive Time (min)">
<label for="floatingDriveTime">Drive Time (min)</label>
</div>
<div class="form-floating">
<input type="text" class="form-control" id="floatingPhoneNum" placeholder="Phone #">
<label for="floatingPhoneNum">Phone Number</label>
</div>
<div class="form-floating">
<input type="text" class="form-control" id="floatingSite" placeholder="Website">
<label for="floatingSite">Website</label>
</div>
<div class="form-floating">
<input type="text" class="form-control" id="floatingDelivery" placeholder="Delivery?">
<label for="floatingDelivery">Delivery (Yes/No)</label>
</div>
<div class="form-floating">
<textarea class="form-control" placeholder="Notes" id="floatingTextarea"></textarea>
<label for="floatingTextarea">Notes</label>
</div>
<div>
<button class="btn btn-primary" id="AddtoWS">Add</button>
</div>
</form>
<!-- jQuery first, then Popper.js, then Bootstrap JS -->
<script src="https://code.jquery.com/jquery-3.4.1.slim.min.js" integrity="sha384-J6qa4849blE2+poT4WnyKhv5vZF5SrPo0iEjwBvKU7imGFAV0wwj1yYfoRSJoZ+n" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/popper.js#1.16.0/dist/umd/popper.min.js" integrity="sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js" integrity="sha384-wfSDF2E50Y2D1uUdj0O3uMBJnjuUD4Ih7YwaYd1iqfktj0Uod8GCExl3Og8ifwB6" crossorigin="anonymous"></script>
<!-- script to take the values inputted in fields above and transfer to spreadsheet -->
<script>
function afterButtonClicked() {
google.script.run.testMe();
var icao = document.getElementById("floatingLocation");
var name = document.getElementById("floatingName");
var dist = document.getElementById("floatingDistance");
var driveTime = document.getElementById("floatingDriveTime");
var phoneNum = document.getElementById("floatingPhoneNum");
var site = document.getElementById("floatingSite");
var delivery = document.getElementById("floatingDelivery");
var notes = document.getElementById("floatingTextarea");
var rowData = {icao: icao.value, name: name.value, dist: dist.value, driveTime: driveTime.value, phoneNum: phoneNum.value, site: site.value, delivery: delivery.value, notes: notes.value};
//google.script.run.testMe();
}
document.getElementById("AddtoWS").addEventListener("click", afterButtonClicked); //tells the "Add" button what to do
</script>
</body>
</html>
That's the entirety of the HTML which does everything from loading the sidebar and input fields, all the way to the button but it's not properly calling my Javascript in the Code.js
Also, I only pasted the top snippet of my Code.js because it's clear I'm not evening getting to where I can get the testMe() function called to check that the handshake between html and js is even working.
I've spent more hours trying to figure this out than I care to admit, any help would be greatly appreciated!
Colin
You have not called on onclick. You can call the function as shown below.
<div>
<button class="btn btn-primary" onclick="afterButtonClicked()" id="AddtoWS">Add</button>
</div>
You need to add an attribute to the button called onclick, which tells the webpage what to do if that button is clicked, for ex.
<div>
<button class="btn btn-primary" id="AddtoWS">Add</button>
</div>
should be changed to
<div>
<button class="btn btn-primary" id="AddtoWS" onclick="functionYouWantToRun()">Add</button>
</div>
if JS file is connected to it even with the src attribute, it will work the same, just add the code to run,
or you can add an eventListener. Ex:
document.getElementById(AddtoWs).addEventListener('click',function(){
//Add the JS code you want to run
});
, it will basically run the code inside the function(){}, once someone clicks the button.
Edit: I just double-checked your code and you added the eventListener, but there is a problem, you need to add the function before you use the addEventLsitener.
Edit No.2: Try adding the function in the eventListener, I made a mistake in the first edit.
Edit No,3: Try this code, This should work:
<!doctype html>
<html lang="en">
<head>
<!-- Required meta tags -->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<!-- Bootstrap CSS -->
<link href="https://cdn.jsdelivr.net/npm/bootstrap#5.0.0-beta3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-eOJMYsd53ii+scO/bJGFsiCZc+5NDVN2yr8+0RDqr0Ql0h+rP48ckxlpbzKgwra6" crossorigin="anonymous">
<!-- Refering the JS code you had first put-->
<script src="anyname.js"></script>
<!---->
<title>Catering Entry Form</title>
</head>
<body>
<form>
<div class="form-floating mb-4">
<input type="text" class="form-control" id="floatingLocation" placeholder="ICAO Location">
<label for="floatingLocation">ICAO</label>
</div>
<div class="form-floating">
<input type="text" class="form-control" id="floatingName" placeholder="Name">
<label for="floatingName">Name</label>
</div>
<div class="form-floating">
<input type="number" class="form-control" id="floatingDistance" placeholder="Distance (mi)">
<label for="floatingDistance">Distance (mi)</label>
</div>
<div class="form-floating">
<input type="number" class="form-control" id="floatingDriveTime" placeholder="Drive Time (min)">
<label for="floatingDriveTime">Drive Time (min)</label>
</div>
<div class="form-floating">
<input type="text" class="form-control" id="floatingPhoneNum" placeholder="Phone #">
<label for="floatingPhoneNum">Phone Number</label>
</div>
<div class="form-floating">
<input type="text" class="form-control" id="floatingSite" placeholder="Website">
<label for="floatingSite">Website</label>
</div>
<div class="form-floating">
<input type="text" class="form-control" id="floatingDelivery" placeholder="Delivery?">
<label for="floatingDelivery">Delivery (Yes/No)</label>
</div>
<div class="form-floating">
<textarea class="form-control" placeholder="Notes" id="floatingTextarea"></textarea>
<label for="floatingTextarea">Notes</label>
</div>
<div>
<button class="btn btn-primary" id="AddtoWS">Add</button>
</div>
</form>
<!-- jQuery first, then Popper.js, then Bootstrap JS -->
<script src="https://code.jquery.com/jquery-3.4.1.slim.min.js" integrity="sha384-J6qa4849blE2+poT4WnyKhv5vZF5SrPo0iEjwBvKU7imGFAV0wwj1yYfoRSJoZ+n" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/popper.js#1.16.0/dist/umd/popper.min.js" integrity="sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js" integrity="sha384-wfSDF2E50Y2D1uUdj0O3uMBJnjuUD4Ih7YwaYd1iqfktj0Uod8GCExl3Og8ifwB6" crossorigin="anonymous"></script>
<!-- script to take the values inputted in fields above and transfer to spreadsheet -->
<script>
/*function afterButtonClicked() {
}*/
document.getElementById("AddtoWS").addEventListener('click', function(){
google.script.run.testMe();
var icao = document.getElementById("floatingLocation");
var name = document.getElementById("floatingName");
var dist = document.getElementById("floatingDistance");
var driveTime = document.getElementById("floatingDriveTime");
var phoneNum = document.getElementById("floatingPhoneNum");
var site = document.getElementById("floatingSite");
var delivery = document.getElementById("floatingDelivery");
var notes = document.getElementById("floatingTextarea");
var rowData = {icao: icao.value, name: name.value, dist: dist.value, driveTime: driveTime.value, phoneNum: phoneNum.value, site: site.value, delivery: delivery.value, notes: notes.value};
//google.script.run.testMe();
}); //tells the "Add" button what to do
</script>
</body>
</html>
,anyname.js:
//GLOBALS
let ss = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet();
var lastRow = ss.getLastRow();
var lastCol = ss.getLastColumn();
var ui = SpreadsheetApp.getUi();
var arrEndRow;
var icaoFindMatch = 0;
//Upon opening spreadsheet, menu items are added and a test is made to determine
//if there are any entries and if not, it will load an entry form
function onOpen(e) {
//creates custom menu
ui.createMenu('Catering Menu')
.addItem('Search Locations', 'menuItem1')
.addItem('Add Catering Info', 'menuItem2')
.addToUi();
//test if there is at least one entry
if (lastRow == 1){
loadForm(); //run entry form
} else {
SpreadsheetApp.getActiveSpreadsheet().toast("Use the 'Catering Menu' dropdown on the toolbar to search, add or modify existing catering info.","User Notice",-1);
}
}
function testMe(){
ui.alert("in TestMe");
}
//takes info entered on the uForm.html and enters it under the appropriate ICAO location
function addNewRow(rowData){
ui.alert("in addNewRow");
/*
var icaoResult = ui.prompt("Please input your ICAO");
var resultText = icaoResult.getResponseText();
*/
let icaoRangeInit = ss.getRange(2,1,lastRow-1,1).getValues();
let icaoArr = icaoRangeInit.filter((string) => string != "");
let icaoArrLast = icaoArr[icaoArr.length-1];
I have a website that when the user leaves any of the text fields blank, the border of the box will turn red. I figured it out in css with these lines of code
.input-box{
border-color: red;
}
.input-box:focus{
outline: none;
}
But I want to implement this in my php code if the fields are empty. I've been searching this all around an cannot find a solution. I even tried JavaScript and got to this point
if(empty($fullname)){
echo "
<script type=\"text/javascript\">
document.getElementByClassName('input-box').style.borderStyle = 'solid';,
document.getElementByClassName('input-box').style.border = '';,
document.getElementByClassName('input-box').style.borderColor = 'red';
</script>
";
}
if(empty($email)){
echo "
<script type=\"text/javascript\">
document.getElementByClassName('input-box').style.borderStyle = 'solid';,
document.getElementByClassName('input-box').style.border = '';,
document.getElementByClassName('input-box').style.borderColor = 'red';
</script>
";
}
if(empty($password)){
echo "
<script type=\"text/javascript\">
document.getElementByClassName('input-box').style.borderStyle = 'solid';,
document.getElementByClassName('input-box').style.border = '';,
document.getElementByClassName('input-box').style.borderColor = 'red';
</script>
";
}
if(!empty($fullname) && !empty($email) && !empty($password)){
echo "you're in";
}
But it is not working. So all I want to do is when the user leaves a field empty, the border of the box will turn red and the outline will be none.
getElementsByClassName returns an array, so you cannot assign properties like style.
Here's the JavaScript you want:
var inputs= document.getElementsByClassName("input-box");
for(var i=0; i<inputs.length; i++) {
inputs[i].style.borderStyle = 'solid';
inputs[i].style.border = '';
inputs[i].style.borderColor = 'red';
}
My Code is based on jQuery.
Hope It will help you...
$('#user-form').submit(function(e) {
var name = $('#name').val();
var email = $('#email').val();
var phone = $('#phone').val();
var address = $('#address').val();
var dob = $('#dob').val();
if(name=="") $('#name').addClass('input-box'); else $('#name').removeClass('input-box');
if(email=="") $('#email').addClass('input-box'); else $('#email').removeClass('input-box');
if(phone=="") $('#phone').addClass('input-box'); else $('#phone').removeClass('input-box');
if(address=="") $('#address').addClass('input-box');else $('#address').removeClass('input-box');
if(dob=="") $('#dob').addClass('input-box'); else $('#dob').removeClass('input-box');
if((name=="")||(email=="")||(phone=="")||(address=="")||(dob==""))event.preventDefault();
});
.input-box{
border-color: red;
}
.input-box:focus{
outline: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form method="post" id="user-form" action="q.php">
<p><label>Name : </label><input type="text" id="name" name="name" /></p>
<p><label>Email : </label><input type="text" id="email" name="email" /></p>
<p><label>Phone : </label><input type="text" id="phone" name="phone" /></p>
<p><label>Address : </label><input type="text" id="address" name="address" /></p>
<p><label>DOB : </label><input type="text" id="dob" name="dob" /></p>
<p><button type="submit" id="submit">Submit</button></p>
</form>
While I am not a big fun of mixing PHP/server code with front end like that, there is an obvious error (unless it was intended). Since you are using class input-box for all, if any one field is empty, all will be marked as empty.
Anyway, try the following:
first, the styles you want to apply for empty fields are the same. So, in your css file define one. E.g.
.needed-field {border:1px solid red;}
Then give each field a unique id while keeping the class input-box in place.
Then do two things in your PHP file: remove any possible bad field from before when submitting the form or something:
$('.input-box').removeClass('needed-field');
Then for each one:
if(empty($fullname)){
echo "
<script type=\"text/javascript\">
$('#fullname').addClass('needed-field');
</script>
";
}
Hope that helps.
Edit:
<html lang="en">
<head>
<meta charset="utf-8">
<title></title>
<base href="/">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="icon" type="image/x-icon" href="favicon.ico">
<style>
.needed_field {border:5px solid red;}
</style>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
</head>
<body>
<form action="so/1.php" method="post">
<input type="text" id="fullname" name="fullname" class="input-box"><br/>
<input type="text" id="email" name="email" class="input-box"><br/>
<input type="text" id="password" name="password" class="input-box"><br/>
<input type="submit" value="Sumbit" id="submit" name="submit">
</form>
<script>
$('.input-box').removeClass('needed_field');
<?php
if($_POST['submit']){
//echo '<script>'
//echo '</script>';
$fullname=$_POST['fullname'];
$email=$_POST['email'];
$pwd=$_POST['pwd'];
if(empty($fullname)){
echo "$('#fullname').addClass('needed_field');";
}
}
?>
</script>
</body>
</html>
Sorry if this question is answered somewhere, but I couldn't find anything close to my question or an answer in other posts.
I'm trying to make a blog, but I'm still learning, so I use my index page for experimenting. Anyways, I have a section on my webpage where you get an output dependant on the input of the user and I can't get the input from the webpage to be received by the JavaScript.
DO NOTE that I only tried this in Microsoft Edge on my laptop and Firefox on my phone, but I don't think that it's to my browsers.
Also, I think it effects my calculator, but that's not for this post.
Feel free to edit my code in the answers, but it would be preferred to explain the edits to the code.
Anyways, thank you in advance for any help you're willing to provide!
Note that I haven't found any posts that answer my question, so please link to the post before closing this post :)
Also, the blank spaces are for future code and I'm not a pro in case someone didn't figure that out.
function age(){
var age=document.getElementById('age');
if(age<18){
document.getElementById('Age').innerHTML="Underage";
alert("This is your age: "+age);
}
else{document.getElementById('Age').innerHTML="Of age";
alert("This is your age: "+age);
}
}
function calculate(){
var num1=document.getElementById('firstNumber');
var num2=document.getElementById('secondNumber');
var sum=num1+num2;
document.getElementById('Age').innerHTML=sum;
}
.page{background-color:#ce6efa;}
#firstHeading{font-family:Nyala, "Palatino Linotype";}
label{color:#5728ad;}
#Age{color:#243bd4;}
<!DOCTYPE html>
<!--Work on this blog began on the 24th of June 2017-->
<html>
<meta charset="UTF-16">
<head>
<link rel="stylesheet" href="mainpage.css">
<title>Sandi Vujaković</title>
</head>
<body class="page">
<h2 id="firstHeading">My life</h2>
<label>First number</label>
<input type="number" id="fistNumber" name="Number a">
<label>Second number</label>
<input type="number" id="secondNumber" name="Number b">
<input type="submit" onclick="calculate()" value="Calculate"><br/>
<p id="calc"></p>
<label>Age</label>
<input type="number" id="age" name="age">
<input type="submit" onclick="age()" value="Check"><br/>
<p id="Age"></p>
<script src="mainpage.js"></script>
</body>
</html>
If I use alert(), I get odd results. Like in the code, the output is
This is your age: [object HTMLInputElement].
When I change it to:
var age2=++age;
alert("This is your age: "+age2);
then the output goes from [object HTMLInputElement] to NaN.
Explanations?
Okay?
At first I found some inconsistencies:
1- "var age = document.getElementById ('age')" failed to report which property needed. In your case: "value". In the "calculate" function I encountered the same problem on the first two lines
2- "var num1 = document.getElementById ('fistNumber')" element id was wrong. I have corrected for "firstNumber"
3- In two moments in which you make a comparison of the age and sum of the values captured in the "calculate" function, I used the "parseInt" function to prevent the variables from being considered strings and thus concatenated.
I hope I have helped.
function age(){
var age=document.getElementById('age').value;
if(parseInt(age)<18){
document.getElementById('Age').innerHTML="Underage";
alert("This is your age: "+age);
}
else{alert("This is your age: "+age);
}
}
function calculate(){
var num1=document.getElementById('firstNumber').value;
var num2=document.getElementById('secondNumber').value;
var sum=parseInt(num1)+parseInt(num2);
document.getElementById('Age').innerHTML=sum;
}
.page{background-color:#ce6efa;}
#firstHeading{font-family:Nyala, "Palatino Linotype";}
label{color:#5728ad;}
#Age{color:#243bd4;}
<!DOCTYPE html>
<!--Work on this blog began on the 24th of June 2017-->
<html>
<meta charset="UTF-16">
<head>
<link rel="stylesheet" href="mainpage.css">
<title>Sandi Vujaković</title>
</head>
<body class="page">
<h2 id="firstHeading">My life</h2>
<label>First number</label>
<input type="number" id="firstNumber" name="Number a">
<label>Second number</label>
<input type="number" id="secondNumber" name="Number b">
<input type="submit" onclick="calculate()" value="Calculate"><br/>
<p id="calc"></p>
<label>Age</label>
<input type="number" id="age" name="age">
<input type="submit" onclick="age()" value="Check"><br/>
<p id="Age"></p>
<script src="mainpage.js"></script>
</body>
</html>
So here are the changes I made:
Firstly, use the value of the property of dom elements you fetch by id.
Then correct the spelling of firstNumber in you HTML. You have mistyped fistNumber.
Also before comparing (x<18) in your age function, you must convert the string to an integer using the parseInt function.
function age(){
var age=document.getElementById('age').value;
age = parseInt(age);
if(age<18){
document.getElementById('Age').innerHTML="Underage";
alert("This is your age: "+age);
}
else{alert("This is your age: "+age);
}
}
function calculate(){
var num1=document.getElementById('firstNumber').value;
var num2=document.getElementById('secondNumber').value;
var sum=num1+num2;
document.getElementById('Age').innerHTML=sum;
}
.page{background-color:#ce6efa;}
#firstHeading{font-family:Nyala, "Palatino Linotype";}
label{color:#5728ad;}
#Age{color:#243bd4;}
<!DOCTYPE html>
<!--Work on this blog began on the 24th of June 2017-->
<html>
<meta charset="UTF-16">
<head>
<link rel="stylesheet" href="mainpage.css">
<title>Sandi Vujaković</title>
</head>
<body class="page">
<h2 id="firstHeading">My life</h2>
<label>First number</label>
<input type="number" id="firstNumber" name="Number a">
<label>Second number</label>
<input type="number" id="secondNumber" name="Number b">
<input type="submit" onclick="calculate()" value="Calculate"><br/>
<p id="calc"></p>
<label>Age</label>
<input type="number" id="age" name="age">
<input type="submit" onclick="age()" value="Check"><br/>
<p id="Age"></p>
<script src="mainpage.js"></script>
</body>
</html>
You need to get the 'value' of the property: document.getElementById('age').value;
Also, your first name input ID is miss-spelled. "fistNumber"
function age() {
var age = document.getElementById('age').value;
if(age == "" || age == null) {
alert("Please enter an age!");
return;
}
if (parseInt(age) < 18) {
document.getElementById('alert').innerHTML = "Underage";
alert("This is your age: " + age);
} else {
document.getElementById('alert').innerHTML = "Of Age";
alert("This is your age: " + age);
}
}
function calculate() {
var num1 = document.getElementById('firstNumber').value;
var num2 = document.getElementById('secondNumber').value;
var sum = parseInt(num1) + parseInt(num2);
document.getElementById('alert').innerHTML = sum;
}
.page {
background-color: #ce6efa;
}
#firstHeading {
font-family: Nyala, "Palatino Linotype";
}
label {
color: #5728ad;
}
#Age {
color: #243bd4;
}
<!DOCTYPE html>
<!--Work on this blog began on the 24th of June 2017-->
<html>
<meta charset="UTF-16">
<head>
<link rel="stylesheet" href="mainpage.css">
<title>Sandi Vujaković</title>
</head>
<body class="page">
<h2 id="firstHeading">My life</h2>
<label>First number</label>
<input type="number" id="firstNumber" name="Number a">
<label>Second number</label>
<input type="number" id="secondNumber" name="Number b">
<input type="submit" onclick="calculate()" value="Calculate"><br/>
<p id="calc"></p>
<label>Age</label>
<input type="number" id="age" name="age">
<input type="submit" onclick="age()" value="Check"><br/>
<p id="alert"></p>
<script src="mainpage.js"></script>
</body>
</html>
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>
So I have this code and it does not seem to work. The thing I want it to do is to call the "together" from the function "go" in the function "second". What am i doing wrong?
The program was initially supposed to take what is in the input-text and add it with the ".com" or the ".no"(depending on what u checked) and redirect to that page. But I only want to call the "together" in the "second" function. Is there any better way to do it?
<!doctype html>
<html>
<head>
<title>A Basic Form</title>
<link rel="stylesheet" type="text/css">
<style type="text/css">
</style>
</head>
<body>
<fieldset>
<legend>Redirection: </legend>
<div>
<label>Where do you want to go?</label>
<input type="text" id="input" name="input" size="7">
<input type="button" id="submit" name="submit" value="Submit" onclick="go()">
</div>
<div>
<input type="radio" id="no" name="end" value=".no">
<label for="no">.no</label><br />
<input type="radio" id="com" name="end" value=".com">
<label for="com">.com</label>
</div>
</fieldset>
<script type="text/javascript">
var end = "";
var input = document.getElementById("input").value;
function go(end, input){
if (document.getElementById("no").checked){
end = document.getElementById("no").value;
}else if (document.getElementById("com").checked){
end = document.getElementById("com").value;
}else{
alert("Please Choose a category!");
}
var together = input + end;
// window.location.replace("http://www." + together);
}
second(together);
function second(together){
alert(together);
}
</script>
</body>
</html>
function go(end, input){
if (document.getElementById("no").checked){
end = document.getElementById("no").value;
}else if (document.getElementById("com").checked){
end = document.getElementById("com").value;
}else{
alert("Please Choose a category!");
}
var together = input + end;
// window.location.replace("http://www." + together);
} // remove this
second(together);
} // add this