For/in loop not working in java script - javascript

function myFunction()
{
var x;
var txt="";
var person={fname:"John",lname:"Doe",age:25};
for (x in person)
{
txt=txt + person[x];
}
document.getElementById("demo").innerHTML=txt;
}
<button onclick="myFunction()">Try it</button>
<p id="demo"></p>
This function should display one property of the object person every time the button is clicked (first "John", then "Doe", and finally 25). However, the first time the button is clicked, the output is JohnDoe25. How can this function be modified so that it fits the requirement?

It's better to use array but in your case,
Yo can do it like this: LIVE DEMO
<script>
var x = 0;
var txt="";
var person={fname:"John",lname:"Doe","age":25};
function myFunction(){
if(x==0){
txt = person['fname'];
}
if(x==1){
txt = person['lname'];
}
if(x==2){
txt = person['age'];
}
x++;
document.getElementById("demo").innerHTML = txt;
}
</script>
<button onclick="myFunction()">Try it</button>
<p id="demo"></p>

Related

Is it possible to use a for loop to display values using buttons?

Hello here is my code at the moment. I would like to be able to display "you have selected" and then the name of the player that you pressed the draft button with however when pressing the button then it says you have selected "undefined". Would anyone be able to help thank you very much
var players=["Patrick Mahomes",
"Tyreek Hill",
"Travis Kelce",
"Chris Jones",
"Tom Brady"];
len=players.length;
for (var i=1;
i < len;
i++) {
document.getElementById("draft").innerHTML+=players[i]+"<button type=\"button\" onclick=\"draft()\">Draft</button><br>"
}
function draft() {
document.getElementById("demo").innerHTML+="You have selected"+players[i]+"<br>";
players.splice(players[i]);
}
<p id="draft"></p>
<p id="demo"></p>
the problem is that you don't specify the index when calling draft. You have to call it with the current index. I modified your code for it to work.
It should be easy to understand.
I also changed your var to let as it is better practice in javascript
<script>
let players = ["Patrick Mahomes", "Tyreek Hill", "Travis Kelce", "Chris Jones", "Tom Brady"];
let len = players.length;
for (let i = 0; i < len; i++) {
document.getElementById("draft").innerHTML += players[i] + "<button type='button' onclick='draft("+i+")'>Draft</button><br>"
}
function draft(player) {
document.getElementById("demo").innerHTML += "You have selected " + players[player] + "<br>";
players.splice(players[player]);
}
</script>
yes you can pass the player name as arg for draft()
for (var i=1;i<len;i++) {
document.getElementById("draft").innerHTML+=players[i]+"<button type=\"button\" onclick=\"draft('"+players[i]+"')\">Draft</button><br>"
}
function draft(player){
document.getElementById("demo").innerHTML+="You have selected "+player+"<br>";
players.splice(players[i]);
}
Why not pass i
<!DOCTYPE html>
<html>
<head>
<title>
Draft
</title>
</head>
<body>
<p id="draft"></p>
<script>
var players=["Patrick Mahomes","Tyreek Hill","Travis Kelce","Chris Jones","Tom Brady"];
len=players.length;
for (var i=0;i<len;i++) {
document.getElementById("draft").innerHTML+=players[i]+"<button type=\"button\" onclick=\"draft("+i+")\">Draft</button><br>"
}
// use different variable name for function parameter as var has scope for i here
function draft(k){
document.getElementById("demo").innerHTML+="You have selected"+players[k]+"<br>";
players.splice(players[k]);
}
</script>
<p id="demo"></p>
</body>
</html>
I didn't test but should work. I don't know why you are using players.splice(players[i]); but if you want to remove the element from players use
players.splice(k, 1);
See more https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/splice#Syntax
Just pass the index to your method draft so you can use it to display the right cell from your array:
var players = ["Patrick Mahomes", "Tyreek Hill", "Travis Kelce", "Chris Jones", "Tom Brady"];
for (var i = 1; i < players.length; i++) {
document.querySelector("#draft").innerHTML += players[i] + "<button type=\"button\" onclick=\"draft("+i+")\">Draft</button><br>"
}
function draft(index) {
document.getElementById("demo").innerHTML += "You have selected " + players[index] + "<br>";
}
<p id="draft"></p>
<p id="demo"></p>
I think you made a typo at declaring the "len" var.
try to use "var len = players.length" or use a comma after the players var declaration.

JavaScript function to hide buttons if specific text shows

I have a function called hideButtons that i want to hide buttons if certain text is present in the paragraph.
The paragraph goes through a list of names that the user either likes or dislikes and then when there are no more names then the buttons disappear.
Obviously this is sudo at the moment:
function hideButtons(){
if namespace.indexOf("Out of people"){
#likeButton = hidden;
#dislikeButton = hidden;
}
}
This is a working function
function showName(){
var name = names[0];
if (!name){
name = 'Out of people';
}
console.log(names)
document.getElementById('namespace').innerHTML = name;
}
And the html:
<body>
<p id='namespace'> Namelist </p>
<button id="likebutton" type="button">Like</button>
<button id="dislikebutton" type="button">Dislike</button>
</body>
You are sort of mixing up javascript and jQuery.
In javascript, to get the value of a p tag:
var ns = document.getElementById('namespace').innerHTML;
the same thing in jQuery:
var ns = $('#namespace').text();
jQuery uses the CSS selectors to identify elements, javascript does not.
Here is a semi-working version of your code.
var lb = document.getElementById('likebutton');
lb.addEventListener('click', hideButtons, false);
var db = document.getElementById('dislikebutton');
db.addEventListener('click', hideButtons, false);
function hideButtons(){
var ns = document.getElementById('namespace').innerHTML;
alert(ns);
if (ns.indexOf("Namelist") > -1 ){
lb.style.display = 'none';
db.style.display = 'none';
}
}
function showName(){
var name = names[0];
if (!name){
name = 'Out of people';
}
console.log(names)
document.getElementById('namespace').innerHTML = name;
}
<body>
<p id='namespace'>Namelist</p>
<button id="likebutton" type="button">Like</button>
<button id="dislikebutton" type="button">Dislike</button>
</body>
Here is the same code in jQuery:
$('#likebutton, #dislikebutton').click(function(){
var ns = $('#namespace').text();
if ( ns.indexOf('Namelist') > -1 ){
$('#likebutton').hide();
$('#dislikebutton').hide();
}else{
alert('P tag does not contain the word namespace');
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<body>
<p id='namespace'>Namelist</p>
<button id="likebutton" type="button">Like</button>
<button id="dislikebutton" type="button">Dislike</button>
</body>

How to make elements appear only when button is clicked in javascript

I'm trying to get answer to display when I press the Show Button but I can't get it to work. Could someone help me understand what I am doing wrong. I can get the first part to work where I generate a random integer. But the second part does not execute (JSFiddle).
<!DOCTYPE html>
<html>
<body>
<button class="button" onclick="disp()">Generate</button>
<button class="button" onclick="show_ans()">Show</button>
<script>
function disp() {
var i = Math.floor((Math.random() * 51) + 1);
var j = 2 * i;
document.getElementById("Goal").innerHTML = [i];
function show_ans() {
document.getElementById("answer").innerHTML = [j];
}
}
</script>
<p> Random Integer:
<span id="Goal"></span>
</p>
<p> Computed Answer:
<span id="answer"></span>
</p>
</body>
</html>
show_ans only exists within the scope of the disp function, so anything outside that scope (such as the rest of the page) can't invoke it.
Move it outside that function:
function disp() {
//...
}
function show_ans() {
//...
}
Of course, since show_ans also relies on j, that too will need to exist in a scope where both functions can access it:
var j;
function disp() {
var i = Math.floor((Math.random() * 51) + 1);
j = 2 * i;
document.getElementById("Goal").innerHTML = [i];
}
function show_ans() {
document.getElementById("answer").innerHTML = [j];
}

Show Multiplication Tables with a button

I want to make a page with JavaScript that has a button saying "Multiplication Tables." When I click the button, the multiplication table of 5 will show up in the "p" tag with the id "tables." I want to use a for loop to calculate the tables. Nothing is happening when I click the button.
HTML:
<body>
<button type="button" id="multiplication" onclick="table()">Multiplication Tables</button>
<br/>
<p id="tables"></p>
</body>
</html>
JavaScript:
function table()
{
var button = document.getElementById('multiplication');
var showTables = '';
for (var i=1; i<12; i++) {
showTables += 5 + "*" + i +"="+5*i + '\n';
}
var p_tables = document.getElementById('tables').innerHTML = showTables;
}
table();
Check this snippet by clicking run snippet button below, I think it's working fine
function table()
{
var button = document.getElementById('multiplication');
var showTables = '';
for (var i=1; i<12; i++) {
showTables += 5 + "*" + i +"="+5*i + '\n';
}
var p_tables = document.getElementById('tables').innerHTML = showTables;
}
<html>
<body>
<button type="button" id="multiplication" onclick="table()">Multiplication Tables</button>
<br/>
<p id="tables"></p>
</body>
</html>
Your are missing html tag before body and there might be some problem with your javascript inclusion, Also don't run table() function after declaring it.
Place the script either in head tag or before closing the body. Remove table() function calling after declaring it.

Javascript tutorial confusion about variable

Im reading the tutorials here.
I am getting confused trying to understand some of this example, why is the variable declared as nothing and what does the ,i indicate
var x="",i;
and also why do you use
x=x
at the beginning of the line?
<!DOCTYPE html>
<html>
<body>
<p>Click the button to loop from 1 to 6, to make HTML headings.</p>
<button onclick="myFunction()">Try it</button>
<div id="demo"></div>
<script>
function myFunction()
{
var x="",i;
for (i=1; i<=6; i++)
{
x=x + "<h" + i + ">Heading " + i + "</h" + i + ">";
}
document.getElementById("demo").innerHTML=x;
}
</script>
</body>
</html>
var x="",i;
This translates as
var x = "";
var i;
which simply declares those variables within the current scope.
x=x + ...
This means replace the value of x with the value of the expression to the right of the = sign. In this case, you are concatenating a string to the end of the current value of x.
var x="",i;
is the same as
var x = "";
var i;
Declare variables in the form of
var a=1,
b=2,
c=3;
is common and make the code style looking clear and easy to read.

Categories