How to get new input value with each button press? - javascript

Upon clicking the button it displays an alert from the input value + a custom string.
My issue is that after clicking the button and changing the input value, clicking the button again displays the old value instead of the new.
Javascript
function test() {
var message = document.getElementById("name").value;
var newMessage = message + " " + "HELLO!";
document.getElementById("send").addEventListener("click", function (e) {
e.stopImmediatePropagation();
alert(newMessage);
console.log(newMessage);
});
}
HTML
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script src="main.js"></script>
<link rel="stylesheet" href="style.css">
<title>Greet your friend</title>
</head>
<body>
<label class="main">Enter the name of your friend you want to greet</label>
<input class="main" type="text" name="name" id="name" value="George">
<button class="main" id="send" onclick=test()>DONE</button>
</body>
</html>

You had uncountable syntax problems which I fixed them. You don't need to use stopImmediatePropagation here.
function test() {
var message = document.getElementById("name").value;
var newMessage = message + " " + "HELLO!";
// -- You don't need a new variable to apply them --
// message += " " + "HELLO!";
// -- Or this one which is better and newer. Called 'String Literals' --
// message = `${message} HELLO!`;
alert(newMessage);
console.log(newMessage);
};
<label class="main">Enter the name of your friend you want to greet</label>
<input class="main" type="text" id="name" />
<button class="main" id="send" onclick="test()">DONE</button>

Related

How do i add edit buttons next to contacts in my contact list?

I specifically got an account on here to ask about this code where I've been sitting for a good while without finding a solution.
I'm new with coding and I am making a contacts list in Javascript where I so far have managed to make the list, but now I want to add buttons on the side of each contact, one where I can edit the contact and another where I can delete it. But I can't manage to create a button input through my js code.
Specifically for how I want the edit button to work is to change the attribute of the contacts name/number from readonly to where you can write and change it. Also, if there are any other improvements I could make to the rest of my code please let me know!
HTML:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>contacs list</title>
</head>
<h1>Your contacts</h1>
<hr>
<section>
<form id="getForm">
<label>Name:</label>
<input
placeholder = " Bertil..."
type="text"
id="contactName">
<label>phone:</label>
<input
placeholder = "xxx-xxx-xx-xx"
type="text"
id="contactNumber">
<input
type="submit"
class="saveButton"
onclick="getContact()">
</form>
</section>
<section>
<h3>My contacts</h3>
<div>
<ul id="contactsList">
</ul>
</div>
</section>
Javascript:
var contactList = [];
var getContact = function(){
event.preventDefault();
var newContact = {
name: document.getElementById("contactName").value,
number: document.getElementById("contactNumber").value
}
contactList.push(newContact);
console.log(contactList)
printList();
}
var printList = function (){
var li = document.createElement("li");
li.innerText = " ";
var list = document.getElementById("contactsList");
for (var i = 0; i < contactList.length; i++) {
li.innerText = contactList[i].name + " " + contactList[i].number + " ";
list.appendChild(li);
}
}
Thanks!
I have tried a bunch of things but none work so I think they're irrelevant?

Regular expression (For digits and characters)

I've been experimenting with a local sign in/log in system and I've hit a error. I was trying to make a regular expression that checks if the user's username and password contain 8 characters and 2 numbers. I really am not sure how to do that but this is all my code I've been able too put togheter.
HTML code:
<!DOCTYPE html>
<meta content="text/html;charset=utf-8" http-equiv="Content-Type">
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
<form id='form'>
<title>Sign Up #1</title>
<h3>Simple Signup system</h3>
<div>
<label>Username:</label>
<input type="text" name="text1" id = "username">
</div>
<div>
<label>Password:</label>
<input type="text" name="text2" id = "password">
<div>
<button type="button" id="subBtn">Sign Up!</button>
</form>
</body>
<script src="main.js"></script>
</html>
My JS code:
var t = 'everything good, loging in'
var f = 'something is not right, try again.'
var tf = 'not-set'
var statment = /^[a-zA-Z]*$/
window.onload = function() {
document.getElementById('subBtn').addEventListener('click', onSubmit);
}
// main
function onSubmit() {
if (document.getElementById('username').value.includes(Number)) {
tf = 'True'
} else {
tf = 'False'
}
if (document.getElementById('username').value.includes(statment)) {
tf.push('True')
} else {
tf.push('False')
}
if (tf = ['True', 'True']) {
alert('Good to go, redirecting')
} else {
alert('Username does not meet the standards for creating a account!')
}
document.forms['forms1'].submit()
}
EDIT: Was able to redo a part of the code, I'm still using regex to check for letters because I'm not sure how to do it without it.
Current error: 'first can't be a Regular Expression'.

How do I update the input value using an onchange event and get the value in vanilla Javascript?

I am doing an assignment where I make a simple API call using fetch to retrieve an image a of dog by breed. The one issue I can't resolve is that the input value never changes when I try to retrieve an image of a different breed. the default value, which is 'hound', reappears after I press submit. I know I need to attach an onchange event to my input but I am not sure how to write it or how to get the value after the onchange event is triggered. Any help would be greatly appreciated. I originally wrote this with jQuery but decided to rewrite it in vanilla Javascript so that's why there is no jQuery.
I put a '<---' on the line I am struggling with.
P.S I know my code isn't very good, I am new to this.
Javascript
function getJson(breed) {
fetch("https://dog.ceo/api/breed/" + breed + "/images/random")
.then((response) => response.json())
.then((responseJson) => displayResults(responseJson));
}
function displayResults(responseJson) {
const dogImage = responseJson.message;
let breedImage = "";
let container = document.createElement("div");
console.log(dogImage);
breedImage += `<img src="${dogImage}">`;
container.innerHTML = breedImage;
document.querySelector(".results-img").innerHTML = "";
document.querySelector(".results-img").appendChild(container);
}
function submitButton() {
let breedName = document.querySelector("#numberValue").value;
breedName.addEventListener().onchange.value; <---
document.getElementById("dog-input").addEventListener("submit", (e) => {
e.preventDefault();
getJson(breedName);
});
}
submitButton();
HTML
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Dog Api</title>
<link rel="stylesheet" href="style.css" />
</head>
<body>
<div class="container">
<form>
<input id="numberValue" type="text" value="hound" />
<button type="submit" class="submit-button">Submit</button>
</form>
<section class="results">
<h2>Look at these Dogs!</h2>
<div class="results-img"></div>
</section>
</div>
<script src="main.js"></script>
</body>
</html>
You don't need an onchange event handler. Currently you're storing the value of the input in breedName when you call submitButton. That means that breedName will never change because it is merely a reference to the value at that moment.
Instead create a reference to the element and read the value property in the submit event handler. That will get the value how it is at the time you submit.
function getJson(breedName) {
console.log(breedName);
}
function submitButton() {
const form = document.querySelector('#dog-form');
const input = document.querySelector('#numberValue');
form.addEventListener('submit', event => {
event.preventDefault();
const breedName = input.value;
getJson(breedName);
});
}
submitButton()
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Dog Api</title>
<link rel="stylesheet" href="style.css" />
</head>
<body>
<div class="container">
<form id="dog-form">
<input id="numberValue" type="text" value="hound" />
<button type="submit" class="submit-button">Submit</button>
</form>
<section class="results">
<h2>Look at these Dogs!</h2>
<div class="results-img"></div>
</section>
</div>
<script src="main.js"></script>
</body>
</html>

Why can I not get the text (name) of this button?

I am a beginner to javascript/jquery and I cannot figure out why I cannot fetch the text of the button clicked. When I console.log(this) it returns the button text. I cannot retrieve the value however to pass into the queryURL in the click handler. Sorry for the rudimentary question, any help would be appreciated.
var topics = ["boardwalk empire", "sopranos", "the wire", "billions", "entourage", "dexter", "breaking bad", "better call saul", "dark", "black mirror",]
var baseURL = "http://api.giphy.com/v1/gifs/search?q="
var apiKey = "Yz4pO4lJDaMYGIX80M9gc2Mq7HKKS2or"
for (var e = 0; e < topics.length; e++) {
var button = $("<button>").text(topics[e]);
button.addClass("btn-primary");
$(".show-buttons").append(button);
button.on("click",function (){
var input = $(this).val()
console.log(this)
var queryURL = baseURL + input + "&api_key=" + apiKey + "&limit=10";
$.ajax({
url: queryURL,
method: "GET"
}).then(function (response) {
console.log(response.data);
console.log(queryURL);
});
});
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<link rel="stylesheet"
href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.0.0/css/bootstrap.min.css" />
<title>Document</title>
</head>
<body>
<div class="container">
<h1>gifTastic!</h1>
<label for="search-field">Find a TV Show: </label>
<input type="text" id="search-field">
<input id="find-giphy" class="btn-primary" type="submit" value="giphy Search">
<div class="show-buttons"></div>
<div class="show-gifs"></div>
</div>
Modify btn click function to:
button.on("click",function (){
var input = $(this).text(); // .text() can be used to set and get text

Click function executed on page load

I am trying to bind my html button to a function using knockout. The function is only supposed to pop up the alert message when the button is clicked but instead, the function is executed on page load.
Here's my HTML:
<!DOCTYPE html>
<html lang="en">
<head>
<title>Bootstrap Example</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="main.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/js/bootstrap.min.js"></script>
<script type='text/javascript' src='knockout-2.2.0.js'></script>
<script type='text/javascript' src='studentapp.js'></script>
</head>
<body>
<div class="container">
<div class="new_student">
<input type="text" class="name" placeholder="name" data-bind="value: person_name, hasfocus: person_name_focus()">
<input type="text" class="age" placeholder="age" data-bind="value: person_age">
<button data-bind="click: createPerson">Create</button>
</div>
</body>
</html>
Here's my js:
function createPerson(){
alert("Name ");
};
ko.applyBindings(new createPerson());
The console is displaying the following:
Uncaught TypeError: Cannot read property 'nodeType' of null
Any ideas ?
view model should look like this
var createPerson = function(){
var self = this;
self.name = "Mike";
self.sendAlert = function(){
alert(self.name);
};
};
ko.applyBindings(new createPerson());
then your button can use
<button type="button" data-bind="click:sendAlert"></button>
Please have a look on this tutorial
Your code should looks like
var viewModel = function () {
var self = this;
self.name = "Name";
self.age = 22;
self.buttonClicked = function () {
alert(self.name + " is " + self.age + " old");
};
};
ko.applyBindings(new viewModel());
Here is working fiddle sample.
EDIT:
Fiddle was fixed, and link updated
try put defer tag in your script, and put all javascript code after </html> tag, it`s a good practice.
<script type='text/javascript' src='studentapp.js' defer="defer"></script>

Categories