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.
Related
Good Afternoon,
I want to set a localStorage to another domain. I used the postMessage function.
Here is the parent page :
<!DOCTYPE html>
<html>
<head>
<title></title>
<meta charset="utf-8" />
<script>
var childwin;
const childname = "popup";
function openChild() {
childwin = window.open('Page2.html', childname, 'height=300px, width=500px');
}
function sendMessage(){
let msg={pName : "Bob", pAge: "35"};
// In production, DO NOT use '*', use toe target domain
childwin.postMessage(msg,'*')// childwin is the targetWindow
childwin.focus();
}
</script>
</head>
<body>
<form>
<fieldset>
<input type='button' id='btnopen' value='Open child' onclick='openChild();' />
<input type='button' id='btnSendMsg' value='Send Message' onclick='sendMessage();' />
</fieldset>
</form>
</body>
</html>
Here the children :
<html>
<head>
<title></title>
<meta charset="utf-8" />
<script>
// Allow window to listen for a postMessage
window.addEventListener("message", (event)=>{
// Normally you would check event.origin
// To verify the targetOrigin matches
// this window's domain
let txt=document.querySelector('#txtMsg');
localStorage.setItem("age", event.data.pAge);
// event.data contains the message sent
txt.value=`Name is ${event.data.pName} Age is ${event.data.pAge}` ;
});
</script>
</head>
<body>
<form>
<h1>Recipient of postMessage</h1>
<fieldset>
<input type='text' id='txtMsg' />
</fieldset>
</form>
</body>
</html>
This works fine but we need 2 buttons. One to open the page, the other to post the message.
If I want to make the two methods openChild();postMessage() in the same button, it does not work.
I think it is because the page2.html is not totally loaded when we call postMessage().
How can we do ?
Best regards.
Christophe.
you can include your script when DOM loads
document.addEventListener('DOMContentLoaded', () => {
//do some functions
})
I am new to javascript programming so am hoping that this is a simple issue... I'm wanting my webpage to allow a user to input a music track name and artist in two separate fields and once you hit 'go' the javascript will run and parse the input into a string. To test I have tried to see if these inputs are being taken and I have tried to print them to console, however nothing is being printed to the console.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Spotify</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<main class="main-container">
<div class="header">
<p>TrackSelector</p>
</div>
<section>
<div class="form">
<form action="">
<input type="textt" class="track" placeholder="Enter track..." />
<input type="texta" class="artist" placeholder="Enter artist..." />
<button type="button" class="submit-btn">GO</button>
</form>
</div>
</section>
</main>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script src="script.js"></script>
</body>
</html>
Javascript file:
const app = {};
//Allow the user to enter names
app.events = function() {
$('form').on('button', function(e){
e.preventDefault();
let tracks = $('input[type=textt]').val();
let artists = $('input[type=texta]').val();
console.log(tracks);
console.log(artists);
});
};
//
//
app.init = function(){
app.events();
};
$(app.init);
I believe I have specified to take in the correct inputs and specified the correct button reference, have played around to try out other methods but I'm still quite stuck... any ideas?
Replace
$('form').on('button', function(e){
with
$('form .submit-btn').on('click', function(e){
jQuery .on() expects event name as its first argument.
There is no input type type="textt" and texta. There are only predefined types like text, email, password, checkbox and so on... So make type "text" in both inputs and for reference use id: <input id="my_track" type="text">. Then in javascript get value by $('#my_track').val(); To handle submit use $('form').on('submit', func)
Yes, i know this is a duplicate, but all the answers i've read didn't help me, i have a side by side working example, from w3school, it works, and mine doesn't, what i am trying to do is show a tooltip warning the user to use numbers only, but instead, it just refreshes the page.
This is my full html page code:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Test</title>
<link rel="stylesheet" media="screen" href="Css/style.css"> /*---not using the bootstrap css because it messes up the form layout, so i copied every tooltip referenced block to my style.css instead.---*/
<script type="text/javascript" src="js/tooltip.js"></script>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script type="text/javascript">
var previous;
$(document).ready(function(){
$('.btn').tooltip();
});
//Buy Button JS code
$(function () {
$("#searchform").bind('submit', function () {
var str = $('#search-form').val();
if (str.match(/^[0-9]*$/)) {
$('#search-form').tooltip({title="You did good :)"});
}
else
{
$('#search-form').tooltip({title="Please enter numbers ONLY !"});
}
});
});
</script>
</head>
<body>
<div class="box">
<form class="search-form" method="post" id="searchform">
<input type="text" id="search-form" name="textbox" placeholder="Please enter your code" required/>
<button type="submit" name="submit" class="btntxt">Validate</button>
<div id="search_results"></div>
</form>
</div>
</body>
</html>
I didn't put the data-toggle:"tooltip" neither a title:"sometitlehere" in the element's options, because i don't really need it.
There are few mistakes in your code,
//it should be title: and not title=
$('#search-form').tooltip({title:"You did good :)"});
The above line initializes the tooltip once your code excutes.
After that if the tooltip title is updated, the tooltip is needed to be destroyed and re-initialized with new title.
var previous;
//Buy Button JS code
$(function () {
$("#searchform").bind('submit', function () {
var newTooltip="";
var str = $('#search-form').val();
if (str.match(/^[0-9]*$/)) {
newTooltip = "You did good :)";
}
else
{
newTooltip = 'Please enter numbers ONLY !';
}
$('#search-form').attr('title', newTooltip).tooltip('fixTitle').tooltip('setContent').tooltip('show');
setTimeout(function(){
$('#search-form').tooltip('hide').tooltip('destroy');
}, 1500);
});
});
<link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
/*---not using the bootstrap css because it messes up the form layout, so i copied every tooltip referenced block to my style.css instead.---*/
<script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
<div class="box">
<form class="search-form" method="post" id="searchform">
<input type="text" id="search-form" name="textbox" placeholder="Please enter your code" required/>
<button type="submit" name="submit" class="btntxt">Validate</button>
<div id="search_results"></div>
</form>
</div>
You are using form so you need to return true or false on validate action so your code should be like
if (str.match(/^[0-9]*$/)) {
$('#search-form').tooltip({title="You did good :)"});
return true;
}
else
{
$('#search-form').tooltip({title="Please enter numbers ONLY !"});
return false;
}
are you initialising the tooltip in the js? - tooltips won't show unless you have this in the code:
$(function(){
$("[data-toggle=tooltip]").tooltip();
})
ok - I just looked at your code - you have :
$('.btn').tooltip();
listed in theree, but your button has the class "btntxt" and you are also trying to get a tooltip on the search form - but that has the id of "search-form" - neither of which will be affected by your tooltip declaration. Best to use the one I gave in the is post so that all elements with tooltips can display them. Setting them to individual classes or ids is too restrictive if you forget that your class or id is not the same as the one listed in the js.
you have this order to your scripts:
<script type="text/javascript" src="js/tooltip.js"></script>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
Does the tooltip.js require jquery? - if so you may need to invert that order
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script type="text/javascript" src="js/tooltip.js"></script>
In this code, when you click on the submit button, it does not display the alert message. However, it works when you remove the object and property definitions.
<--!DOCTYPE html>
<html>
<head>
<title>This is just a test</title>
<script src="script.js"></script>
</head>
<body>
<h1>This is going to be the search bar</h1>
<form>
<input type="text" id="BookName" name="Book1">
<input type="submit" id="Searchbtn" onclick="algo()">
</form>
<script>
function algo(){
alert("It is working");
};
var search = document.getElementById("BookName");
var bookDirectory = {};
bookDirectory.book1 = {
bookName = "book1",
bookTag1 = "MAIT",
bookTag2 = "3rd Semester"
};
bookDirectory.book2 = {
bookName = "book2",
bookTag1 = "NIEC",
bookTag2 = "1st Semester"
};
bookDirectory.book3 = {
bookName = "book3",
bookTag1 = "USIT",
bookTag2 = "5th Semester"
};
</script>
<h2 id="Book1">This is going to be the book</h2>
</body>
</html>
Why does it work if you remove the object and property definitions?:
<!DOCTYPE html>
<html>
<head>
<title>This is just a test</title>
<script src="script.js"></script>
</head>
<body>
<h1>This is going to be the search bar</h1>
<form>
<input type="text" id="BookName" name="Book1">
<input type="submit" id="Searchbtn" onclick="algo()">
</form>
<script>
function algo(){
alert("It is working");
};
</script>
<h2 id="Book1">This is going to be the book</h2>
</body>
</html>
You are incorrectly defining your Object Literals.
Instead of using the = in your definitions:
bookDirectory.book1 = {
bookName = "book1",
bookTag1 = "MAIT",
bookTag2 = "3rd Semester"
};
You should be defining them with :, like so:
bookDirectory.book1 = {
bookName: "book1",
bookTag1: "MAIT",
bookTag2: "3rd Semester"
};
Because these are defined using an incorrect syntax, the entire <script> block and all the code within it is invalid and not available for use.
Please note that most browsers you might use for testing have a development console which you can use to check for errors, and this incorrect assignment would definitely have shown in your console. For most browsers, the default key to open the developer panel is F12.
Here is the javascript code.
<script type="text/javascript">
function myfunc()
{
var filmName = document.getElementById("mysearch-text").value;
alert(filmName);
if(filmName == "parker")
window.location.assign("http://www.google.com");
else
alert("hello");
}
</script>
If I enter any other string I get an "hello" alert and If I enter "parker" the page "http://www.google.com" wont get loaded. Why is this happening?
EDIT:
Ok as someone mentioned I did remove "http://www.google.com" and added "http://stackoverflow.com" but it did not resolve my problem. And I cant even load local html pages that are in the same directory
if(filmName == "parker")
window.location.assign("index.html"); // also "./index.html" or ./index/html
Even this is not working. What's wrong
I also have jquery libraries: that is Jquery UI and Jquery
This question needs more of info I think. Here are the final edits
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<!-- Other style and js libraries, including Jquery Ui and regular jquery -->
<script>
$(document).ready(function() {
$(".youtube").fancybox();
}); // end ready
</script>
<script>
$(document).ready(function(e) {
$('.tooltip').hide();
$('.trigger').mouseover(function() {
/* Rest of it, which is not necessary here */
</script>
<script type="text/javascript">
function myfunc()
{
var filmName = document.getElementById("mysearch-text").value;
alert(filmName); // for debugging
if(filmName == "parker")
window.location.assign("index.html");
else
alert("hello");
}
</script>
</head>
<body>
<div id='mysearch-box'>
<form id='mysearch-form'>
<input id='mysearch-text' placeholder='' type='text'/><!-- Input here guys -->
<button class = "none" id='mysearch-button' onclick = "myfunc()">Search</button>
<!-- press this button after entering "parker" -->
</form>
</div>
<!-- Rest of the HTML page -->
</body>
</html>
I assume you are using a form onsubmit event to call myfunc, if so you have to prevent the default behavior by return false; (for example)
HTML:
<form id="form">
<input type="text" id="mysearch-text">
<input type="submit" value="Submit">
</form>
JS:
<script>
window.onload = function () {
document.getElementById("form").onsubmit = function () {
var filmName = document.getElementById("mysearch-text").value;
alert(filmName);
if (filmName == "parker") window.location.href = "http://www.w3fools.com";
else alert("hello");
return false; //prevent the default behavior of the submit event
}
}
</script>
I have tested the following solution and it works perfectly:
setTimeout(function(){document.location.href = "page.html;"},500);