JavaScript assigned array values removed after invoking function - javascript

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

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.

Get Element Breaking Code

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?

Cant display JSON data in html page

I'm working on an API App utilizing the Foursquare API. Using my getRequest,
Im getting my results in JSON, which Im displaying in my console.log.
The thing is, I don't know how to parse the JSON data and display what I want on my HTML page.
I'm trying to have the 'name' of the venues displayed, but I don't know how to do it.
P.S: I have a Math.random function on the incoming data from Foursquare, so whatever random venue name that is displayed in my console.log is what I want displayed in my HTML page.
HTML:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Search</title>
<link href='http://fonts.googleapis.com/css?family=Lobster' rel='stylesheet' type='text/css'>
<link href='http://fonts.googleapis.com/css?family=Comfortaa' rel='stylesheet' type='text/css'>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.2/jquery.min.js" type="text/javascript" id="jquery"></script>
<script type="text/javascript" src="apps/app.js"></script>
</head>
<body>
<H1>Hunger Pains</H1>
<p>Search for food cause you cant take it anymore</p>
<!--This is the area your location gets spit out on the html page-->
<p id="demo"></p>
<form id ="search-term">
<!--text entry field-
<input type="text" id="query">-->
<!--Submit button-->
<input id="submit" type="submit" value="submit">
<!--Search results div-->
<div id="search-results"></div>
</form>
</body>
</html>
Jquery:
$(document).ready(function(){
//document.getElementById("submit").disabled = false;
//When you click the submit button it fires off the getRequest.
$(function(){
$('#search-term').submit(function(event){
event.preventDefault();
//getRequest();
myFunction();
});
});
// This is the get request. It has a random function that randomizes the callback data. Once you get the randomizes data, it shows in the console window.
//This function displays three random results based on the myFunction below
function getRequest(){
$.getJSON('https://api.foursquare.com/v2/venues/search?v=20131016&ll=40.7%2C-74&intent=browse&radius=800&categoryId=4d4b7105d754a06374d81259&client_id=C2IEUINHBL2HEVOHIWNO0GGN5EUHK3PGYH03HCZRP2ETA4CF&client_secret=DOLF3UBQZOY5GX2DP3EXBQ5CW4AHEWMNDGRMH0IHJWZBDSIO', function(data){
var random = data.response.venues[Math.floor(Math.random() * data.response.venues.length)];
//showResults();
console.log(random);
});
}
//This is the function that calls getRequest function three times then stops.
function myFunction(){
var myVar = setInterval(function(){getRequest();}, 500);
//clearTimeout(myVar);
setTimeout(function( ) { clearInterval( myVar); }, 1600);
}
});
To get the name from the object you are getting from Foursquare use:
console.log(random.name);
And if you need the url for example use:
console.log(random.url);
Something like this should do it:
$("#search-results").append('<br>' + random.name);

When input correct onload html document

<!DOCTYPE html>
<html>
<head>
<title>Test</title>
<script type="text/javascript" src="date_time.js"></script>
</head>
<body>
<input id="input"><br>What is the number?</input>
<button type="button" onclick="getFunction()">Submit</button>
<script>
function getFunction () {
var x = document.getElementById('input').value;
if (x == 32) {
window.alert("Right answer!");
}
else {
window.alert("Try again.");
}
}
</script>
</body>
</html>
So I want to proceed or load a new HTML page when the user clicks on the "submit" button and the input is correct. Any ideas? Maybe JS DOM could help...
First you need to add a form tag, and give it a name, id, and action. The action should point to your desired page.
<form name="formname" id="formid" action="mypage.html">
Your javascript, where it is true, should simple use:
document.getElementById("formid").submit();
And it will direct to the action page only when true.

How to swap an H1 element from an H1 in another document using JQuery

Please bear with me because I'm student. My instructor had us watch 5 YouTube videos and now expects us to program using JQuery instead of standard JavaScript. All I want to do is swap an element with an element from another file.
Here's my HTML code:
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Testing JQuery</title>
<script src="jquery-1.7.2.min.js"></script>
</head>
<body>
<h1 id="header">Testing JQuery</h1>
<p id ="dummy">Lorem Ipsum </p>
<script src="changes.js"></script>
<form name="input" action="changes.js">
<input type="button" value="Change the Header">
</form>
</body>
</html>
Here is my JavaScript/JQuery code:
$(document).ready(function() {
$('input').click(function() {
var url = $(this).attr('form');
$('#header').load( greeting.html + '#ajax h1');
return false;
});
});
The third file is called greeting.html and this is all it contains:
<h1 id="ajax">Hello from jQuery with AJAX</h1>
$('#header').load( 'greeting.html #ajax' );
That's all you need. Get rid of all the other stuff.
You dont need to declare url and you dont need to return false.
To replace the element, load() won't work as it loads the new H1 inside the old H1, it does not replace it, so you have to use $.get and do it yourself :
$(document).ready(function() {
$('input').on('click', function() {
$.get({
url : 'greeting.html'
}).done(function(data) {
var h1 = $('<div />').append(data).find('h1#ajax');
$('#header').replaceWith(h1);
});
return false;
});
});

Categories

Resources