Why is my button not activating my validation function - javascript

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";
}
};

Related

Javascript (not found) error on form submit [duplicate]

I am trying to copy the value of the textbox to the textarea However the value gets copied using the javascript function but it disappears from the textarea after a second. What am i doing wrong?Why does it get disappear after being copied?
this is the html:
<html>
<head>
<title>
</title>
<script src="scripts/script.js" type="text/javascript"></script>
</head>
<body>
<form>
<label>Key/Value Pair: </label><input type="text" name="inputText" id="t1"></br></br>
<label>Key/Value List: </label><br>
<textarea name="outputText" rows="10" cols="50" id="t2" ></textarea><br><br>
<input type="submit" value="Add" onClick="fn_copy()" />
</form>
</body>
and this is the javascript code:
function fn_copy()
{
var temp = document.getElementById("t1").value;
if(temp != "")
{
document.getElementById("t2").value = temp;
}
else
alert("Text is Empty");
}
Thank you.
Change your button type to button instead of submit. Otherwise your page will be refreshed (default behavior with submit) and hence the content of your textarea reset.
<input type="button" value="Add" onClick="fn_copy()" />
Your problem is that you are using input of type submit, when you click it, the fuction fn_copy execute, but also do a post request, and that is why the value disappears.
Change the input for a button like that and it will work
function fn_copy()
{
var temp = document.getElementById("t1").value;
if(temp != "")
{
document.getElementById("t2").value = temp;
}
else
alert("Text is Empty");
}
<form>
<label>Key/Value Pair: </label><input type="text" name="inputText" id="t1"><br><br>
<label>Key/Value List: </label><br>
<textarea name="outputText" rows="10" cols="50" id="t2" ></textarea><br><br>
<button type="button" onclick="fn_copy()">Add</button>
</form>
You can sse a working sample here: https://jsfiddle.net/8e5e4wuz/
http://www.w3schools.com/jsref/event_preventdefault.asp
Use preventdefault to stop it from submitting.
Try this. Add any id to the button, for example btn, and do this:
function fn_copy()
{
var temp = document.getElementById("t1").value;
if(temp != "")
{
document.getElementById("t2").value = temp;
}
else
alert("Text is Empty");
}
document.getElementById("btn").addEventListener("click", function(event){
fn_copy();
event.preventDefault();
})

The inputs are not showing up at all when I click on the button. If I remove the form an html then it works but I want it to work in form

I know this may be a dumb question to some but I am pretty new to this and trying to learn. I have been stuck on this for days and couldn't figure it out so I came here for help. Whenever I hit the button it doesn't display my input at all. I want to make it that when the user clicks the button their input will show up in an ol list.
let form = document.getElementById("todo");
let list = document.getElementById("myList");
let input = document.getElementById("add1");
let input2 = document.getElementById("add2");
let button = document.getElementById("button");
let id = 1;
button.addEventListener("click", addToDo)
list.addEventListener("click", removeEvent)
function addToDo (e) {
let text = input.value;
let textAdd = input2.value;
let item = `<li class="del">
${text} ============= ${textAdd} <button class="del">Delete</button>`
list.insertAdjacentHTML("beforeend",item);
id++;
document.getElementById("add1").value = "";
document.getElementById("add2").value = "";
}
function removeEvent(e) {
if(e.target.classList.contains("del")) {
list.removeChild(e.target.parentElement);
list.removeChild(list);
}
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<h1 id="name">Todo List</h1>
<link href="project.css" rel="stylesheet"/>
</head>
<body>
<div id="todo">
<h1>Name</h1>
<input type="text" id="add1" placeholder="Title">
<br>
<h1>Add Reminder</h1>
<input type="text" id="add2" placeholder="Notes">
<button id="button">Submit</button>
</div>
<ol id="myList">
</ol>
<script src="pro.js"></script>
</body>
</html>
There is something "special" about buttons within a form.
If your HTML looks like:
<form>
<input placeholder="enter some text">
<button>Click me</button>
</form>
Your button will submit the form and therefore reset it.
I guess you would expect the form to have some crucial properties to do so, namely 'action' and 'method' (to send the data in your inputs to some remote address - because that's the main concern of forms).
If you want your button to just be a button, use the following:
<form>
<input placeholder="enter some text">
<button type="button">Click me</button>
</form>
And you'll see: nothing happens.
I've created a StackBlitz here for you (just look at the HTML file). With type="button", more and more inputs are added to the form. If you omit this, you can see the input is added, and immediately after it, the form resets itself (sending a GET request to '/' and refreshing everything - but that's something for another question).

Javascript addEventListener leads to incorrect result

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!

How do I manually test 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>

Second exists condition does not work

I'm having a question about javascript where I have two conditions to check if the input fields exists. But it only shows me that "opleiding exists" and not that "opleiding exists" and "domein exists".
please tell me what's wrong with my code.
Thanks very much !
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Untitled Document</title>
<script type="text/javascript">
function submit()
{
var opleiding = document.getElementById("opleiding");
var domein = document.getElementById("domein");
if(document.getElementById("opleiding")){
document.write("opleiding exists");
}
if (document.getElementById("domein")){
document.write("domein exists");
}
}
</script>
</head>
<body>
<input type="hidden" id="domein" value="domein" />
<input type="hidden" id="opleiding" value="opleiding" />
<div id="button" onclick="submit()">
<strong>button text</strong>
</div>
</body>
</html>
document.write will override the existing content in the page. That's the reason why you're seeing only on message.
You must use document.body.appendChild instead to show both error messages.
function submit()
{
var opleiding = document.getElementById("opleiding");
var domein = document.getElementById("domein");
var textElement;
if(document.getElementById("opleiding")){
textElement = document.createElement("p");
textElement.textContent = "opleiding exists";
document.querySelector("#results").appendChild(textElement);
}
if (document.getElementById("domein")){
textElement = document.createElement("p");
textElement.textContent = "domein exists";
document.querySelector("#results").appendChild(textElement);
}
}
<body>
<input type="hidden" id="domein" value="domein" />
<input type="hidden" id="opleiding" value="opleiding" />
<div id="results"></div>
<div id="button" onclick="submit()">
<strong>button text</strong>
</div>
</body>
You should avoid using document.write, since that it's a deprecated method. When you use it the first time, it will write down what you want, but remove all the content of the page, as per its definition.
To do what you want you should "write" using either document.body.appendChild to append some element (like a <div>) containing text, or add some text to the document.body.innerHTML, here's an example:
function submit() {
var opleiding_div = document.createElement('div'),
domein_div = document.createElement('div');
opleiding_div.textContent = "opleiding exists";
domein_div.textContent = "domein exists";
if(document.getElementById("opleiding")){
document.body.appendChild(opleiding_div);
}
if (document.getElementById("domein")){
document.body.appendChild(domein_div);
}
}

Categories

Resources