When I press submit, I'm trying to capture the current lat-long and after that I'm running some validations and returning true or false depending on if they are met or not. My problem is that the location function is async and I can't get it to work with my function. I've tried many ways to get this to work, and haven't been successful. I'm hoping you guys could shed some light on what I can do to get it to work like I want. What I want is to capture those coordinates, then execute my save function.
$("#save").click(function(){
navigator.geolocation.getCurrentPosition(function(position){
$('#lat-location-end').attr('value', position.coords.latitude);
$('#lon-location-end').attr('value',position.coords.longitude);
saveData();
} function() {
saveData();
});
});
function saveData(){
var odleave = $('#odometer-leave').val();
var odarrival = $('#odometer-arrival').val();
var miles = $('#mil').data('mile');
if (odarrival < odleave){
alert("Odometer: Arrival must not be less than Odometer: Leave");
return false;
}
if (odleave != miles){
if (odleave > miles){
var mile_diff = odleave - miles;
if (mile_diff > 25){
if (!confirm("Your leaving mileage exceeds by " + mile_diff + " miles from your last mileage. Do you want to continue?"))
return false;
}
} else {
if(!confirm("Mileage entered is less than your last mileage. Are you using a new car?"))
return false;
}
//Return the image
var sig = signaturePad.toDataURL("image/png");
sig = sig.split(',')[1];
$('#sig-data').attr('value', sig);
return true;
}
Please, I've been having trouble with this all day and I can't find a way to solve this. I asked something similar this morning but I noticed that the question I was asking was the wrong one. I hope this doesn't get me in trouble. Any help will be appreciated.
Here's a solution that I came up with. For this to work you will be needing both files as it is necessary to make everything work.
semantic.css
semantic.js
it's either you download it locally from semantic-ui or get it on the cdnjs semantic-ui on cdnjs.
Hope it helps.
here is the code:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Get geolocation on Javascript then submit form if validations are met</title>
<link rel="stylesheet" href="http://keith-santiago.com/css/semantic.css">
<style type="text/css">
div#this-form {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}
</style>
</head>
<body>
<div id="this-form" class="ui raised very padded text container segment">
<div class="ui form">
<form class="ui form">
<div class="field">
<label>Odometer Arrival</label>
<input name="odometer-arrival" placeholder="Arrival" type="number">
</div>
<div class="field">
<label>Odometer Leave</label>
<input name="odometer-leave" placeholder="Leave" type="number">
</div>
<div class="field">
<div class="ui checkbox">
<input name="toc" type="checkbox">
<label>I agree to the Terms and Conditions</label>
</div>
</div>
<button class="ui button" type="submit">Submit</button>
</form>
</div>
</div>
<script
src="http://code.jquery.com/jquery-3.2.1.min.js"
integrity="sha256-hwg4gsxgFZhOsEEamdOYGBf13FyQuiTwlAQgxVSNgt4="
crossorigin="anonymous"></script>
<script src="http://keith-santiago.com/js/semantic.js"></script>
<script type="text/javascript">
$(document).ready( function() {
$('.ui.button').click(function() {
var $form = $('.ui.form');
var odarrival = parseInt($form.form('get value', 'odometer-arrival'));
var odleave = parseInt($form.form('get value', 'odometer-leave'));
$('.ui.form').form({
fields : {
arrival : {
identifier : 'odometer-arrival',
rules : [{
type: 'empty',
prompt : "please enter a valid number"
}]
},
leave : {
identifier : 'odometer-leave',
rules: [ {
type : 'empty'
}
]
},
toc : {
identifier : 'toc',
rules : [{
type : 'checked'
}]
}
}
});
if ( $('.ui.form').form('is valid')) {
if ( odarrival < odleave ) {
// this block handles everything before submitting. if the condition are not met it will prevent the form from submitting.
return false;
}
}
});
});
</script>
</body>
</html>
Related
this is my code:
"use strict";
const searchBox = document.querySelector("#myText");
const searchBtn = document.querySelector(".btn-search");
const searchContainer = document.querySelector(".search-container");
let mainText = document.querySelector(".main-text");
const quit = document.querySelector("#btn-close");
let showMain;
const newMain = "";
let printMain = function(text) {
showMain = `
<article class="country">
<h1>Country you Searched</h1>
<p>Hello</p>
<p>${text}</p>
</article>`;
console.log(`Our show main is : ${showMain}`);
mainText.insertAdjacentHTML("beforeend", showMain);
};
searchBox.addEventListener("click", function() {
if (searchBox.value === "Type in") {
searchBox.value = "";
}
});
searchBtn.addEventListener("click", function() {
if (searchBox.value && searchBox.value !== "Type in") {
console.log(searchBox.value);
printMain(searchBox.value);
searchBox.value = "";
} else {
alert("please type in country name!");
}
});
quit.addEventListener("click", function() {
//mainText.remove(showMain);
const myDiv = document.getElementById("myId");
const parent = myDiv.parentNode;
parent.removeChild(myDiv);
console.log(showMain);
});
<!DOCTYPE html>
<html lang="en">
<header>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta http-equiv="X-UA-Compatible" content="ie=edge" />
<script defer src="script.js"></script>
<title>Simple Work</title>
<button id="btn-close">go back</button>
</header>
<body>
<main class="container">
<div class="main-text" id="myId"></div>
<p class="search-container">
<label>Type In : </label>
<input type="text" id="myText" value="Type in" />
</p>
<button class="btn-search">input</button>
</main>
</body>
</html>
So, I was trying to make code that add the text using insertAdjacentHTML
and next when I click "go back" button, it will erase the html that I had added using insertAdjacentHTML.
I have success up to this point. After this when I try to add new HTML using insertAdjacentHTML, it doesn't work. What I must do to fix this?
(as my English is second language, explanation might not be clear, I am just making web site that I could add text(must use insertAdjacentHTML) and erase that by using "go back" button and after I erase all of them, it could add new text again by using "input" button)
When you remove the node, you are removing the element that mainText points to, therefore, you code cannot place content into a node that is no longer there. So it throws an error stating so.
You should probably only remove the element with classname of country:
document.querySelector('.country').remove();
I've been experimenting with a local sign in/log in system and I've hit a error. I was trying to make a regular expression that checks if the user's username and password contain 8 characters and 2 numbers. I really am not sure how to do that but this is all my code I've been able too put togheter.
HTML code:
<!DOCTYPE html>
<meta content="text/html;charset=utf-8" http-equiv="Content-Type">
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
<form id='form'>
<title>Sign Up #1</title>
<h3>Simple Signup system</h3>
<div>
<label>Username:</label>
<input type="text" name="text1" id = "username">
</div>
<div>
<label>Password:</label>
<input type="text" name="text2" id = "password">
<div>
<button type="button" id="subBtn">Sign Up!</button>
</form>
</body>
<script src="main.js"></script>
</html>
My JS code:
var t = 'everything good, loging in'
var f = 'something is not right, try again.'
var tf = 'not-set'
var statment = /^[a-zA-Z]*$/
window.onload = function() {
document.getElementById('subBtn').addEventListener('click', onSubmit);
}
// main
function onSubmit() {
if (document.getElementById('username').value.includes(Number)) {
tf = 'True'
} else {
tf = 'False'
}
if (document.getElementById('username').value.includes(statment)) {
tf.push('True')
} else {
tf.push('False')
}
if (tf = ['True', 'True']) {
alert('Good to go, redirecting')
} else {
alert('Username does not meet the standards for creating a account!')
}
document.forms['forms1'].submit()
}
EDIT: Was able to redo a part of the code, I'm still using regex to check for letters because I'm not sure how to do it without it.
Current error: 'first can't be a Regular Expression'.
This example prompts for barcode scan, and then places the value into "scan-input" box. This works great for ONE input/ONE button.
My issue is i want to be able to add multiple inputs/buttons, and have the scan then place the value in the corresponding input text box.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Scandit Web SDK</title>
<link rel="stylesheet" href="style.css">
<meta name='viewport' content='width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0'/>
<!-- Add the library, as explained on http://docs.scandit.com/stable/web/index.html -->
<script src="https://cdn.jsdelivr.net/npm/scandit-sdk#4.x"></script>
</head>
<body onclick="console.log('body clicked')">
<div id="scandit-barcode-picker"></div>
<div id="input-container">
<input id="scan-input" type="text" placeholder="Scan Receiver...">
<button id="scan" onclick="scan()">SCAN
</button>
</div>
<script>
function scan() {
startScanning();
}
function showScanner() {
scannerContainer.style.opacity = "1";
scannerContainer.style.zIndex = "1";
}
function hideScanner() {
scannerContainer.style.opacity = "0";
scannerContainer.style.zIndex = "-1";
}
function startScanning() {
showScanner();
if (picker) {
picker.resumeScanning();
}
}
function stopScanning() {
hideScanner();
if (picker) {
picker.pauseScanning();
}
}
// Configure the library and activate it with a license key
const licenseKey = "LICENSE_KEY_HERE";
// Configure the engine location, as explained on http://docs.scandit.com/stable/web/index.html
const engineLocation = "https://cdn.jsdelivr.net/npm/scandit-sdk#4.x/build"
ScanditSDK.configure(licenseKey, { engineLocation: engineLocation });
const scannerContainer = document.getElementById("scandit-barcode-picker");
scannerContainer.style.opacity = "0";
scannerContainer.style.zIndex = "-1";
const scanInput = document.getElementById("scan-input");
let picker;
// Create & start the picker
ScanditSDK.BarcodePicker.create(scannerContainer)
.then(barcodePicker => {
picker = barcodePicker;
// Create the settings object to be applied to the scanner
const scanSettings = new ScanditSDK.ScanSettings({
enabledSymbologies: ["ean8", "ean13", "upca", "upce", "code128", "code39"]
});
picker.applyScanSettings(scanSettings);
picker.on("scan", scanResult => {
stopScanning();
scanInput.value = scanResult.barcodes[0].data;
});
picker.on("scanError", error => alert(error.message));
picker.resumeScanning();
})
.catch(alert);
</script>
</body>
<style>#scan:after {display:none;}</style>
</html>`
I want to be able to add multiple buttons/inputs. and have the corresponding button place it into the scan-input spot.
`<input id="scan-input" type="text" placeholder="Scan Receiver...">
<button id="scan" onclick="scan()">SCAN</button>
<input id="scan-input2" type="text" placeholder="Scan Receiver #2...">
<button id="scan2" onclick="scan()">SCAN</button>`
[text1] [button1] ----- scan places value into text1
[text2] [button2] ----- scan places value into text2
Here's a slightly adapted version of your HTML (using a digit in every id will help us keep things simpler):
<input type="text" id="scan-input1" />
<button type="button" id="scan1">SCAN</button>
<br />
<input type="text" id="scan-input2" />
<button type="button" id="scan2">SCAN</button>
Then, in our JavaScript, we can use the following function to send a message to scan-input1 if scan1 is pressed, scan-input2 if scan-2 is pressed, and so on:
[...document.getElementsByTagName('button')].forEach((el) => {
el.addEventListener('click', (e) => {
const num = e.currentTarget.id.match(/\d+$/)[0];
document.getElementById(`scan-input${num}`).value = "Scan Complete";
});
});
The code above:
Adds a click event listener to every button,
Gets the number from the id of whichever button is clicked,
Uses that number to target the correct input.
The advantage of the solution above is that it scales automatically. As long as you follow the same naming convention for each id (scan3, scan-input3, etc.), every a new button and input will have identical behaviour.
Edit: Your Code
Below, I've inserted my suggestion into your code - only changing the bare minimum:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Scandit Web SDK</title>
<link rel="stylesheet" href="style.css">
<meta name='viewport' content='width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0' />
<!-- Add the library, as explained on http://docs.scandit.com/stable/web/index.html -->
<script src="https://cdn.jsdelivr.net/npm/scandit-sdk#4.x"></script>
</head>
<body onclick="console.log('body clicked')">
<div id="scandit-barcode-picker"></div>
<div id="input-container">
<input type="text" id="scan-input1" />
<button type="button" id="scan1" placeholder="Scan Receiver...">SCAN</button>
<br />
<input type="text" id="scan-input2" />
<button type="button" id="scan2" placeholder="Scan Receiver...">SCAN</button>
<br />
<input type="text" id="scan-input3" />
<button type="button" id="scan3" placeholder="Scan Receiver...">SCAN</button>
</button>
</div>
<script>
let scanInput;
[...document.getElementsByTagName('button')].forEach((el) => {
el.addEventListener('click', (e) => {
const num = e.currentTarget.id.match(/\d+$/)[0];
scanInput = document.getElementById(`scan-input${num}`);
scan();
});
});
function scan() {
startScanning();
}
function showScanner() {
scannerContainer.style.opacity = "1";
scannerContainer.style.zIndex = "1";
}
function hideScanner() {
scannerContainer.style.opacity = "0";
scannerContainer.style.zIndex = "-1";
}
function startScanning() {
showScanner();
if (picker) {
picker.resumeScanning();
}
}
function stopScanning() {
hideScanner();
if (picker) {
picker.pauseScanning();
}
}
// Configure the library and activate it with a license key
const licenseKey = "LICENSE_KEY_HERE";
// Configure the engine location, as explained on http://docs.scandit.com/stable/web/index.html
const engineLocation = "https://cdn.jsdelivr.net/npm/scandit-sdk#4.x/build"
ScanditSDK.configure(licenseKey, {
engineLocation: engineLocation
});
const scannerContainer = document.getElementById("scandit-barcode-picker");
scannerContainer.style.opacity = "0";
scannerContainer.style.zIndex = "-1";
let picker;
// Create & start the picker
ScanditSDK.BarcodePicker.create(scannerContainer)
.then(barcodePicker => {
picker = barcodePicker;
// Create the settings object to be applied to the scanner
const scanSettings = new ScanditSDK.ScanSettings({
enabledSymbologies: ["ean8", "ean13", "upca", "upce", "code128", "code39"]
});
picker.applyScanSettings(scanSettings);
picker.on("scan", scanResult => {
stopScanning();
scanInput.value = scanResult.barcodes[0].data;
});
picker.on("scanError", error => alert(error.message));
picker.resumeScanning();
})
.catch(alert);
</script>
</body>
<style>
#scan:after {
display: none;
}
</style>
</html>`
I am checking whether an input field is empty or not, if it is empty display a button(google search) with a message if its has some value them display another button (update record) and a message.
My Elements:
Input field
button 1 ( field is empty ====> search)
button 2 (field is not empty ====> update information)
Currently i can see the 2 buttons i created in the inspect element and it looks very bad.
I have replicated the code below, thanks!
<!DOCTYPE html>
<html lang="en">
<head>
<title>Bootstrap Example</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.0/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<style>
/* #googlesearch{display:none;}
#updateinformation{display:none;}
#emptyform{display:none;} */
</style>
</head>
<body>
<div class="container">
<div class="form-group">
<label >Company name:</label>
<input onload="checker()" onkeydown="checker()" onchange="checker()" onkeyup="checker()" onfocus="checker()" class="form-control" id="txtcompany" value="dgfsd" >
<div id="txtinformator">
<small id="emptyform">Your form is empty, we recommend </small><br/>
<button id="googlesearch" class="btn btn-xs btn-primary">Search on Google</button>
<button id="updateinformation" class="btn btn-xs btn-success">Update Information</button>
</div>
</div>
</div>
<script>
$( document ).ready(function() {
$('#googlesearch').hide();
$('#updateinformation').hide();
$('#emptyform').hide();
});
// $( document ).ready(function() {
// if($('#txtcompany').val() == ""){
// $('#googlesearch').show();
// $('#emptyform').show();
// }
// else if (!$('#txtcompany').val()){
// $('#updateinformation').show();
// }
// else {
// $('#googlesearch').hide();
// $('#emptyform').hide();
// }
// });
function checker(){
if($('#txtcompany').val().length === 0){
$('#updateinformation').hide();
$('#googlesearch').show();
$('#emptyform').show();
}
else if (!$('#txtcompany').val()){
$('#updateinformation').hide();
}
else {
$('#emptyform').text('We suggest that you update this information.');
$('#updateinformation').show();
$('#googlesearch').hide();
}
}
</script>
</body>
</html>
You can use javascript to create dynamic elements
for example
var myButton = document.createElement("<button style='background-color:yellow;' class='btn btn-default'>
MyButton</button>
");
I am writing my first site from scratch - I have a form and a function that acts when the form is submitted:
application.js
$(document).ready(function() {
$("#signupform").submit(function(e) {
var name = document.getElementById("pname").value;
var email = document.getElementById("email").value;
var userArray = [];
var user = {
name: name,
email: email
};
console.log(user.email, user.name);
e.preventDefault;
});
});
The message gets logged to the console correctly...but it is only a blip - it disappears right away. Also...any errors I was getting while writing the above code also only showed up as short blips in the console. Just barely long enough to read.
Here is my index.html file...incase it is relevant:
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>it IT</title>
<link rel="stylesheet" type="text/css" href="application.css" />
<script src="jquery.js"></script>
<script src="application.js"></script>
<!--[if lt IE 9]>
<script src="http://html5shiv.googlecode.com/svn/trunk/html5.js"></script>
<![endif]-->
</head>
<body>
<h1>it IT</h1>
<div id="signup">
<form id="signupform">
Name: <input type="text" name="pname" id="pname"><br>
Email: <input type="text" name="email" id="email"><br>
<input type="submit" value="sign up">
</form>
</div>
<div id="signin"></div>
<div id="content"></div>
</body>
</html>
preventDefault is a method, you need:
e.preventDefault();
In your question code, the form was submited so console was refreshed.
Actually e.preventDefault is not correct, you need to do this:
$(document).ready(function () {
$("#signupform").submit(function (e) {
e.preventDefault(); // Missing () for preventDefault method
var userArray = [];
var user = {
name: $('#pname').val(), // also, you can get the values here only
email: $('#email').val() // no need to use extra variables for it
};
console.log(user.email, user.name);
});
});
In your browser console go to settings (on the top-right corner) and check the preserve log option. That should prevent the page from reloading.