How do I manually test JavaScript? - javascript

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>

Related

Why is my button not activating my validation function

I have an html page that access an external javascript file to validate the users input. My button doesnt seem to be doing anything and I dont understand why.
<html lang = "en">
<head>
<title>random</title>
</head>
<body>
<form>
<p>Please enter course information</p>
<input type="text" name="userInput" id="userInput" maxlength="15">
<input type="button" value="validate" onclick="validationFunction()">
<p id = "validationResults"></p>
</body>
</html>
//My external JS file that is supposed to validate the pattern WEB.110#4101_sp-2017
function validationFunction(input) {
var myRegularExpression = /([a-z]{3})(\W\d{3})(\W\d{4})(\W[a-z]{2})(\W\d{4})/gi;
return (myRegularExpression.test(input));
}
if (validationFunction(userInput)){
text = "valid";
} else {
text = "invalid";
}
document.getElementById("validationResults").innerHTML = text;
The below code works for what you want to achieve. Issues I noticed with your code:
Your form element had no closing tag
Rather than adding an onclick to a button within a form, you are better submitting the whole form, and grabbing the event object from an onsubmit event
You need to preventDefault on the event which stops the page refreshing
Your maxLength was set to 15 but your target expression is 20 characters
Your RegEx works, but could be cleaner
<!DOCTYPE html>
<html>
<head>
<title>random</title>
<script src="./script.js" defer></script>
</head>
<body>
<form id="form">
<p>Please enter course information</p>
<input type="text" name="userInput" id="userInput" maxlength="20"/>
<input type="submit"></input>
</form>
<p id="validationResults"></p>
</body>
</html>
const form = document.getElementById("form");
const paragraph = document.getElementById("validationResults");
form.addEventListener('submit', validationFunction);
function validationFunction(event) {
event.preventDefault();
const userInput = event.target.querySelector("#userInput").value;
const regEx = /([a-z]{3}(.\d{3})(#\d{4})(_[a-z]{2})(-\d{4}))/gi;
const isValid = regEx.test(userInput);
if (isValid) {
paragraph.innerHTML = "Valid";
} else {
paragraph.innerHTML = "Invalid";
}
};

how to change the action of submit button after submission

I want to change the submit button to call signout function after the user signed in
<html>
<head>
/* Here I have the links for jQuery and bootstrap so, they are working properly
</head>
<body>
<form onsubmit="signIn(event)">
<input type="text" id="username" />
<input type="password" id="password" />
<input type="submit" id="connect_disconnect">
</form>
</body>
<script type="text/javascript">
function signIn() {
code ....
// Below I just change the caption of the submit button from 'Connect' to
// 'Disconnect'
$("#connect_disconnect").text('Disconnect');
}
</script>
<script type="text/javascript">
function signOut() {
code...
}
</script>
</html>
with the above code, when I click on submit button, it will call the signIn function even when I am already signed in. I want it to call signOut function when I am already signed it. any ideas?
Thanks in advance and please let me know if my question is not clear.
If you apply a "submit" event handler to your form, then run event.preventDefault() you can prevent the form from submitting the native way and you can run any Javascript you want.
Below I've added a code example showing what you could do to capture the event.
I try not to add too much philosophy into my answers, but I've decided to include an example of a linked Javascript file.
HTML
<body>
<form id="theForm">
<input type="text" id="username" />
<input type="password" id="password" />
<input type="submit" id="connect_disconnect">
</form>
<script type="text/javascript" src="/script.js"></script>
</body>
Javascript (script.js)
(function() { // Create closure to avoid global-scoped variables
var theForm = document.getElementById('theForm'); // Select the <form> element
theForm.addEventListener('submit', handleFormSubmission); // Bind event listener.
function handleFormSubmission(event) {
event.preventDefault(); // Keep the form from taking any further native action
if( /* user is signed in */ )
signOut();
else
signIn();
}
function signIn() {
// Sign In Code
}
function signOut() {
// Sign Out Code
}
})(); // End closure

preventDefault and JSONP

We have a form that should post data to an external domain. We are aware of the cross-domain limitations, therefore we want to use JSONP.
All parts are working fine, except for the part that should prevent a default form submission that reloads the page. Below is the form.
The html page:
<html lang="en">
<head>
<meta charset="utf-8">
<title>test</title>
<script src="https://code.jquery.com/jquery-1.10.2.js"></script>
<script src="https://gateway.wildfx.com/test.js"></script>
</head>
<body>
<form method="POST" id="wild">
<fieldset>
<label for="email">Your email:</label>
<input type="text" name="email" id="wild">
<p class="wild_err">invalid</p>
<p>
<input type="hidden" id="wild_v" name="v" value="test2">
<input type="hidden" id="wild_l" name="l" value="">
<input type="hidden" id="wild_i" name="i" value="identifier">
<input type="hidden" id="wild_s" name="s" value="10612">
<input type="submit" id="wild_button" value="Check">
</p>
</fieldset>
</form>
</body>
</html>
Below is the Javascript. However, if the wild form is submitted, the page reloads instead of transfering the data with JSONp. In addition even the submission2 log isn't logged.
If tried to replace the .submit() with .click for the from button with correct ID but it isn't working either. What is wrong with the script?
function isValidEmailAddress(emailAddress) {
var pattern = new RegExp(/^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))#((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?$/i);
return pattern.test(emailAddress);
};
console.log('submission1');
$("#wild").submit(function(e) {
console.log('submission2');
e.preventDefault();
if (isValidEmailAddress(e["e"])) {
var e = {};
e["e"] = $("#wild_email").val();
e["v"] = $("#wild_v").val();
e["i"] = $("#wild_i").val();
e["s"] = $("#wild_s").val();
e["l"] = $("#wild_l").val();
(function() {
var wildAPI = "https://gateway.wildfx.com/testjsonp.php?jsoncallback=?";
$.getJSON( wildAPI, {
tagmode: e,
format: "json"
})
.done(function( data ) {
$(".wild_message_container").text('Success. you are in');
setTimeout(function() {
$("#wildnotifier-container").hide();
$("#wildnotifier-overlay").hide();
}, 5000);
});
})();
} else {
$(".wild_error").show();
$("#wild_email").addClass("wild_input_error");
}
});
You load jQuery
You load your script
Your script tries to add an event handler to the form
You add the form to your page
Step 3 fails because the form doesn't exist. Move the script so it is after the form. (Or put it in a function and call it with the DOM is ready).

Need to validate form before sending

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.

div tag not being updated

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

Categories

Resources