What's wrong with this code(JavaScript, buttons, HTML)? - javascript

<!DOCTYPE html>
<html>
<head>
<title>Question 2</title>
<meta http-equiv="X-UA-Compatible" content="IE=9"/>
</head>
<body>
<button onClick="myFunction()">Alphabetical order</button>
<button onClick="countFunction">Count</button>
<p id="i"></p>
<p id="ii"></p>
<script>
var products = ["Printer", "Tablet", "Router", "Keyboard"];
document.getElementById("i").innerHTML = products;
function myFunction() {
products.sort();
document.getElementById("i").innerHTML = products;
}
function countFunction() {
document.getElementById("i").innerHTML = products.length;
}
</script>
</body>
</html>
I think it's just a spelling or formatting error. If you can change the code as little as possible while still fixing it I would appreciate it a lot. If you need any more details please just ask. I would be happy to provide as much information as I can to help you help me.
This is for my son - he loves traffic lights!

Modify these lines:
<button onClick="myFunction();">Alphabetical order</button>
<button onClick="countFunction();">Count</button>

Set type of buttons to button. Default type is submit so on
clicking your function doesn't execute and page is submitted.
onClick should be onclick.
You are missing () after countFunction so add () at end of
countFunction
<button type="button" onclick="myFunction()">Alphabetical order</button>
<button type="button" onclick="countFunction()">Count</button>

You missed the brackets inside the second onclick attribute:
<!DOCTYPE html>
<html>
<head>
<title>Question 2</title>
<meta http-equiv="X-UA-Compatible" content="IE=9"/>
</head>
<body>
<button onClick="myFunction()">Alphabetical order</button>
<button onClick="countFunction()">Count</button>
<p id="i"></p>
<p id="ii"></p>
<script>
var products = ["Printer", "Tablet", "Router", "Keyboard"];
document.getElementById("i").innerHTML = products;
function myFunction() {
products.sort();
document.getElementById("i").innerHTML = products;
}
function countFunction() {
document.getElementById("i").innerHTML = products.length;
}
</script>
</body>
</html>
Now if you use the code, the first button will sort the array into alphabetical order and the second one will display the number of values, hope this helps :)

Modify this:
countFunction changed to countFunction()

See here for a working version: https://jsfiddle.net/BrechtDeMan/hzg4zefb/
1. Add brackets to the function call in the onclick= bit
I.e. <button onClick="countFunction()">Count</button> instead of <button onClick="countFunction">Count</button>.
2. Get the right HTML element
Your code now has
document.getElementById("i").innerHTML = products.length;
meaning the array is then replaced with the number '4'.
Presumably you want
document.getElementById("ii").innerHTML = products.length;
so that the output is
Printer,Tablet,Router,Keyboard
4
3. Best practices
This will change your code as little as possible, like you asked.
However, there are other improvements that might improve the style of your code.
Technically the code works like this (barring compatibility issues I'm not aware of - it works for me).

Related

Is the problem the onclick method or the represenation of the html element as a object

I'm new to javascript and this has been driving me nuts for the last hour
Here's the html
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Number Guessing Game</title>
<link rel="stylesheet" href="styles/main.css">
</head>
<body>
<h1>Number Guessing Game</h1>
<p>Greetings hominid. I've selected a number between 1 and 100. See if you can guess it in 10 turns or fewer. I'll tell you if your guess was too high or too low.</p>
<label for="guess">Enter your guess:</label>
<input id="guess">
<button id ="submit">Submit</button>
<p id="response"></p>
<p id="guess-count"></p>
<p id="previous-guesses"></p>
<script src = scripts/game.js ></script>
</body>
</html>
And here's the javascript
const submitButton= document.getElementById('submit')
alert('hi')
submitButton.onClick = function submitGuess() {
alert('button is live')
}
For some reason the submitGuess function is not being executed at all (at least I'm not seeing the alert). I had a lot more javascript but I reduced it to find out why it wasn't working.
Any help is much appreciated
As pointed out in the comments, you can add the event handler in the JavaScript via EventTarget.addEventListener, rather than the inline HTML attribute. For example:
document.querySelector('#submit').addEventListener('click', event => {
console.log(`${event.target.id} was clicked`)
});
<h1>Number Guessing Game</h1>
<p>Greetings hominid. I've selected a number between 1 and 100. See if you can guess it in 10 turns or fewer. I'll tell you if your guess was too high or too low.</p>
<label for="guess">Enter your guess:</label>
<input id="guess">
<button id="submit">Submit</button>
<p id="response"></p>
<p id="guess-count"></p>
<p id="previous-guesses"></p>
const submitButton = document.getElementById('submit')
this line get the value before the DOM fully loaded the solution is to define the const after the page load like this
window.onload = function(){
const submitButton = document.getElementById('submit')
alert('hi')
if(submitButton){
submitButton.addEventListener('click', function() {
alert("Clicked!");
});
}else{
alert("Something Wrong")
}
}

Javascript Confirm Method is not working, Why there is no action on calling the method?

I have got stuck to this small thing.
<!DOCTYPE html>
<html>
<head>
<script>
function cnfm(){
var r = window.confirm("hey");
}
</script>
</head>
<body>
<button onclick="cnfm">here</button>
</body>
</html>
Whenever I am pressing on the button, no action.
You should call your method with paranthesis, <button onclick="cnfm()">here</button>
try for best practice and clean code like this:
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<button id='btn'>here</button>
<script>
let btn = document.querySelector('#btn')
btn.addEventListener('click', ()=>{
let r = window.confirm("hey");
})
</script>
</body>
</html>
this is modern javascript. now your confirm work. if user click of OK then r is equal true and if click on CANCEL thats be false.

How do I use javascript to create two button popups where the user can type in their name?

My sticking point is how to create two buttons and identify them separately within JS?
What the lecturer asks for in the image to create two buttons and two click functions.
My HTML code with the script tags:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Popup Boxes Lesson</title>
<body>
<button onclick="Enter Name">Click here for a popup alert</button>
</body>
<script>
function myFunction() {
alert("Enter your Name");
}
function myFunction(){
alert("Generate Greeting");
}
</script>
</html>
First of all create two different functions with different names.
Then you can use them with onclick
OR
Give them id and then use document.getElementById("id") to assign the click event on it. Something like this
<body>
<button id="foo">Click here for a popup alert</button>
</body>
<script>
document.getElementById('foo').onclick = function(){
prompt('Hello world');
}
</script>
There are several problems with your code:
First the click event you assigned to the button does not match the function you created.
Second don't create two functions with same names
The code should look like this:
<!DOCTYPE html>
<html>
<head>
<title>
Example
</title>
</head>
<body>
<button onclick="myFunction()">
Enter your name
</button>
<button onclick="generateMessage()">
Generate Message
</button>
<script>
function myFunction(){
var message = prompt("What is your name?");
}
function generateMessage(){
alert("Hello " + message);
}
</script>
</body>
</html>

Error... Talk is not defined

I'm trying to create a small RPG game.
But I keep receiving this error. I have my function (talk) defined. (activated by the talk button) Yet it says it's not defined.
<!DOCTYPE HTML>
<head>
</head>
<title> </title>
<body>
<script>
function talk() {
document.querySelector(".options").innerHTML = "<button onclick="fine()">I'm fine.</button>";
}
</script>
<div class="options">
<button onclick="talk()">Try it</button>
<button onclick="silent()">Stay Silent</button>
</div>
</body>
There's an error in the use of single and double quotation. Here's the fix:
function talk() {
document.querySelector(".options").innerHTML = "<button onclick='fine()'>I'm fine.</button>";
}
After doing this you'll get "fine is not defined". So you'll need to do something like this:
function fine(){
alert('I am fine');
}
Anyway, I don't get why are you trying to do this, but hope it helps!

Increase counter value upon button click

I cannot seem to get the jQuery bit I need to work. I've never used jQuery before, but I'd like to have a button on my page that, when clicked, increments an initially 0 value by one. My question is similar to jQuery - Increase the value of a counter when a button is clicked and press button and value increases in text box but I can't make sense of what I'm doing wrong. Here's what I have:
<html>
<head>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.4.3.min.js"></script>
<script type="text/javascript">
$("#update").click(function()
{
$("#counter")++;
}
</script>
</head>
<body>
<input type="text" name="TextBox" id="TextBox" value="0" />
<input type="Button" id='AddButton' value="+" />
<script type="text/javascript" src="http://code.jquery.com/jquery-1.4.3.min.js"></script>
<script type="text/javascript">
$('#AddButton').on('click', function ()
{
var input = $('#TextBox');
input.val(parseInt(input.val()) + 1);
})
</script>
</body>
</html>
Any help is greatly appreciated. Please forgive any huge glaring mistakes, I have no idea how to do any of this yet. Thank you, and happy tidings! =)
It's clear you're new to jQuery, so a good read might be of help to you, I would recommand Head First jQuery.
As for the question, I rewrote your code, here's what it should be like :
<!DOCTYPE html>
<html>
<head>
<title> My first increment </title>
</head>
<body>
<input type="text" name="TextBox" id="TextBox" value="0" />
<input type="Button" id='AddButton' value="+" />
<script src="http://code.jquery.com/jquery-1.4.3.min.js"></script>
<script>
$(document).ready(function(){
$('#AddButton').click( function() {
var counter = $('#TextBox').val();
counter++ ;
$('#TextBox').val(counter);
});
});
</script>
</body>
</html>
Here is a little test : test me
The idea is to increment a variable not an object, and you have some syntax mistakes as well, but try this code and we can discuss it further on comments.
Best of luck.
(This is merely a supplement to other answers)
You only need to load this once before all other js srcs:
<script type="text/javascript" src="http://code.jquery.com/jquery-1.4.3.min.js"></script>
That's a really old jquery version. You can find the latest here.
Almost all jQuery code should be wrapped in
$(document).ready(function(){
});
Do it all of the time until you find a reason not to which is rare for pure jQuery.
Assuming $('#TextBox') can never be changed from the last counter, you might like:
$('#TextBox').val(0);
$('#AddButton').click( function() {
$('#TextBox').val(parseInt($('#TextBox').val()) + 1);
});
but if you want TextBox to be changed by the user then set back to the incrememented counter whenever AddButton's clicked, assuming counter should start at 0:
counter = 0;
$('#AddButton').click( function() {
counter++;
$('#TextBox').val(counter);
});
It should be:
var counter = 0;
$("#update").click(function()
{
counter++;
});
Demo for this here.
If counter is a variable you need to define it (var counter;) and you forgot also to close the click ")". Notice the extra ) in the end. What you were doing was increment a jQuery object (good idea to explain Ohgodwhy).
In case what you want is to put the value in another field (and now I am guessing a bit), like an input field, you can do this:
var val;
$("#update").click(function()
{
val = $('#counter').val();
val++;
$('#counter').prop('value',val )
});
Demo for this here.
This can be done using plain html and JS, Attaching the code below
<b>
<button id="btn" onclick="this.innerHTML=++this.value" value=0 >0</button>
</b>

Categories

Resources