Radio button redirect page - javascript

I'm trying to make a menu for a Memory Game type game. I created the html page that contains a form consisting of 2 radio buttons with different values. On the submit input I called my function from the javascript file. And in the js file I created an if else function to redirect me, but it doesn't work.
Code:
`
let button = document.getElementById("button");
let solo = document.getElementById("solo");
let multiplayer = document.getElementById("multiplayer");
let level1 = document.getElementById("3x4");
let level2 = document.getElementById("4x4");
let radio1 = document.getElementsByName("radio1");
let radio2 = document.getElementsByName("radio2");
// button.addEventListener("click", gameMenu);
function gameMenu() {
if ((radio1.value = "solo") && (radio2.value = "3x4")) {
// location.href = "sg_34.html";
console.log("solo/3x4");
}
else if ((radio1.value = "solo") && (radio2.value = "4x4")) {
// location.href = 'sg-44.html';
console.log("solo/4x4");
}
else if ((radio1.value = "multiplayer") && (radio2.value = "3x4")) {
// location.href = 'mp-34.html';
console.log("mp/3x4");
}
else if ((radio1.value = "multiplayer") && (radio2.value = "4x4")) {
// location.href = "mp-44.html";
console.log("mp/4x4");
}
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=, initial-scale=1.0">
<link rel="stylesheet" href="./css/styleIndex.css">
<title>Memorizer JS</title>
</head>
<body>
<div class="container">
<h1>Memorizer JS</h1>
<form class="form menu">
<section class="game cf">
<h2>Choose game mode:</h2>
<input type="radio" name="radio1" id="solo" value="solo">
<label class="solo-label four col" for="solo">Solo</label>
<input type="radio" name="radio1" id="multiplayer" value="multiplayer">
<label class="multiplayer-label four col" for="multiplayer">With a friend</label>
</section>
<section class="level cf">
<h2>Level:</h2>
<input type="radio" name="radio2" id="3x4" value="3x4">
<label class="3x4-label four col" for="3x4">3x4</label>
<input type="radio" name="radio2" id="4x4" value="4x4">
<label class="4x4-label four col" for="4x4">4x4</label>
</section>
<input class="submit" id="button" type="submit" value="Play" onclick="gameMenu()">
</form>
</div>
<script src="./scripts/index.js"></script>
</body>
</html>
`
Code pen: https://codepen.io/sebastian-mihai-ciuc/pen/BaVagNM
I created the conditions in an if else structure to check the values in the radio buttons. I expected it to redirect me to other pages or at least display the cases in the console.log.

You should remove form tags for not reloading the window

Related

Adding inputs through for loop

How do I change this code so that when I select an input it adds the text from array based on input id. I have tried to do it myself, but in for loop "i" is always equal to 2, but I want it to be 0, 1 based on which input I select. Please help, I have spent multiple hours with no success.
let basetext = [];
let text1 = document.getElementById("text")
text1.innerHTML = basetext
const thank = [`hi`,
`bye`]
for (i=0; i<thank.length; i++) {
document.getElementById("thank"+i).addEventListener("click", function () {
basetext[i] = thank[i]
text1.innerHTML = basetext.join('')
})
}
<!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>Document</title>
<link rel="stylesheet" href="index.css" />
</head>
<body>
<textarea id="text"></textarea>
<div class="buttons">
<div>
<div>
<input type="radio" name="thank" id="thank0" />
<label for="thank0">first</label>
<input type="radio" name="thank" id="thank1" />
<label for="thank1">second</label>
</div>
<button>Next</button>
</div>
</div>
</body>
<script src="index.js"></script>
</html>
Add a data attribute to each input.
Add a class to a containing element, and then use event delegation to catch events from the child input elements when they're fired. In the handler check to see if the child element that fired the event is a radio input, and then use the data attribute to grab the element from the thank array, and update the textarea content with it.
// Cache the elements
const text = document.querySelector('#text');
const group = document.querySelector('.inputGroup');
// Add one listener to the input group element
group.addEventListener('change', handleChange);
const thank = [`hi`, `bye`];
// Check that clicked input is a radio button,
// grab the id from its dataset, and then use
// that id to add the element from the array to
// the content of the text area
function handleChange(e) {
if (e.target.matches('[type="radio"]')) {
const { id } = e.target.dataset;
text.defaultValue = thank[id];
}
}
<textarea id="text"></textarea>
<div class="buttons">
<div>
<div class="inputGroup">
<label for="0">first
<input
type="radio"
name="thank"
data-id="0"
id="thank0"
/>
</label>
<label for="thank1">second
<input
type="radio"
name="thank"
data-id="1"
id="thank1"
/>
</label>
</div>
<button>Next</button>
</div>
</div>

Using addeventlistener to add content when radio button is clicked in Javascript

I am a freshman at a university. I have been given an assignement where I need to use addEventListener. The problem is that I haven't used it before.
What this assignment is, is that I have a json file With a list of student names. My first exercise was to show a list of all the students. I did that. But then comes the hard part, where I can't find a possible solution, when I need to show only students that are in a certain program. There are radio buttons for each of the programs and when clicked a list of the members of the program need to show up. Also there is a radio button that says "all", which need to Select all the students.
Here is my javascript file:
.then((response) => {
return response.json();
})
.then(function appendData(data) {
var unordered = document.querySelector(".studenter");
for (var i = 0; i < data.length; i++) {
var li = document.createElement("li");
li.innerHTML = 'Name: ' + data[i].fornavn + ' ' + data[i].etternavn;
unordered.appendChild(li);
}
});
Here is the HTML file:
<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" />
<title>Studenter i IIKG1002 og IDG1011</title>
<script defer src="js/studenterIKlasse.js"></script>
<link rel="stylesheet" href="css/studenterIKlasse.css" />
</head>
<body>
<h1>Studenter i IIKG1002 og IDG1011</h1>
<p>Velg klasse</p>
<div class="klasseVelger">
<div>
<input type="radio" name="programvelger" id="BIGEOMAT" />
<label for="BIGEOMAT">Bachelor in Engineering, Geomatics</label>
</div>
<div>
<input type="radio" name="programvelger" id="BWU" />
<label for="BWU">Bachelor in Web Development</label>
</div>
<div>
<input type="radio" name="programvelger" id="ÅRWEB" />
<label for="ÅRWEB">Web Design - One-year programme</label>
</div>
<div>
<input type="radio" name="programvelger" id="BIXD" />
<label for="BIXD">Interaction Design - Bachelor's Programme</label>
</div>
<div>
<input type="radio" name="programvelger" id="all" />
<label for="all">Show all</label>
</div>
</div>
<p>
<ul class="studenter"></ul>
</p>
</body>
</html>
And here is an example of what the student Object look like (json):
{
"fornavn": "Marcus Gimse",
"etternavn": "Blikstad",
"studieprogram": "Bachelor in Engineering, Geomatics",
"forkortelse": "BIGEOMAT"
},

How to fix strange behaviour input radio in a JS quiz game

I'm trying to create a very basic JS quiz game. Almost everything works except for a single piece of code. When you hit the third radio input at the very last question, you have to double click the button in order to make true the "if else" statement. If I check the first two radio buttons everything works correctly. I don't understand why.
// VARIABLES
var all = {
question: ['Quante dita ha una mano?', "Qual è la capitale del Marocco", "Cosa si mangia in Spagna?" ],
response: [['uno', 'due', 'cinque'],['Marrakesh', 'Dubai', 'Roma'], ['Paella', 'Salsiccia', 'Fish']]
}
var i = 0;
var storage = [];
// TITLE
var title = document.getElementById("title");
//LABELS
var label1 = document.getElementById('risposta1');
var label2 = document.getElementById('risposta2');
var label3 = document.getElementById('risposta3');
// INPUTS
var inputs = document.querySelectorAll('input[type="radio"]')
var input1 = document.getElementById('input1');
var input2 = document.getElementById('input2');
var input3 = document.getElementById('input3');
// DISPLAY ANSWER
function displayAnswer(){
if(all.response[i] != undefined){
title.innerHTML = all.question[i];
label1.innerHTML = all.response[i][0];
label2.innerHTML = all.response[i][1];
label3.innerHTML = all.response[i][2];
}
}
displayAnswer();
document.querySelector('#btn').addEventListener("click", function(e){
inputs.forEach(function(input){
if(i <= (all.question.length - 1)){
if(input.checked === true){
console.log(e);
console.log(input3);
console.log(input.value);
storage.push(input.value);
i++;
displayAnswer();
console.log(i);
}
}
else {
console.log("Your score is: " + storage);
document.getElementById( 'content' ).style.display = 'none';
}
})
})
<!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">
<title>Document</title>
</head>
<body>
<div id="content">
<h1 id="title"></h1>
<label id="risposta1"></label>
<input id="input1" type="radio" name="test" value="1" ><br>
<label id="risposta2"></label>
<input id="input2" type="radio" name="test" value="2" ><br>
<label id="risposta3"></label>
<input id="input3" type="radio" name="test" value="3"> <br>
<button id="btn">Invia</button>
</div>
<script src="app.js"></script>
</body>
</html>
In the console there is no errors.

Jquery radio button starts endless loop?

I want to get an answer from the php file if I click on one of the radio buttons, but if I use the radio button, the alert appers in an endless loop. Why? And how do I get the alert only once?
I try it with only a „normal“ button, then it works:
If I click on the button, the ajax responds the values in the alert once.
Thank you
<!doctype html>
<html lang="de">
<head>
<title>test</title>
<!-- Required meta tags -->
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
</head>
<body>
<div class="container">
<br>
<br>
<button type="button" class="btn btn-dark" id="go">Go</button>
<div class="row">
<div class="btn-group" id="auswahl" data-toggle="buttons">
<label class="btn btn-outline-primary active">
<input type="radio" name="aktionswahl" value="alles" checked autocomplete="off"> Alles
</label>
<label class="btn btn-outline-primary">
<input type="radio" name="aktionswahl" value="blue" autocomplete="off"> blue
</label>
<label class="btn btn-outline-primary">
<input type="radio" name="aktionswahl" value="red" autocomplete="off"> red
</label>
</div>
</div>
</div><!--Container-->
<!-- jQuery first, then Popper.js, then Bootstrap JS -->
<script src="https://code.jquery.com/jquery-3.2.1.min.js"
integrity="sha256-hwg4gsxgFZhOsEEamdOYGBf13FyQuiTwlAQgxVSNgt4="
crossorigin="anonymous">></script>
<script>
$(function() {
$("input[name=aktionswahl]").focus(function () {
//var auswahl = this.value;
var sqlwhere = "where aktion=4 and Datum >= '2017-12-05' and Datum < '2017-12-07'";
ask(sqlwhere);
});
});
$(function() {
$("#go").click(function () {
var sqlwhere = "where aktion=4 and Datum >= '2017-12-05' and Datum < '2017-12-07'";
ask(sqlwhere);
});
});
function ask(sqlwhere) {
$.ajax({
type: 'POST',
url: 'read_sql.php',
data: { sqlwhere:sqlwhere }
}).done(function(data) { alert(data); });
return false;
}
</script>
</body>
</html>
As the alert appears, the radio button will lose focus. As you close the alert, the focus will return which triggers the alert which causes the radio button to lose focus but when you close that alert ...
Use console.log instead
Try this, your code is right just need one change...
write return false; immediately after alert.
means...function(data) { alert(data); return false; }

Aligning Header with Button in JQM after inserting HTML snippet with Javascript

I'm trying to inject into the header of a page(JQM) a title by using Javascript.
I also want to enable a Subscription feature so I need to insert the button via Javascript aswell. However, whenever I inject it, it's getting messy.
I want the button to align with the title, and I want the title in the middle of the header.
Here's a picture to demonstrate how it looks right now
and I want it to align perfectly, with no line-breaks at all(like it has now)
Im using these lines to insert the button and the title(JS):
document.getElementById("forum_name").innerHTML = fName;
document.getElementById("subscribe_btn").innerHTML = " <a href='#' class='ui-btn'>Unsubscribe</a>";
And Im using these lines in the HTML File:
<div data-role="header"><span style="display:inline;" id="subscribe_btn"></span><center><div id="forum_name" style="display:inline-block"></div></center></div>
With JQM you can do it following way:
var subscribeText = "Subscribe", unsubscribeText = "Unsubscribe";
function changeSubscription() {
var choiche = $('input[name=rg-subscription]:checked'),
value = choiche.val(),
label = choiche.parent().text();
$("#toggleSubscription").toggleClass("ui-screen-hidden", value == "no-subscription");
if (value == "no-subscription") {
$("#toggleSubscription").text(subscribeText);
}
var pageId = $(":mobile-pagecontainer").pagecontainer("getActivePage").prop("id");
$("#" + pageId + " [data-role='header'] h1").text(label);
}
$(document).on("pagecreate", "#page-1", function(e) {
$("input[name='rg-subscription']").change(changeSubscription);
$("#toggleSubscription").on("vclick", function(e) {
$(this).text($(this).text() === subscribeText ? unsubscribeText : subscribeText);
});
$("#injectButton").click(injectButton);
});
$(document).on("pagebeforeshow", "#page-1", function(e, ui) {
changeSubscription();
});
function injectButton() {
$("#toggleSubscription").off();
var html = [
'<button id="toggleSubscription" ',
'class="ui-btn-left ui-btn ui-btn-inline ui-mini ui-corner-all">',
'Subscribe',
'</button>'
].join("");
$("#toggleSubscription").remove();
$("#page-1 [data-role='header']").prepend(html).enhanceWithin();
$("#toggleSubscription").on("vclick", function(e) {
$(this).text($(this).text() === subscribeText ? unsubscribeText : subscribeText);
});
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, user-scalable=no">
<link rel="stylesheet" href="https://code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.css">
<script src="https://code.jquery.com/jquery-1.11.2.min.js"></script>
<script src="https://code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.js"></script>
</head>
<body>
<div id="page-1" data-role="page">
<div data-role="header">
<h1>Header</h1>
</div>
<div role="main" class="ui-content" id="page-1-content">
<fieldset data-role="controlgroup" data-mini="true">
<input name="rg-subscription" id="rc-subscription-0" value="no-subscription" checked="checked" type="radio">
<label for="rc-subscription-0">no subscription</label>
<input name="rg-subscription" id="rc-subscription-1" value="alt-binaries-mp3" type="radio">
<label for="rc-subscription-1">alt.binaries.mp3</label>
<input name="rg-subscription" id="rc-subscription-2" value="alt-binaries-linux" type="radio">
<label for="rc-subscription-2">alt.binaries.linux</label>
<input name="rg-subscription" id="rc-subscription-3" value="alt-binaries-games" type="radio">
<label for="rc-subscription-3">alt.binaries.games</label>
</fieldset>
<button id="injectButton" class="ui-btn ui-btn-inline ui-mini ui-corner-all">Inject "Subscribe" Button</button>
</div>
</div>
</body>
</html>

Categories

Resources