Get Element Breaking Code - javascript

I'm trying to improve my Javascript by starting a simple web interface, but every time I try to add an event listener to an input field, it breaks my code.
Here's my HTML:
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="colors.css">
<script src="spot.js"></script>
</head>
<div id="ask">
Search for an artist to see their top songs:
</div>
<form>
<input type="text" name="artist" id="artist-search">
</form>
<div id="sub">
submit
</div>
</html>
And here's my Javascript:
window.onload = loaded;
var inField;
function loaded() {
document.getElementById("sub").addEventListener("click", search);
inField = document.getElementById("artist-search");
}
//https://api.spotify.com/v1/search?q=tania%20bowra&type=artist
function search() {
alert();
//var query = "//https://api.spotify.com/v1/search?q=";
}
When I add the getElementById to "artist-search", the alert in the search function stops working. Why is this? And is there a better way to get the text in an input field when someone clicks a submit button using vanilla Javascript?

Related

JavaScript addEventListener on submit not working

it's a total newbie question, but I'm having serious issues with my first JavaScript task. I've decided to learn JS and start with a TODO List, and I'm now stuck at the very beginning.
The event listener that should trigger when the form is submitted doesn't work. When I change the event it listens for to "click", "focus" or "blur" it works, but not with submit. Can anyone be of advise?
PS. Is there a simple explanation for event.preventDefault(); ? What does it do, and when it should be used?
Thanks a million.
My HTML:
<!DOCTYPE html>
<html lang="en">
<head>
<title>TODO</title>
</head>
<body>
<div id="headerDiv">
<h1>My To Do List</h1>
<form>
<input aria-label="Add a new task:" type="text" id="newTaskInput" placeholder="Do the laundry, write a new chapter...">
<input id="submitNewTaskButton" type="submit" value="+">
</form>
</div>
<div id="tasks">
<ul id="tasksList">
<li>Do the laundry</li>
<li>Walk the cat</li>
</ul>
</div>
</body>
<script type="text/javascript" src="script.js"></script>
</html>
My JavaScript:
let newTaskInputForm = document.getElementById('newTaskInput');
let tasksList = document.getElementById("tasksList");
let submitNewTaskButton = document.getElementById("submitNewTaskButton");
function submitNewTask() {
var newTask = newTaskInputForm.value;
var newListItem = document.createElement("li");
var newListTextNode = document.createTextNode(newTask);
newListItem.appendChild(newListTextNode);
tasksList.appendChild(newListItem);
}
newTaskInputForm.addEventListener('submit', function (event) {
event.preventDefault();
submitNewTask(event)
});
<input> elements don't raise submit events - it's the <form> that does that.
(in other words, you've attached the listener to the wrong element)
Two changes made here, the event listener add to the <form> not the input submit, also changed the <input> tag to <button> check this SO question to know the difference between them.
And for e.preventDefault(), basically its used to stop default HTML tags behavior, for example <a> tag when clicked they will redirect users to a different page or domain sometimes, also forms submit actions usually redirect the page too to a different page, e.preventDefault() will stop this behavior and let the developer decide what should happen after the form submit, or <a> anchor tag is clicked, when should it be used: this is up to the app design, so if the application you are working on require some HTML tags to behave differntly e.g <a> and <form> tags to do Ajax calls.
let newTaskInputForm = document.getElementById('newTaskInput');
let tasksList = document.getElementById("tasksList");
let submitNewTaskButton = document.getElementById("submitNewTaskButton");
function submitNewTask() {
var newTask = newTaskInputForm.value;
var newListItem = document.createElement("li");
var newListTextNode = document.createTextNode(newTask);
newListItem.appendChild(newListTextNode);
tasksList.appendChild(newListItem);
}
document.getElementById('newTaskForm').addEventListener('submit', function (event) {
event.preventDefault();
submitNewTask(event)
});
<!DOCTYPE html>
<html lang="en">
<head>
<title>TODO</title>
</head>
<body>
<div id="headerDiv">
<h1>My To Do List</h1>
<form id="newTaskForm">
<input aria-label="Add a new task:" type="text" id="newTaskInput" placeholder="Do the laundry, write a new chapter...">
<button id="submitNewTaskButton" type="submit">+ form</button>
</form>
</div>
<div id="tasks">
<ul id="tasksList">
<li>Do the laundry</li>
<li>Walk the cat</li>
</ul>
</div>
</body>
<script type="text/javascript" src="script.js"></script>
</html>
The submit event only exist on form element. Check here.
so, it is
<html>
...
<form id="form></form>
...
<script>
let form = document.getElementById('form')
form.addEventListener('submit',function(){})
</script>
</html>
The event.preventDefault() I think it is best explained here.
Welcome to Javascript.

Global replace user input text to modified output by element ID in JS

I am currently learning to use the replace method in JS. I was able to get it to work in a simple function using the console to check the output. However I am now working on making a simple user interface to interact with the function and it has caused some difficulty. I can get the function to accept and re-print the user's text, but the replace portion doesn't seem to be functioning properly as I've written it. Here is the HTML:
<!DOCTYPE html>
<!-- Create a function grabText that replaces the char - with _ -->
<html lang="en">
<meta charset="utf-8">
<head>
<title>HMTL Template</title>
</head>
<body>
<input type="text" id="inputField"
placeholder="Input Text"/>
<button id="clickButton" onclick="grabText();">Run</button>
<p id="outputText"></p>
</body>
</html>
And here is the JS:
var inputText;
function grabText () {
inputText = document.querySelector("#inputField");
document.getElementById("outputText").innerHTML = inputText.value;
inputText.value.replace(/-/g , "_");
document.getElementById("outputText").innerHTML = inputText.value;
}
I suspect there is an issue with where and how I am using .value . Thanks for any help.
keep in mind replace returns a new string, it doesn't change the existing one.
var inputText;
function grabText() {
inputText = document.querySelector("#inputField");
document.getElementById("outputText").innerHTML = inputText.value.replace(/-/g, "_");
}
<input type="text" id="inputField" placeholder="Input Text" />
<button id="clickButton" onclick="grabText();">Run</button>
<p id="outputText"></p>

Showing hidden input field with custom text

I have this text field hidden with HTML hidden code, now when the user enter an invalid input I use javascript to unhide the text field and display an error message, this is what is suppose to happen.
I have seen a lot of css style like
`style.visibility = 'visible';` and `style.display='block';`
But none of them are working for me what happens is that the error text shows for less than a second and then disappears, any one would like to share their thoughts.
This is the complete code for better understanding, it's still not working in firefox and Edge while IE and Chrome wont do anything, in Firefox, it just blinks once on each button press and that about it.
Javascript:
</script>
function validate(){
var firstname = document.getElementById("fn").value;
if (firstname == "") {
document.getElementById("fn").style.visibility = "visible";
document.getElementById("fn").text = "ERROR";
}
}
function init()
{
var formData = document.getElementById("enqForm");
formData.onsubmit = validate;
}
window.onload = init;
</script>
<!DOCTYPE html>
<html lang="en">
<head>
<script src="scripts.js"></script>
</head>
<body>
<form id="enqForm">
<input id="fn" type="text" placeholder="First Name *" />
<input id="sendbutton" type="submit" value="Enquire" />
</form>
</body>
</html>
Instead of changing the style, you can change the form's type attribute.
Using JavaScript - assuming you want to change lnspan to text:
document.getElementById('lnspan').type = 'text';
Style is not the same as the type attribute.
Also there's two id attributes in your <input>, you may want to change that.
**THAT IS THE ANSWER TO YOUR QUESTION**
<html>
<head>
<script>
function newDoc() {
document.getElementById("hid").type="text";
document.getElementById("hid").value="ERROR";
}
</script>
</head>
<body>
<input type="button" value="Load new document" onclick="newDoc()">
<input type="hidden" id="hid" value="">
</body>
</html>
<!--However this makes your error message as text field which is not good.
What you can do is make the Error into embedded into paragraph <p> so the
users cannot change it and it also looks more professional
<!DOCTYPE html>
<html>
<head>
<script>
function newDoc() {
document.getElementById("te").innerHTML="ERROR";
}
</script>
</head>
<body>
<input type="button" value="Load new document" onclick="newDoc()">
<p id="te">
</body>
</html>

JavaScript assigned array values removed after invoking function

Using JavaScript to display a list of what was typed into the textarea element listed below. The values submitted are displayed for a split second, but are removed from the array right after the function is called. Would anyone care to explain why?
HTML
<!DOCTYPE html>
<html>
<head>
<title>title</title>
<link rel='stylesheet' type='text/css' href='template.css'>
</head>
<body>
<header id='title'>
<h1></h1>
<h2></h2>
</header>
<div id='main_container'>
<div id='chat'>
<form id='messaging'>
<textarea id='current_msg'></textarea>
<input type='submit' value='send'>
</form>
<ul id='msg_list'>
</ul>
</div>
</div>
<script type='text/javascript' src='client.js'></script>
</body>
</html>
JavaScript
var msgList=[];
var form=document.getElementById('messaging');
var currentMsg=document.getElementById('current_msg');
var chat=document.getElementById('chat');
var ul=document.getElementById('msg_list');
function addText() {
if(currentMsg.value.length>0) {
if(msgList.length>=25) msgList.pop();
msgList.unshift(currentMsg.value);
currentMsg.value='';
console.log(msgList.length);
}
var concat='';
for(var index=0; index<msgList.length; index++) {
concat+='<li>'+msgList[index]+'</li>';
}
ul.innerHTML=concat;
}
if(document.addEventListener) {
form.addEventListener('submit', function() {
addText();
},
false);
}else {
form.attachEvent('onsubmit', function() {
addText();
},
false);
}
You need to understand the effects of having form:
1) User input some values
2) Once Submit the form get submitted , as you have not specified the action it will default to reload the current web page which means all inputs will be cleared
3) The html page get parsed from scratch , the JS code runs but it will only access the new values of inputs which are empty at this point
To make this work you need to remove the form tag

Why is my script not showing input characters dynamically in a div

I want to create a TextField in which when I give any input it show on div and this script is showing inputs but not properly...
I don't know where I am making mistakes and I request that please give your answers only in JavaScript please don't use jquery. Thank you .
<!DOCTYPE html>
<html>
<head>
<meta charset=utf-8 />
<title>JS Bin</title>
</head>
<body>
<form name="form">
<input name="t" value="" onkeypress="printvalues();">
</form>
<div id="divId"></div>
</body>
</html>
script
function printvalues() {
var div = document.getElementById("divId");
div.innerHTML += form.t.value;
}
Here is my code with output
function printvalues() {
var div = document.getElementById("divId");
div.innerHTML = document.form.t.value;
}
EDIT:The keypress event executes before the value of textbox is changed so use keyup() event which triggers when the key is released instead like
<input name="t" value="" onkeyup="printvalues();">
Your solution is here....
Just change onkeypress to onkeyup
Made below changes and enjoy..
function printvalues(a) {
var div = document.getElementById("divId");
div.innerHTML=a;
}
<input type="text" name="t" onkeyup="printvalues(this.value);">

Categories

Resources