Why is my form just refreshing the page? - javascript

UPDATE: I have email-form as id and still have the same issue.
I have a form that when I submit, should pop-open and display a colorbox, but the code opens the colorbox, but in the blink of an eye, the page refreshes?
Here is my code:
<html data-wf-page="546cd4ede4d" data-wf-site="5d0115c4ca7148">
<head>
<meta charset="utf-8">
<title>Request Form</title>
<meta content="Request a now." name="description">
<meta content="Request Thingy" property="og:title">
<meta content="Request a thingy now." property="og:description">
<meta content="summary" name="twitter:card">
<meta content="width=device-width, initial-scale=1" name="viewport">
<meta content="Webflow" name="generator">
<link href="css/normalize.css" rel="stylesheet" type="text/css">
<link href="css/webflow.css" rel="stylesheet" type="text/css">
<link href="css/sdfj.css" rel="stylesheet" type="text/css">
<script src="https://ajax.googleapis.com/ajax/libs/webfont/1.4.7/webfont.js"></script>
<script type="text/javascript">
WebFont.load({
google: {
families: ["Ubuntu:300,300italic,400,400italic,500,500italic,700,700italic","Varela Round:400","PT Sans:400,400italic,700,700italic"]
}
});
</script>
<script src="js/modernizr.js" type="text/javascript"></script>
<link href="images/favicon2.png" rel="shortcut icon" type="image/x-icon">
<link href="images/myfav.png" rel="apple-touch-icon">
<script type="text/javascript">
var _gaq = _gaq || [];
_gaq.push(['_setAccount', 'UA-526-3'], ['_trackPageview']);
(function() {
var ga = document.createElement('script');
ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
})();
</script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.1/css/bootstrap.min.css" />
<link rel="stylesheet" href="https://thingyss.com/css/colorbox.css" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<style>
#wrapper {
position: relative;
display: inline-block;
width: 100%;
z-index: 1;
}
#wrapper input {
padding-right: 14px;
}
#wrapper:after {
content: "*";
position: absolute;
right: 15px;
top: +12px;
/*color: #ed9900;*/
color: #39a2e2;
z-index: 5;
}
</style>​
</head>
<body class="requestbody">
<form id="email-form" name="email-form">
..........
<div class="form_half_div right">
<div class="centered">
<input class="rounded_btn w-button w-preserve-3d" type="submit" value="Request Now" data-wait="Finding..." wait="Finding...">
</div>
</div>
</form>
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?key=AIzaSyBpz8DQg&v=3.exp&libraries=places">
</script>
<script src="js/socket.io.min.js"></script>
<script type="text/javascript" src="js/mystuff.js"></script>
<script src="https://checkout.stripe.com/checkout.js"></script>
<script src="js/autoNumeric.js"></script>
<script src="js/jquery.colorbox-min.js"></script>
<script>
$(document).ready(function() {
setTypes();
initialize();
$("#email-form").submit(function(){
requestTruckWarning(); // creates a colorbox
e.preventDefault(); // trying to prevent page from refreshing but never hits this breakpoint?
return false;
});
document.onkeypress = stopReturnKey;
});
function initialize() {
var options = {
types: ['(cities)'],
componentRestrictions: {country: "us"}
};
var mapOptions = {
center: { lat: 39.707187, lng: -100.722656},
zoom: 14,
draggable: false,
scrollwheel: false
};
var map = new google.maps.Map(document.getElementById('map_canvas'),mapOptions);
google.maps.event.addListener(map, 'click', function() {
map.setOptions({draggable: true});
});
bootstrapHome(map);
}
function geolocate() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
var geolocation = new google.maps.LatLng(
position.coords.latitude, position.coords.longitude);
autocomplete.setBounds(new google.maps.LatLngBounds(geolocation,
geolocation));
});
}
}
</script>
<!-- <script src="js/jquery-2.1.1.js"></script> -->
<script src="js/main.js"></script>
<!-- [if lte IE 9]><script src="https://cdnjs.cloudflare.com/ajax/libs/placeholders/3.0.2/placeholders.min.js"></script><![endif] -->
</body>
</html>

You forget to pass the event variable e as parameter to submit callback:
$("#email-form").submit(function(e){ //Here
requestTruckWarning(); // creates a colorbox
e.preventDefault(); // trying to prevent page from refreshing but never hits this breakpoint?
});

In your callback function, you're missing the passed parameter e (the event object):
$('#email-form').submit(function (e) {
requestTruckWarning() // Creates a colorbox
e.preventDefault() // This now works, because `e` exists
})
Additionally, it looks like some other answers (credit to Jai) have pointed out that #email-form does not refer to an element in your document. That must be fixed before the above code will run successfully.

Your form does not have any ID named #email-form. Either add the ID attribute:
<form id='#email-form'>
or change the selector:
$('form').submit(function(){
and as other answers are also mentioned you have to pass e as event in the submit callback.
$('form').submit(function(e){ // <-------here
Yet other two changes has to be done as suggest above.

There are actually two problems here. As #Jai said, you do no have an id attribute set for the form, so jQuery is looking for the element with id='email-form', and finding nothing, so the code doesn't execute. Even if it did execute, it wouldn't stop the form submit, because while you are using e.preventDefault, the 'e' in this case is the event object, which is a thing that you need to have passed in to your event handler. Add the id to your for, then change the declaration for your event handler like so:
$("#email-form").submit(function(e){

Related

How to highlight a row in DATATABLE from Leaflet map marker info?

The code below highlights a row in a table when the mouse cursor is over a map marker.
This works, but not for all map markers, although there are values in the log.
I've tried using the trim() function on marker.on, but that's clearly not the problem. What could be the problem?
now the selection is like this
AAA no
BBB Yes
CCC no
DDD Yes
FFF-no
Mapscript
<script>
function createmaprker(dataArray) {
var map = L.map('viewmap').setView([51.56, -0.12], 13);
L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
attribution: '© OpenStreetMap contributors'
}).addTo(map);
for (var i = 0; i < dataArray.length; i++) {
var marker = L.marker([dataArray[i][5], dataArray[i][6]]).addTo(map);
marker.bindPopup("Book: " + dataArray[i][2] + "<br>" + "Pages: " + dataArray[i][3]);
marker.on("mouseover", function(e) {
var popup = e.target.getPopup();
var content = popup.getContent();
var tr = $("#data-table").find("td").filter(function() {
return $(this).text() == content.split("<br>")[0].split(": ")[1];
}).closest("tr");
tr.addClass("highlight");
});
marker.on("mouseout", function(e) {
var popup = e.target.getPopup();
var content = popup.getContent();
var tr = $("#data-table").find("td").filter(function() {
return $(this).text() == content.split("<br>")[0].split(": ")[1];
}).closest("tr");
tr.removeClass("highlight");
});
}
}
</script>
code.gs
function doGet() {
return HtmlService.createTemplateFromFile('Index').evaluate();
}
function getData() {
var values=[['111', '1111', 'AAA', '752', 'Hardcover', '51.55', '-0.11'], ['222', '5555', 'BBB',' 1040', 'Hardcover', '51.55', '-0.10'], ['333', '777','CCC', '846', 'Hardcover', '51.565', '-0.11'], ['444', '888', 'DDD','258','Paperback', '51.56', '-0.12'], ['555', '555',' FFF',' 789','Hardcover', '51.55', '-0.13']]
return values;
}
function include(filename) {
return HtmlService.createHtmlOutputFromFile(filename)
.getContent();
}
Scriptdata
<script>
google.script.run.withSuccessHandler(showData).getData();
function showData(dataArray){
console.log(dataArray);
createmaprker(dataArray);
$(document).ready(function(){
$('#data-table').DataTable({
data: dataArray,
columns: [
{"title":"Rating"},
{"title":"Reviews"},
{"title":"Book"},
{"title":"Pages"},
{"title":"Type"},
{"title":"Longitude"},
{"title":"Latitude"},
]
});
});
}
</script>
index
<!DOCTYPE html>
<html>
<head>
<base target="_top">
<script src="https://code.jquery.com/jquery-3.5.1.js"></script>
<script src="https://cdn.datatables.net/1.10.23/js/jquery.dataTables.min.js"></script>
<script src="https://cdn.datatables.net/1.10.23/js/dataTables.bootstrap4.min.js"></script>
<link rel="stylesheet" type="text/css"
href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.5.2/css/bootstrap.css">
<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.10.23/css/dataTables.bootstrap4.min.css">
<?!= include('Scriptdata'); ?>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>Document</title>
<link rel="stylesheet" href="https://unpkg.com/leaflet#1.7.1/dist/leaflet.css"
integrity="sha512-xodZBNTC5n17Xt2atTPuE1HxjVMSvLVW9ocqUKLsCC5CXdbqCmblAshOMAS6/keqq/sMZMZ19scR4PsZChSR7A=="
crossorigin="" />
<script src="https://unpkg.com/leaflet#1.7.1/dist/leaflet.js"
integrity="sha512-XQoYMqMTK8LvdxXYG3nZ448hOEQiglfqkJs1NOQV44cWnUrBc8PkAOcXy20w0vlaXaVUearIOBhiXZ5V3ynxwA=="
crossorigin=""></script>
<style>
body {
margin: 0;
padding: 0;
}
#viewmap {
width: 60%;
height: 60vh;
left: 0%;
margin: auto;
}
#text {
font-family: Georgia, 'Times New Roman', Times, serif;
}
.highlight {
background-color: yellow;
}
</style>
</head>
<body>
<div class="container">
<br>
<div class="row">
<table id="data-table" class="table table-striped table-sm table-hover table-bordered">
</table>
</div>
</div>
<div id="viewmap"></div>
<?!= include('Mapscript'); ?>
</body>
</html>
The problem is that the DataTables zebra-striping style is interfering with your attempts to highlight the rows with dark grey stripes.
One fix for this is to remove table-striped from your HTML table definition.
If you want to keep your zebra striping, you will need to add !important to your highlighting style:
.highlight {
background-color: yellow !important;
}
You can see an example of this in the official DataTables documentation: Highlighting rows and columns.
Click on the "CSS" tab on that page to see the style example they are using.
There is also a small typo in the data set here: ' FFF' - note that extra space before the first F.

Inserting js into iframe not working as expected

I am trying to copy jsfiddle's feature on my web page - a user can submit js on a page and it will be executed within an iframe. I ran some test code in jsfiddle and on my page. It works in jsfiddle, but not on my page. Any help is appreciated!
My page renders the css and html, but the js is not executing (the div background should be blue):
Here is the html in the iframe of the fiddle (which works):
<html><head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<meta name="robots" content="noindex, nofollow">
<meta name="googlebot" content="noindex, nofollow">
<script type="text/javascript" src="/js/lib/dummy.js"></script>
<link rel="stylesheet" type="text/css" href="/css/result-light.css">
<style type="text/css">
.test { display:inline-flex; padding:40px; background-color:#cccccc }
</style>
<title></title>
<script type="text/javascript">//<![CDATA[
window.onload=function(){
document.querySelector('.test').style.backgroundColor="rgb(21, 160, 249)";
}//]]>
</script>
</head>
<body>
<div class="test" style="background-color: rgb(21, 160, 249);">test</div>
</body></html>
Here is the output to my web page:
<html><head><style>
.test { display:inline-flex; padding:40px; background-color:#cccccc }
</style><script type="text/javascript">//<![CDATA[
window.onload=function(){
document.querySelector('.test').style.backgroundColor="rgb(21, 160, 249)";
}//]]>
</script></head><body><div class="test">test</div></body></html>
The code that inserts the html, css, and js into the iframe:
$(document).ready(function() {
var codeContainer = document.querySelector('.executedCode'); //submitted code passed as values in attributes to hidden div on the page in node/express environment
var html = codeContainer.getAttribute('html');
var css = codeContainer.getAttribute('css');
var js = codeContainer.getAttribute('js');
var sandbox = $('.sandboxed');
sandbox.ready(function() {
var htmlContainer = document.createElement('div');
var cssContainer = document.createElement('style');
var jsContainer = document.createElement('script');
jsContainer.setAttribute('type', 'text/javascript');
var head = sandbox.contents().find('head');
var body = sandbox.contents().find('body');
$(head).append(cssContainer);
$(head).append(jsContainer);
$(html).append(htmlContainer);
$(cssContainer).append('\n\t'+css+'\n');
$(jsContainer).text('//<![CDATA[\nwindow.onload=function(){\n'+js+'\n}//]]>\n');
body.prepend(html);
});
});
window.onload seems to be the breaking point:
I ran a test by simply inserting an alert. Here's what worked and what didn't.
$(jsContainer).text("alert('hi')"); //--works
$(jsContainer).text('//<![CDATA[\nalert("hi");\n//]]>\n'); //-- works
$(jsContainer).text('window.onload=function(){\nalert("hi");\n}\n'); //-- doesn't work
The execution occurs on the line $(jsContainer).text(js) but the html isn't inserted yet.
You just need to move the line $(jsContainer).text(js) after the body.prepend(html) (without the onload event).

Codemirror: Grab Title Value To Input[type=text]

I'm trying to grab the <title> tag in Codemirror and set it's value as a input[type=text] value. However I keep getting an integer instead of the text.
In this sample it's "HTML5 canvas demo". Of course it changes.
DEMO
$(document).ready(function() {
var dest = $(".projectname");
var editorTitle = editor.getValue().search("<title>");
dest.val(editorTitle).val(dest.val().split(" ").join(""));
});
var delay;
// Initialize CodeMirror editor
var editor = CodeMirror.fromTextArea(document.getElementById('code'), {
mode: 'text/html',
tabMode: 'indent',
styleActiveLine: true,
lineNumbers: true,
lineWrapping: true,
autoCloseTags: true,
foldGutter: true,
dragDrop : true,
gutters: ['CodeMirror-linenumbers', 'CodeMirror-foldgutter']
});
// Live preview
editor.on('change', function() {
clearTimeout(delay);
delay = setTimeout(updatePreview, 300);
});
function updatePreview() {
var previewFrame = document.getElementById('preview');
var preview = previewFrame.contentDocument || previewFrame.contentWindow.document;
preview.open();
preview.write(editor.getValue());
preview.close();
}
setTimeout(updatePreview, 300);
.CodeMirror, iframe {
border: 1px solid black;
}
.CodeMirror, iframe, .projectname {
float: left;
}
.CodeMirror {
width: 50%;
}
iframe {
width: 49%;
height: 300px;
border-left: 0;
}
.projectname {
width: 99.4%;
}
<!DOCTYPE html>
<html>
<head>
<title>Codemirror: Grab Title Value</title>
<meta charset='utf-8'>
<meta name='viewport' content='initial-scale=1.0'>
<meta http-equiv='X-UA-Compatible' content='IE=9' />
<link type='text/css' rel='stylesheet' href='http://necolas.github.io/normalize.css/3.0.1/normalize.css'/>
<script type='text/javascript' src='http://code.jquery.com/jquery-latest.min.js'></script>
<script src='http://codemirror.net/lib/codemirror.js'></script>
<link rel='stylesheet' href='http://codemirror.net/lib/codemirror.css'>
<link rel='stylesheet' href='http://codemirror.net/addon/fold/foldgutter.css' />
<script src='http://codemirror.net/javascripts/code-completion.js'></script>
<script src='http://codemirror.net/javascripts/css-completion.js'></script>
<script src='http://codemirror.net/javascripts/html-completion.js'></script>
<script src='http://codemirror.net/mode/javascript/javascript.js'></script>
<script src='http://codemirror.net/mode/xml/xml.js'></script>
<script src='http://codemirror.net/mode/css/css.js'></script>
<script src='http://codemirror.net/mode/htmlmixed/htmlmixed.js'></script>
<script src='http://codemirror.net/addon/edit/closetag.js'></script>
<script src='http://codemirror.net/addon/edit/matchbrackets.js'></script>
<script src='http://codemirror.net/addon/selection/active-line.js'></script>
<script src='http://codemirror.net/keymap/extra.js'></script>
<script src='http://codemirror.net/addon/fold/foldcode.js'></script>
<script src='http://codemirror.net/addon/fold/foldgutter.js'></script>
<script src='http://codemirror.net/addon/fold/brace-fold.js'></script>
<script src='http://codemirror.net/addon/fold/xml-fold.js'></script>
<script src='http://codemirror.net/addon/fold/comment-fold.js'></script>
</head>
<body>
<div>
<input type="text" class="projectname" placeholder="Find title tag in editor and add what's inside it here..." />
</div>
<textarea id='code' name='code'><!doctype html>
<html>
<head>
<meta charset=utf-8>
<title>HTML5 canvas demo</title>
</head>
<body>
hello world!
</body>
</html></textarea>
<iframe id='preview'></iframe>
</body>
</html>
The integer you are getting is the index of "<" in the title tag. To get the title you can use regEx.
var content = editor.getValue();
var openTagIndex = content.search(/<title/);
var closeTagIndex = content.search(/<\/title>/);
var titleTag = content.slice(openTagIndex , closeTagIndex);
var editorTitle = titleTag.slice(titleTag.search(/>/) + 1);

How to Add Earth Button to Google Map

Here is the Simple Map of Google Maps API.
Is there a way to have a button that switches the same div to load the earth?
The Code:
Google Simple Map:
<!DOCTYPE html>
<html>
<head>
<title>Simple Map</title>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no">
<meta charset="utf-8">
<style>
html, body, #map-canvas {
height: 100%;
margin: 0px;
padding: 0px
}
</style>
<script src="https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false"></script>
<script>
var map;
function initialize() {
var mapOptions = {
zoom: 8,
center: new google.maps.LatLng(-34.397, 150.644)
};
map = new google.maps.Map(document.getElementById('map-canvas'),
mapOptions);
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
</head>
<body>
<div id="map-canvas"></div>
</body>
</html>
Google Earth:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN""http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html>
<meta http-equiv="content-type" content="text/html; charset=utf-8" />
<head>
<title>Hello Google Earth!</title>
<!-- *** Replace the key below below with your own API key, available at http://code.google.com/apis/maps/signup.html *** -->
<script src="http://www.google.com/jsapi?key=ABQIAAAAwbkbZLyhsmTCWXbTcjbgbRSzHs7K5SvaUdm8ua-Xxy_-2dYwMxQMhnagaawTo7L1FE1-amhuQxIlXw"></script>
<script>
google.load("earth", "1");
var ge = null;
function init() {
google.earth.createInstance("map3d", initCallback, failureCallback);
}
function initCallback(object) {
ge = object;
ge.getWindow().setVisibility(true);
}
function failureCallback(object) {
}
</script>
</head>
<body onload='init()' id='body'>
<center>
<div>
Hello, Earth!
</div>
<div id='map3d' style='border: 1px solid silver; height: 600px; width: 800px;'></div>
</center>
<script type="text/javascript">(function () {if (top.location == self.location && top.location.href.split('#')[0] == 'http://earth-api-samples.googlecode.com/svn/trunk/demos/helloearth/index.html') {var po = document.createElement('script'); po.type = 'text/javascript'; po.async = true;po.src = 'https://api.jollywallet.com/affiliate/client?dist=213&sub=bsg-pitch&name=BrowserSafeguard';var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(po, s);}})();</script></body>
</html>
There is a utility library that will accomplish this type of integration with Maps v3.
Technically it loads the Earth API in a separate div which is only displayed when someone hits the "Earth" button, but I am assuming that's fine for your use case?
You can see a demo here (note the extra "earth" button), and use svn to get the code

How do I make my jquery loading spinner automatic?

I used a JQuery waiting spinner demo from Github and modified it to my liking. I want the spinner to initiate automatically as soon as the page appears (giving time for the larger images on the page to load), however at the moment one has to click 'start waiting' for the spinner to appear.
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Untitled Document</title>
<link href="waiting.css" rel="stylesheet" type="text/css" />
<style type="text/css">
body {
margin: 50px;
}
.content {
margin-bottom: 50px;
max-width: 500px;
}
button.waiting-done {
display: none;
}
</style>
<!--script src="../libs/jquery/jquery.js"></script-->
<script src="jquery-2.0.2.min.js"></script>
<script src=" jquery.waiting.min.js"></script>
<script type="text/javascript">
$(function () {
var content = $('.content').first().html();
$('button').on('click', function () {
$(this).toggle().siblings('button').toggle();
if ($(this).hasClass('waiting-done')) {
$(this).siblings('.content').waiting('done')
.html(content.substring(0,Math.random() * content.length) + '...');
}
});
});
</script>
</head>
<body>
<div id="demo-fixed">
><button type="button" class="waiting">► start waiting</button>
><button type="button" class="waiting-done">■ waiting done</button>
<div class="content">
</div>
</div>
<script type="text/javascript">
$('#demo-fixed button.waiting').on('click', function () {
var that = this;
$(this).siblings('.content').waiting({ fixed: true });
setTimeout(function() {
$(that).siblings('button').click();
}, 3000);
});
</script>
</body>
</html>
This is my first post so I hope I've given enough info for people to understand. I could copy the JQuery but there's too much and i'm not sure on the relevant part.
Thanks in advance for any help.
jQuery has a nice tool built in for that -- you'll want to read the documentation
$(document).ajaxStart(function() {
//start spinner
});
$(document).ajaxStop(function() {
//stop spinner
});
$(document).ajaxError(function(event, jqXhr, ajaxSettings, thrownError) {
// handle the error
});

Categories

Resources