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

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

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?

How to get new input value with each button press?

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>

Generate a New HTML Document with Javascript

Ok, so all I want to do is : whenever I write something in the Input and press the Button, a new HTML page gets created. But I also want to set the page's name and location. Tried searching it, couldn't find any results...
HTML
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Books test</title>
<link rel="stylesheet" href="https://cdn.rawgit.com/Chalarangelo/mini.css/v3.0.1/dist/mini-default.min.css">
</head>
<body>
<input type="text" id="book-input">
<button id="book-button">Create a book</button>
<h1>All the books</h1>
<ul id="books-list"></ul>
<script src="/app.js" defer></script>
</body>
</html>
Javascript
const bookNameInput = document.getElementById("book-input");
const bookCreateButton = document.getElementById("book-button");
var bookName;
var bookId;
bookCreateButton.addEventListener('click', createBook);
function generateRandomNumber() {
var randomNumber = Math.floor(1000000000 + Math.random() * 900000000);
var rn = randomNumber.toString();
return rn;
}
function createBook() {
bookName = bookNameInput.value;
bookId = generateRandomNumber();
fbn = bookName + '_' + bookId
var bookLi = document.createElement("li");
bookLi.classList.add("book-li")
var bookLiA = document.createElement("a");
bookLiA.innerText = bookName;
bookLiA.href = fbn + ".html";
document.getElementById("books-list").appendChild(bookLi);
bookLi.appendChild(bookLiA);
bookNameInput.value = "";
}
Tried using :
const newDoc = document.implementation.createHTMLDocument(title)
But doesn't creates any page...
I already answered your question in comments, so I'm writing this down as a answer so it might be helpful for others too.
So as i was saying it is totally possible to save the file directly from the client side without any need of server or special file system permission on client side -
In Short You can do something like this, Follow this step-by-step -
Get the value of the text input using input.value
Create a Blob out of It
Create a DOM element of anchor element with download attribute
Convert the Blob to an URL Using URL.createObjectURL and Chane the href of previously created anchor element to the returning url
Click on the anchor element without appending it to the DOM
Here is the Code
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Generate HTML Page</title>
<style>
* {
padding: 0;
box-sizing: border-box;
margin: 0;
}
</style>
</head>
<body style="padding: 20px">
<textarea
placeholder="Enter Your Content Here"
style="width: 100%; height: 500px; font-size: 18px; padding: 18px"
></textarea>
<br /><br />
<button>Download Text as HTML page</button>
<script>
let btn = document.querySelector("button");
let text = document.querySelector("textarea");
btn.addEventListener("click", () => {
if (!/^\s*$/.test(text.value)) {
let a = document.createElement("a");
a.setAttribute("download", "download.html");
let blob = new Blob(text.value.split(""));
let url = URL.createObjectURL(blob);
a.href = url;
a.click();
text.value = "";
} else {
alert("Blank text");
text.value = "";
}
});
</script>
</body>
</html>

Cannot get HTML table to display data from API

I followed a tutorial that fetches JSON data from an API and renders this into a table, but when I press the 'Create table' button the table doesn't show up. The 'Create JSON Data' button however is functional and creates dummy data as a test to show in the table, the 'Create Table' button is also working but just doesn't show the table.
Could it be document.GetElementById, var tbl = js.CreateTable, or var tbl = js.CreateTable causing the problem?
<!DOCTYPE html>
<html lang="en">
<head>
<title>JSON to Table</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.0/jquery.min.js" type="text/javascript"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.3.1/js/bootstrap.bundle.js" type="text/javascript"></script>
<script src="https://cdn.apidelv.com/libs/awesome-functions/awesome-functions.min.js" type="text/javascript"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/chance/1.0.6/chance.min.js" type="text/javascript"></script>
<body>
<div id="jsonData">
<button type="button" class="btn btn-primary CreateJSON">Create JSON Array</button>
<button type="button" class="btn btn-primary CreateMyTable">Create Table</button>
</div>
</body>
<script>
$(document).ready(function($)
{
function CreateJSONArray()
{
var total_rows = 10;
console.time('create_json_array')
var arr = []
for (var i = 0; i < total_rows; i++)
{
arr.push({
"id": i +1,
"first_name": chance.first(),
"email": chance.email({domain: 'gmail.com'}),
"ip_address": chance.ip(),
})
};
console.timeEnd('create_json_array')
return arr;
document.getElementById(CreateJSONArray)
}
$(document).on('click', '.CreateJSON', function(event)
{
event.preventDefault();
var data = CreateJSONArray();
console.log(data);
});
$(document).on('click', '.CreateMyTable', function(event)
{
event.preventDefault();
var data = CreateJSONArray();
//var tbl = js.CreateTable(data);
var tbl = js.CreateTable(data,['Line Num','First Name','User Emails','IP Address']);
$('.MyTable').html(tbl);
});
});
</script>
</head>
</html>
You need to have a table tag in your body, so something like:
<table class="MyTable"></table>
Don't forget to use the same class as you specify in you js, in this case MyTable since $('.MyTable').html(tbl).

Need help for a getInput function

I've been having trouble with my javascript code.
<!DOCTYPE html>
<html>
<head>
<title>js-game</title>
<script src="script.js" type="text/javascript"></script>
<script src="story.js" type="text/javascript"></script>
<link href="style.css" rel="stylesheet" type="text/css"/>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
<div id="game">
<ul id="output">
<li onclick="main()">Click here to start!</li>
</ul>
<input autofocus id="inputLine" type="text">
<p onclick="" id="enterInput">ENTER</p>
</div>
</body>
</html>
// Variables
var log="<li>Hello</li>";
var lastVar="";
// Functions
function getInput() {
document.getElementById("enterInput").addEventListener("click", function() {
return document.getElementById("inputLine").value;
document.getElementById("inputline").value="";
});
}
function output(output) {
log=log + "<li>" + output + "</li>";
document.getElementById("output").innerHTML=log;
}
function main() {
output("What's your name?");
alert(getInput());
}
As you can probably see I want to get input from a <input type="text"> with the id of inputLine. And a button with the id of enterInput.
But all I get back is undefined, and I've been working on this for a long time, so I'm getting frustrated.
Sorry for bad english.
Try doing it like so:
document.getElementById("enterInput").addEventListener("click", getInput );
function getInput() {
var val = document.getElementById("inputLine").value;
//do something with val
document.getElementById("inputLine").value="";
return val;
}
See this demo
Or to fetch it as a variable with getInput():
document.getElementById("enterInput").addEventListener("click", function(event){
var val = getInput();
alert(val);
});
function getInput() {
var val = document.getElementById("inputLine").value;
document.getElementById("inputLine").value="";
return val;
}
See this demo

Categories