How to ask Question 5 Times in Quiz App in JavaScript? - javascript

Im working on Quiz Web App.
I Just code a simple question.
but now I want To Ask The Question 5 Times.
i tried using for loop and also while loop but its didn't work.
i used lot off setTimeout functions here,
where user click on start button i want that question ask 5 times and count how many answers are right and how many answers are wrong.
How Can i do That ?
<?php
$btn1 = '<button id="optiona" class="btn btn-primary">2</button>';
$btn2 = '<button id="optionb" class="btn btn-primary">5</button>';
$btn3 = '<button id="optionc" class="btn btn-primary">11</button>';
$btn4 = '<button id="optiond" class="btn btn-primary">0</button>';
$btnArray = [$btn1, $btn2, $btn3, $btn4];
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Welcome</title>
<link rel="stylesheet" href="css/bootstrap.css">
<script src="js/jquery.js"></script>
<style>
#question{
margin: 10px 50px;
padding: 20px 40px;
box-shadow: 0 12px 16px 0;
font-size: 2em;
}
#options{
margin: 50px;
padding: 10px;
}
#options, button{
margin: 10px;
padding: 100px;
width: 50px;
}
</style>
</head>
<body>
<h1 id="hqid">Question<span id="qid"></span></h1>
<div class="container">
<button id="start" class="btn btn-primary">Start</button>
<div id="game">
<h1 id="question">What is 1 + 1 ?</h1>
<div id="options">
<?php
shuffle($btnArray);
print_r($btnArray[0]);
print_r($btnArray[1]);
print_r($btnArray[2]);
print_r($btnArray[3]);
?>
</div>
</div>
</div>
<script>
$('#hqid, #game').hide();
$(document).ready(function(){
localStorage.clear();
var count = 1;
//Check if you have a stored value
if (localStorage.getItem("count") === null) {
localStorage.setItem("count", 1);
}
count = localStorage.getItem("count");
$("button#start").on("click", function(){
$('#start').hide();
$('#hqid, #game').show();
$('h1 span').html(count);
$('#optiona, #optionb, #optionc, #optiond').click(function(){
$('#game').load('#options');
if(count < 6){
count++;
localStorage.setItem("count", count);
//process your code
//example
//END of the code
$('h1 span').html(count);
if(count == 6){
//get to default
localStorage.setItem("count", 1);
$('#start').show();
$('#hqid, #game').hide();
//go somewhere else
}
}
});
return false;
});
});
</script>
</body>
</html>
This Is Whole Code.
its looks messy but its working.

Here is code which works like you expecting:
index.php
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Welcome</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script>
<style>
.content {
padding-top: 10rem;
}
.answers.text-center {
margin: 1rem 0;
}
</style>
</head>
<body>
<div class="container">
<div class="row">
<div class="col-lg-12">
<div class="content">
<div class="jumbotron text-center">
<h1>Play game!</h1>
<button id="start" class="btn btn-lg btn-primary">Start</button>
</div>
<div id="game" class="text-center">
<h1 id="hqid">Question #<span id="qid"></span>: <span id="question">What is 1 + 1 ?</span></h1>
<hr>
<div class="answers text-center">
<label>Correct answers: <span class="success badge has-success"></span></label>
<label>Wrong answers: <span class="fail badge has-danger"></span></label>
</div>
<hr>
<div id="options">
<div class="btn-group" data-toggle="buttons">
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<script>
$(document).ready(function(){
var count = 1;
var success = 0; //right answers
var fail = 0; // wrong answers
var fileUrl = '/includes/options.php'; //php file where we calc all results
//Check if you have a stored value
$('#game').hide();
$("button#start").on("click", function(){
$('.jumbotron').hide();
$('#game').show();
$('h1 span#qid').html(count);
$('#options').show();
$('.success').html('0');
$('.fail').html('0');
success = 0;
fail = 0;
$.post(fileUrl, function( response, status, xhr ) {
var data = JSON.parse(response);
$('#options .btn-group').html(data.options);
});
});
$("#options .btn-group").on("click", "label.btn", function(e){
//$('#game').load('#options');
$('#options .btn-group').html('');
$.post(fileUrl, { answer: $(this).find('input').val() }, function( response, status, xhr ) {
//check response
var data = JSON.parse(response);
$('#options .btn-group').html(data.options);
if(data.status == 1){
success++;
$('.success').html(success);
} else {
fail++;
$('.fail').html(fail);
}
});
if(count < 5){
count++;
$('h1 span#qid').html(count);
} else {
$('.jumbotron h1').html(" Game over.");
$('.jumbotron button').text("Play again");
//get to default
count = 1;
$('.jumbotron').show();
$('#options').hide();
$('#hqid').hide();
}
});
});
</script>
</body>
</html>
additional file i created to establish correct answers:
options.php
<?php
/*
* Temporary we set right answer.
*/
$right_answer = 2;
/*
* Response array
*/
$response = [];
if(isset($_POST['answer'])){
(intval($_POST['answer']) == $right_answer)? $response['status'] = 1: $response['status'] = 0;
}
$btn1 = '<label class="btn btn-primary"><input type="radio" name="option[]" value="2" autocomplete="off">2</label>';
$btn2 = '<label class="btn btn-primary"><input type="radio" name="option[]" value="5" autocomplete="off">5</label>';
$btn3 = '<label class="btn btn-primary"><input type="radio" name="option[]" value="11" autocomplete="off">11</label>';
$btn4 = '<label class="btn btn-primary"><input type="radio" name="option[]" value="0" autocomplete="off">0</label>';
$btnArray = [$btn1, $btn2, $btn3, $btn4];
shuffle($btnArray);
$response['options'] = implode('', $btnArray);
/*
* Encode response in json string
*/
echo json_encode($response);
This code works on my localhost, and produce desired result.

Related

Did I correctly set-up my API for this weather app?

I am working with a weather app api and I am trying to display weather Data based off what the users inserts in the form. For some reason the data is not displaying. I have gone through the code 10 times, and I cant seem to find the error.
Can anyone take a look at point out where I have gone wrong?
Thank you
$(document).ready(function() {
$('submitWeather').click(function() {
var city = $('#city').val();
if (city != '') {
$.ajax({
url: 'https://api.openweathermap.org/data/2.5/weather?q=' + city + "&units=metric" + "&APPID=_MY_API_KEY_",
type: "GET",
dataType: "jsonp",
success: function(data) {
var widget = show(data);
$("#show").html(widget);
$("#city").val('');
}
});
} else {
$("#error").html('Field cannot be empty');
}
});
});
function show(data) {
return '<h3><strong>Weather<strong>: ' + data.weather[0].main + ' </h3>' +
'<h3><strong>Weather<strong>: ' + data.weather[0].description + ' </h3>';
}
console.log('hello')
.mainArea {
background-color: lightgray;
}
.day1,
.day2,
.day3,
.day4,
.day5 {
width: 220px;
height: 200px;
background-color: blue;
position: relative;
color: white;
}
.input {
text-align: center;
}
input[type='text'] {
height: 50px;
width: 200px;
background: #e7e7e7;
}
input[type='submit'] {
height: 50px;
width: 100px;
background: blue;
}
<!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://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous">
<link rel="stylesheet" type="text/css" href="style.css">
<title>Weather Dashboard</title>
</head>
<body>
<!-- Navigation Bar -->
<nav class="navbar navbar-light bg-light jumbotron">
<div class="navbar-brand">Weather Guide</a>
<!-- <form class="form-inline">
<input class="inputValue form-control mr-sm-2" type="text" placeholder="Search City" aria-label="Search">
<button class="button btn btn-outline-success my-2 my-sm-0" value="submit" type="submit">Search</button>
</form>-->
</nav>
<div class="container">
<div class="row">
<h3 class="text-center text-primary">Enter City Name</h3>
</div>
<div class='row form-group form-inline'>
<input tyepe='text' name='city' id="city" class="form-control" placeholder="city name">
<button id="submitWeather" class="btn btn-primary">Search</button>
</div>
<div id="show">
</div>
</div>
<!-- Main Content -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script src="script.js"></script>
</body>
</html>
$('submitWeather') should be $('#submitWeather')
Here's how to do it without jquery incase anybody wants it:
const getCity = () => document.querySelector('input#city').value || "austin"
document.querySelector("#getWeather").addEventListener('click', function () {
const url = `https://api.openweathermap.org/data/2.5/weather?q=${getCity()}&units=metric&APPID=_MY_API_KEY_`
loadDataRequest(url, displayJSON)
})
function loadDataRequest(url, cb) {
var xhttp;
xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function () {
if (this.readyState == 4 && this.status == 200) {
cb(this);
}
};
xhttp.open("GET", url, true);
xhttp.send();
}
function displayJSON(xhttp) {
document.querySelector("#show").textContent = JSON.stringify(JSON.parse(xhttp.response), null, 2);
}
<input id="city" name="city" placeholder="city"/>
<button id="getWeather" type="button" >Get</button>
<div id="show" style="white-space:pre"></div>

Change li element class when pressing a button and in that css class change background color

I have a todo app.
I managed to make it show an input when pressing the add button and to delete randomly, but when I click the done button I want to change the li element class to a class that has css background color red, but it doesn't work. I tried with jquery but it still doesn't work. The red background suggests that the task is done.
index.html
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<link rel="stylesheet" type="text/css" href="stil.css">
<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/css/bootstrap.min.css">
<!-- jQuery library -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<!-- Latest compiled JavaScript -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/js/bootstrap.min.js"></script>
<meta charset="utf-8">
<title></title>
</head>
<body>
<div class="centru">
<div class="row">
<div class="col-lg-12">
<h2>TO DO LIST</h2>
</div>
</div>
<div class="row">
<div class="col-lg-6">
<input type="text" class="form-control" id="usr" placeholder="Input task...">
</div>
<div class="col-lg-6">
<button type="button" class="btn btn-primary" onclick="adauga()">Add task</button>
</div>
</div>
<div class="row">
<div class="col-lg-12">
<ul class="list-group" id="lista1">
</ul>
</div>
</div>
</div>
<script src="script.js"></script>
</body>
</html>
script.js
function adauga() {
var inp = document.getElementById('usr').value;
var list = document.getElementById('lista1');
var li = document.createElement('li');
var lungime = document.getElementById("lista1").getElementsByTagName('li').length;
for(var i = 0; i < lungime ; i++) {
li.setAttribute("id",i);
}
li.appendChild(document.createTextNode(inp));
var button = document.createElement("button");
button.innerHTML = "Delete";
button.setAttribute("class","btn btn-primary ste");
button.setAttribute("onclick","sterge()");
//button.setAttribute("class","ste");
li.appendChild(button);
list.appendChild(li);
//////////////////////////////////////
var button2 = document.createElement("button");
button2.innerHTML = "Done";
button2.setAttribute("class","btn btn-primary done");
button2.setAttribute("onclick","done()");
li.appendChild(button2);
list.appendChild(li);
}
function change() {
li.setAttribute("class","xxx");
}
function sterge() {
$('body').on('click','.ste', function(){
$(this).parent().remove();
});
}
function done() {
$('body').on('click','done',function(){
$(this).parent().setAttribute("class","btn btn-primary done xxx");
});
}
stil.css
.centru {
width: 600px ;
margin-left: auto ;
margin-right: auto ;
}
.lix {
padding-right: 20px;
}
.xxx {
background-color: red;
color:red;
}
you can use addClass function on done function like this
function done() {
$('body').on('click','.done',function(){
$(this).parent().addClass("btn btn-primary done xxx");
});
}

How do I remove a to do list item after it is added

I really tried everything, almost every function in JS. But I cannot remove the list item from the to-do list once it is added. I have tried adding event listeners, onclick=" " etc but nothing works. Can someone please look at my code and tell me what I am doing wrong. Thank You, any help is much appreciated.
HTML:
<!DOCTYPE html>
<html lang="en">
<head>
<script
src="https://code.jquery.com/jquery-3.3.1.js"
integrity="sha256-2Kok7MbOyxpgUVvAk/HJ2jigOSYS2auK4Pfzbm7uH60="
crossorigin="anonymous"></script>
<script src="script.js"></script>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet href="style.css">
<link rel="stylesheet" href="style.css">
<link href="https://fonts.googleapis.com/css?family=Roboto" rel="stylesheet">
<meta charset="UTF-8">
<title>To-Do-List</title>
</head>
<body>
<div class="container">
<div id="header">
<h1>My To Do List</h1>
</div>
<form autocomplete="off">
<input type="text" id="task" placeholder="Title...">
</form>
<button id="addTask">Add</button>
</div>
<br><br>
<div id="tasks">
<ul id="myUL">
</ul>
</div>
</div>
</div>
<script>
var list = document.getElementById('myUL');
list.addEventListener("click", boxChecked);
function boxChecked(event){
const element = event.target;
if(element.type === "close"){
delete element;
}
}
</script>
</body>
</html>
JS:
$(document).ready(function(){
document.getElementById('addTask').addEventListener("click", function(){
var task = document.getElementById('task').value;
if(task == ""){
alert("You Must Enter A Value!");
}else{
document.getElementById('myUL').innerHTML += '<li>' + task + '</li>' + '<button class="close" >&#10007</button>' + '<br><br>' + '<button class="check" >✓</button>' + '<br><br>';
}
var button = document.querySelectorAll('.close');
for(var i = 0; i < button.length;i++){
button[i].addEventListener("click", function(){
this.parentNode.removeChild(this.previousSibling);
this.parentNode.removeChild(this);
});
}
var check = document.querySelectorAll('.check');
for(var i = 0; i < check.length;i++){
check[i].addEventListener("click", function(){
this.parentNode.style.textDecoration = "line-through";
});
}
});
});
Don't try to concatenate innerHTML strings when you have listeners attached to elements inside, else the listeners will be lost. Instead, append elements properly with appendChild.
delete element won't actually do anything, because element is a variable, not a property of an object - try using .remove() instead, to remove the li (and put the button inside the li so that the HTML is valid).
var list = document.getElementById('myUL');
list.addEventListener("click", boxChecked);
function boxChecked(event) {
const element = event.target;
if (element.className === "close") {
element.parentElement.remove();
}
}
document.getElementById('addTask').addEventListener("click", function() {
var task = document.getElementById('task').value;
if (task === "") return alert("You Must Enter A Value!");
const li = list.appendChild(document.createElement('li'));
li.textContent = task;
const button = li.appendChild(document.createElement('button'));
button.className = 'close';
button.textContent = '✗';
});
.close {
position: absolute;
left: 150px;
}
<div class="container">
<div id="header">
<h1>My To Do List</h1>
</div>
<form autocomplete="off">
<input type="text" id="task" placeholder="Title...">
</form>
<button id="addTask">Add</button>
</div>
<br><br>
<div id="tasks">
<ul id="myUL">
</ul>
</div>
Your .querySelectorAll() simply needs to target .close rather than close. In addition to this, you'll probably want to target the close button's parent (the item itself), with .parentNode. Note that you probably don't want to hide it, but rather actually simply remove both the <li> and the close icon, so that you can add more items after removal of the item(s). This can be done with:
this.parentNode.removeChild(this.previousSibling);
this.parentNode.removeChild(this);
And can be seen working in the following:
var list = document.getElementById('myUL');
list.addEventListener("click", boxChecked);
function boxChecked(event) {
const element = event.target;
if (element.type === "close") {
delete element;
}
}
$(document).ready(function() {
document.getElementById('addTask').addEventListener("click", function() {
var task = document.getElementById('task').value;
if (task == "") {
alert("You Must Enter A Value!");
} else {
document.getElementById('myUL').innerHTML += '<li>' + task + '</li>' + '<button class="close" >&#10007</button>' + '<br><br>';
}
var button = document.querySelectorAll('.close');
for (var i = 0; i < button.length; i++) {
button[i].addEventListener("click", function() {
this.parentNode.removeChild(this.previousSibling);
this.parentNode.removeChild(this);
});
}
});
});
<!DOCTYPE html>
<html lang="en">
<head>
<script src="https://code.jquery.com/jquery-3.3.1.js" integrity="sha256-2Kok7MbOyxpgUVvAk/HJ2jigOSYS2auK4Pfzbm7uH60=" crossorigin="anonymous"></script>
<script src="script.js"></script>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="style.css">
<link rel="stylesheet" href="style.css">
<link href="https://fonts.googleapis.com/css?family=Roboto" rel="stylesheet">
<meta charset="UTF-8">
<title>To-Do-List</title>
</head>
<body>
<div class="container">
<div id="header">
<h1>My To Do List</h1>
</div>
<form autocomplete="off">
<input type="text" id="task" placeholder="Title...">
</form>
<button id="addTask">Add</button>
</div>
<br><br>
<div id="tasks">
<ul id="myUL">
</ul>
</div>
</body>
</html>
Also note that your stylesheet is missing a closing ", and you have two additional closing </div> that don't match anything in your above code.

Script is getting executed before I press button

I'm stuck in this code this is a coursera assignment on angularjs. I'm beginner in angular js and new to stackoverflow. This is a code about to find how much a person should it. It counts the number of items and then show the result. Items are seperated by ','.
(function () {
'use strict';
angular.module('LunchCheck', [])
.controller('LunchCheckController', LunchCheckController);
LunchCheckController.$inject = ['$scope'];
function LunchCheckController($scope) {
//$scope.msg="";
//console.log($scope.calculate);
$scope.calculate="";
$scope.check = Checker($scope);
}
function Checker(string) {
var str = string.calculate;
console.log(str);
var str1 = str.split(',');
var temp = str1.length;
console.log(temp);
string.msg=message(string,temp);
}
function message(string,temp) {
if(temp > 3) {
return "Too Much!";
}
else if (temp==0) {
return "Aren`t you hungry??";
}
else {
return "Enjoy";
//console.log('Enjoy');
}
}
})();
<!doctype html>
<html lang="en">
<head>
<title>Lunch Checker</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<!--<link rel="stylesheet" href="styles/bootstrap.min.css">-->
<style>
.message { font-size: 1.3em; font-weight: bold; }
</style>
<script src="angular.min.js"></script>
<script src="app.js"></script>
</head>
<body ng-app="LunchCheck">
<div class="container" ng-controller="LunchCheckController">
<h1>Lunch Checker</h1>
<div class="form-group">
<input id="lunch-menu" type="text"
placeholder="list comma separated dishes you usually have for lunch"
class="form-control" ng-model="calculate">
</div>
<div class="form-group">
<button class="btn btn-default" ng-click="check();">Check If Too Much</button>
</div>
<div class="form-group message">
<!-- Your message can go here. -->
{{msg}}
</div>
</div>
</body>
</html>
Here javascript function is getting executed before I enter any input. I want it to execute after I enter a input. Please help.
Thanks in advance.

How to add images that were searched to an array then present them one by one in a slideshow?

I am looking to add images to an array by appending the outputted images based on what was searched. Before I implemented the array code, all of the photos would appear on the page, 15 or so. I hope to add them to an array and them show one at a time by adding a side. That is what I am trying to accomplish now.
<!DOCTYPE html>
<html>
<head>
<title></title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">
<!-- Optional theme -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap-theme.min.css">
<link rel="stylesheet" href="imageSearch.css">
</head>
<body>
<form class="form-inline" id="myForm" action="" method="post">
<div class="form-group">
<input type="text" class="form-control " id="item" name="imageSearch" placeholder="Search for an Image">
</div> <br> <br>
<input class="btn btn-default" type="submit" value="Submit"> <input class="btn btn-default" id="clear" type="button" value="Clear"> <br>
</form>
<div id="output"></div>
<script>
$('#myForm').on('submit', function(e){
e.preventDefault();
search();
return false;
});
function search() {
var images = new Array();
var apiKey = '';
$.ajax(
{
type:'GET',
url:"https://api.gettyimages.com/v3/search/images/creative?phrase=" + $('#item').val(),
beforeSend: function (request)
{
request.setRequestHeader("Api-Key", apiKey);
}})
.done(function(data){
console.log("Success with data")
for(var i = 0;i<data.images.length;i++)
{
images[i].src = " <img src='" + data.images[i].display_sizes[0].uri + "'/>" ;
$("#output").append(images[i]);
}
})
function nextImage(output)
{
var img = document.getElementById("output");
for(var i = 0; i < images.length;i++)
{
if(images[i].src == img.src) // << check this
{
if(i === images.length){
document.getElementById("output").src = images[0].src;
break;
}
document.getElementById("output").src = images[i+1].src;
break;
}
}
}
.fail(function(data){
alert(JSON.stringify(data,2))
});
return false;
}
</script>
<script type="text/javascript">
$("#clear").click(function()
{
$("#output").empty();
});
</script>
</body>
</html>

Categories

Resources