I have created a simple application which connects to a rest api, as follows:
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<script src="http://code.jquery.com/jquery-latest.min.js" >
</script>
<title></title>
</head>
<body>
<h1 id="header">A headline</h1>
<div id = "info"></div>
<p1 id = "p1">p1</p1>
<form id="name" name="name">
Please enter a switch: <input type="text" name="switch" id = "switch">
<input type="submit" value="submit" name="submit" id="submit">
</form>
<script>
$(document).ready(function() {
$('#name').submit(function() {
alert('submitted');
var switchName = $('#switch').val();
$.getJSON('http://localhost:8081/withindex/switch','name='+switchName, processSwitches(data));
});
});
function processSwitches(data) {
alert('processSwitches');
var infoHTML = '<p>Switch Name: ' + data.switchName +'</p>' ;
alert(infoHTML);
$('#info').html(infoHTML);
$('#header').html('<h1>Switches</h1>');
}
</script>
</body>
</html>
It runs, and will return an alert with the infoHTML string correctly, but I can't figure out why it won't update the div tag with id info.
Could anyone help?
Thanks.
You're invoking the processSwitches function inside the $.getJSON function. You should pass only the name of that function - without the (data) part:
$.getJSON('http://localhost:8081/withindex/switch','name='+switchName, processSwitches);
Simply, this:
processSwitches
instead of this:
processSwitches(data)
EDIT:
You also forgot to prevent the form from submiting. Simply add return false at the end of the submit event handler:
$('#name').submit(function() {
alert('submitted');
var switchName = $('#switch').val();
$.getJSON('http://localhost:8081/withindex/switch','name='+switchName, processSwitches);
return false;
});
It looks like you're submitting the form. Upon form submition data is lost.
Try adding
return false
after
$.getJSON(... )
In the fiddle it works http://jsfiddle.net/K3ZKA/ check your console for errors!
strings are undefined but doesen't matter
Related
I have a problem as I try to addEvenrListener to the form to validate the user input. However, there is something wrong with the code as it keeps showing "All done" even when I left blank the input or the input contains number inside. Can you guys let me know me where is the problem? Furthermore, what is the difference between onsubmit and addEventListener? Is there any way simpler to do this? I just start learning JavaScript so I just want to build my knowledge step by step starting from the bottom. Thank you so much!
var check=document.getElementById("check");
var name=document.getElementById("name");
var reg = /^[a-zA-Z]+$/;
function ipt(){
if(name.value !== ""){
if(!reg.test(name.value)){
alert("Number not allowed")
}
else{
alert("All done");
}
}
else{
alert("Please enter your name");
}
}
check.addEventListener("submit", ipt());
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Check</title>
<script src="./check.js" defer></script>
</head>
<body>
<form name="check" id="check">
<label for="name">Name</label>
<input type="text" id="name" name="name" value="">
<button type="submit">Submit</button>
</form>
</body>
</html>
This happens because you invoke the function with parenthesis () at the event listener, invoke the function without parenthesis.
Try creating your "check" and "name" variables inside the function ipt(), so immediately you submit the form, it will take the info that you previously typed in the input.
Creating your variables outside the function, the result will be undefined for the input value because js creates them as soon as the page is created and when you submit, those variables were already created at the beginning without any info.
here some official docs from MDN about submit eventListener.
https://developer.mozilla.org/en-US/docs/Web/API/HTMLFormElement/submit_event
Add your script at the bottom of the body, it gives the HTML the time to load before de Javascript code is executed.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Check</title>
</head>
<body>
<form name="check" id="check">
<label for="name">Name</label>
<input type="text" id="name" name="name" value="">
<button type="submit">Submit</button>
</form>
<script src="./check.js" defer></script>
</body>
</html>
And here your Js file, add the event as an argument to your "ipt" function.
var reg = /^[a-zA-Z]+$/;
function ipt(event) {
event.preventDefault();
var check = document.getElementById("check");
var name = document.getElementById("name");
if (name.value !== "") {
if (!reg.test(name.value)) {
alert("Number not allowed")
}
else {
alert("All done");
}
}
else {
alert("Please enter your name");
}
}
check.addEventListener('submit', ipt);
Hope it works for You. Regards!
I'm trying to learn javascript by making a simple price checking website using the Best Buy products API.
How do I "run" the javascript? My form takes in a product ID number (the SKU) and sends it to validateSKU() on submit. The function processData(data) searches for the product using the SKU.
Nothing is happening when I test the site, and any help would be great; thanks!
<!DOCTYPE html>
<html>
<head>
<title>Learn JavaScript</title>
</head>
<body>
<form id="bestBuyForm" name="bestBuyForm" onsubmit="validateSKU()">
<input id="SKU" name="SKU" required="" type="text">
<label for="SKU">SKU</label>
<input id="email" name="email" type="email">
<label for="email">Email</label>
<input class="button" id="submit" name="submit" type="submit">
</form>
<script>
function validateSKU() {
var SKU = document.forms["bestBuyForm"]["SKU"].value;
var bby = require('bestbuy')('process.env.BBY_API_KEY');
var search = bby.products('sku=' + SKU);
search.then(processData);
}
function processData(data) {
if (!data.total) {
console.log('No products found');
} else {
var product = data.products[0];
console.log('Name:', product.name);
console.log('Price:', product.salePrice);
}
}
</script>
</body>
</html>
Use web console to see what does happen and read about the console API.
Try to bind validateSKU with HTML element addEventListener method. Also you should prevent default form behaviour which cause page reloading on submit. Call event.preventDefault().
Working example code:
<html>
<form id="someForm">
...
<button type="submit">Submit</submit>
</form>
<script>
function validateSKU(event) {
console.log('IT works');
event.preventDefault();
// ...here your code
}
var form = document.getElementById('someForm');
form.addEventListener('submit', validateSKU, false);
</script>
</html>
I have some html and some javascript code that is supposed to take input in a text box, and open a new tab with the Wikipedia page of whatever was in the text box. However, I'm using this as an extension, and google chrome doesn't allow inline javascript.
page.js
document.getElementById("search").addEventListener("click", searchPage);
function searchPage() {
console.log("test")
var temp = document.getElementById(pageName);
var temp = temp.value;
var myPage = "http://en.wikipedia.org/wiki/" + temp;
window.location.replace(myPage);
}
popup.html
<!DOCTYPE html>
<html>
<body>
Random
Enter page to lookup: <input type="text" id="pageName" /><br />
<input type="submit" value="Submit" id="search" />
<script src="./page.js></script>
</body>
</html>
Anyone have any clue why this isn't working?
what you can do instead is include your JS in your HTML <head> tag, and add an onClick attribute to your button, like so:
<!DOCTYPE html>
<html>
<body>
<a href="http://en.wikipedia.org/wiki/Special:Random/" target="_blank">$
Enter page to lookup: <input type="text" id="pageName" /><br />
<input type="submit" value="Submit" id="search" />
<script src="./page.js"></script>
</body>
</html>
I think the problem was that in your original code, you had <script src="./page.js></script> instead of <script src="./page.js"></script>
then you can change your javascript to be the following:
document.getElementById('search').addEventListener('click', searchPage);
function searchPage() {
console.log("hjabdfs");
var temp = document.getElementById('pageName');
var temp = temp.value;
var myPage = "http://en.wikipedia.org/wiki/" + temp;
window.location.replace(myPage);
}
please note that I also changed var temp = document.getElementById(pageName) to var temp = document.getElementById('pageName'), as pageName is not a variable.
Input type submit is trying to submit a form. You need to add an action to that submit button or you can change it to a button and the event will fire.
Your click event listener doesn't work because it has not been loaded yet. Or in other words, you need to make sure this line <script src="./page.js></script> is correctly pointing to page.js.
I am trying to send a form to email but I wanted the name field to be validated (if no content then don't send)
I cannot get it validate and then end through the php script I have working correctly
I have created a jsfiddle at the following link
Can someone help please?
$(document).ready(function () {
$('.form-horizontal').on('submit', function (e) {
e.preventDefault();
var name = $('#name').val();
if (!name) {
showError();
}
else {
$('#contact-form').submit();
}
});
function showError() {
$('.tyler-error').show();
}
});
Working fiddle
In your fiddle, you didn't select jQuery from the library dropdown.
Secondly, you should avoid submitting the form from within the submit handler, instead just preventDefault if there is a validation error.
$('.form-horizontal').on('submit', function (e) {
var name = $('#name').val();
if (!name) {
showError();
e.preventDefault();
}
});
If you really want to keep the code as it was, you need to call the forms submit function, not the jQuery submit function:
$('#contact-form')[0].submit();
// or
$('#contact-form').get(0).submit();
Here, [0] or .get(0) is giving you the plain JavaScript DOM element with no jQuery wrapper, and with this you can call submit().
HTML5 provides input validation, you can set in order to tell the browser that your html view is HTML5.
//Set your doctype for HTML5.
<!doctype html>
<html>
<head>
<title></title>
</head>
<body>
<form id="the_form">
//here html5 will not submit if the box is empty or does not meet the email
//addres format.
<input type="email" name="email" id="email" placeholder="Enter email..">
<input type="submit" value="send">
</form>
</body>
</html>
If you dont want to use HTML5, you could also make a simple javascript code to not submit if the input is empty.
<html>
<head>
<title></title>
<script type="text/javascript">
window.onload = init();
function init(){
//get form.
var form = document.getElementById("the_form");
form.onsubmit = email_validation;
}
function email_validation(){
email = document.getElementById("email");
if(email.value == ''){
//return false to avoid submission.
return false;
}
else{
//do whatever code.
}
}
</script>
</head>
<body>
<form id="the_form">
<input type="text" name="email" id="email" placeholder="Enter email..">
<input type="submit" value="send">
</form>
</body>
</html>
with this way, your email will be validated before is sent, hope this work for you.
I am trying to confirm with the user if the following string he or she is about to enter is correct but the confirmation box won't appear. Here is that segment of the code:
<html xmlns="http://www.w3.org/1999/html" xmlns="http://www.w3.org/1999/html">
<head>
<script>
function validateForm(){
var pkey = document.forms["createProductForm"]["pagekeyTF"].value;
var agree = confirm("Is this your product?\n\n ${pkey}");
if(agree) //Do something
else //Do something else
}
</script>
</head>
<body>
<form name="createProductForm" controller="actions" action="ImplementNewProduct" onsubmit="return validateForm()" method="post">
<g:textField id="productTF" name="productTF" value="My Product" />
<button id="createProductID" name="createButton" value="Create Product">Create Product</button>
</form>
</body>
</html>
Am I not allowed to pass in string variables in the confirmation function? Because if I take off the ${pkey} it works fine but it does not include the user's input and that is not what I am not trying to achieve. Any help? Thanks!
Edit it like this :
var pkey = document.forms["createPixelForm"]["pagekeyTF"].value;
var agree = confirm("Is this your product?\n\n " + pkey);