How to include a input in a label in a querySelector() in javascript? - javascript

I am trying to construct a personality quiz for my school project. Everything was working fine until I decided that I want the inputs for the radio buttons to be just pictures. The problem is that I am not sure how to save the selected choice and its value, in order to calculate the result.
This is my HTML code:
<div id="simplequiz">
<h3>What's your favourite colour palette?</h3>
<p>
<input type="radio" name="colour" class="a" value="-1" />
<label for="p">
<img src="images/2.jpg" alt="Gothic colour palette" style="width: 200px">
</label>
</p>
<button type="submit" value="submit" onClick="submitSimpleQuiz()">Submit</button>
</div>
This is my CSS:
.input_hidden {
position: absolute;
left: -9999px;
}
.selected {
background-color: #ccc;
}
#simplequiz label {
display: inline-block;
cursor: pointer;
}
#simplequiz label:hover {
background-color: #efefef;
}
#simplequiz label img {
padding: 3px;
}
And this is my Javascript:
function submitSimpleQuiz() {
"use strict";
var colour = praseInt(document.querySelector('input[name = "colour"]:checked').value);
var total = colour;
if (total < 0) {
document.getElementById("answer").innerHTML = "Goth";
document.getElementById("simplequiz").style.display = "none";
} else {
document.getElementById("answer").innerHTML = "Minimalistic";
document.getElementById("simplequiz").style.display = "none";
}
}
$('#simplequiz input:radio').addClass('input_hidden');
$('#simplequiz label').click(function () {
$(this).addClass('selected').siblings().removeClass('selected');
});
This is just one question and answer but essentially all the answers should add up to an outcome which will display a personality description. I don't know why the button for submitting doesn't work anymore.
I would greatly appreciate the help.
I am only new to coding, but I tried including the label into the javascript and also changing the layout of the HTML so that the input is included in the label tag.

As I am sure you won't stop with only 1 question, here is a working snippet in which you can add more questions easily:
function submitSimpleQuiz() {
"use strict";
var total = 0;
var answer = ""; // Added, just because… (see below)
// Easy selection, now! That counts only "selected" inputs!
var inputs = document.querySelectorAll("#simplequiz .selected input");
for (var i = 0; i < inputs.length; i++) {
total += parseInt(inputs[i].value);
}
if (total < 0) {
answer = "Goth";
} else {
answer = "Minimalistic";
}
// Moved outside of the if to only have these instructions one time
document.getElementById("simplequiz").style.display = "none";
document.getElementById("answer").innerHTML = answer;
}
// Your other code, I haven't touched it. Promise.
$('#simplequiz input:radio').addClass('input_hidden');
$('#simplequiz label').click(function() {
$(this).addClass('selected').siblings().removeClass('selected');
});
.input_hidden {
position: absolute;
left: -9999px;
}
.selected {
background-color: #ccc;
}
#simplequiz label {
display: inline-block;
cursor: pointer;
}
#simplequiz label:hover {
background-color: #efefef;
}
#simplequiz label img {
padding: 3px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="simplequiz">
<h3>What's your favourite colour palette?</h3>
<p>
<!-- Modified order -->
<label for="p">
<input type="radio" name="colour" class="a" value="-1" />
<img src="images/2.jpg" alt="Gothic colour palette" style="width: 200px">
</label>
<!-- Added another one below -->
<label for="p">
<input type="radio" name="colour" class="a" value="1" />
<img src="images/2.jpg" alt="Minimal colour palette" style="width: 200px">
</label>
</p>
<button type="submit" value="submit" onClick="submitSimpleQuiz()">Submit</button>
</div>
<!-- Added "answer" -->
<div id="answer"></div>
Anyway, I've got a few remarks, here:
⋅ Your function submitSimpleQuiz is in JavaScript only, whereas your other code is in jQuery. You should choose what you want to use!
⋅ I moved the inputs in your labels to make it easier to select them.
⋅ Why are you using inputs if you're hiding them, and can't/don't check them?!…
Hope it helps.

You need to remove line :
$('#simplequiz input:radio').addClass('input_hidden');
Or you need to modify the line:
var colour = parseInt(document.querySelector('input[name = "colour"]:checked').value);
Because if you uncheck radiobutton you can't get the value. And You have to use parseInt not praseInt. it's an error.

First off all you need to import Jquery for using Jquery function $.
<script
src="https://code.jquery.com/jquery-3.3.1.min.js"
integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8="
crossorigin="anonymous"></script>
Second it is parseInt not praseInt.
Third:
use this piece of code instead of yours:
var colour = parseInt(document.querySelector("div#simplequiz input[name = 'colour']").value);
Fourth:
for your script to work correctly your javasScript should be -
<script type="text/javascript">
function submitSimpleQuiz(){
"use strict";
var colour = parseInt(document.querySelector("div#simplequiz input[name = 'colour']").value);
if (document.querySelector("div#simplequiz input[name = 'colour']").checked) {
colour = 0;
}
var total = colour;
if (total < 0) {
document.getElementById("answer").innerHTML = "Goth";
document.getElementById("simplequiz").style.display = "none";
}
else
{
document.getElementById("answer").innerHTML = "Minimalistic";
document.getElementById("simplequiz").style.display = "none";
}
}
$('#simplequiz input:radio').addClass('input_hidden');
$('#simplequiz label').click(function() {
$(this).addClass('selected').siblings().removeClass('selected');
});
</script>

Related

JavaScript Function

Hello everybody I have this code that I have made alone.
function appearafter() {
document.getElementById("buttonappear").style.display = "block";
document.getElementById("button").style.display = "block";
document.getElementById("hinzufuegen").style.display = "none";
function myFunction() {
var itm = document.getElementById("myList2").lastChild;
var cln = itm.cloneNode(true);
document.getElementById("myList1").appendChild(cln);
}
function allFunction() {
myFunction();
appearafter();
}
#button {
display: none;
}
#buttonappear {
display: none;
}
#test {
width: 300px;
height: 300px;
background-color: red;
}
<!DOCTYPE html>
<html>
<body>
<button id="hinzufuegen" onclick="allFunction()">ADD</button>
<div id="myList1">
<button id="button" onclick="">DELETE</button>
<div id="myList2">
<div id="test">
</div>
</div>
</div>
<button onclick="allFunction()" id="buttonappear">ADD</button>
</body>
</html>
What I want to make is that the red square whenever you are clicking on the ADD button it will be a clone and when you click on the DELETED button that the clone is deleted. Can somebody help me, please?
In addition to missing } as was mentioned in the comments, there was a not-so-obvious problem with finding the <div> to clone. The lastChild was actually a text node containing the \n (newline), after the <div>. It's better to search for <div> by tag:
var itm = document
.getElementById('myList2')
.getElementsByTagName('div')[0];
Since there's only one <div> we can use the zero index to find this first and only one.
And for delete function you can use a similar approach and get the last <div> and remove it.
function appearafter() {
document.getElementById("buttonappear").style.display = "block";
document.getElementById("button").style.display = "block";
document.getElementById("hinzufuegen").style.display = "none";
}
function myFunction() {
var itm = document.getElementById("myList2").getElementsByTagName("div")[0];
var cln = itm.cloneNode(true);
document.getElementById("myList1").appendChild(cln);
}
function deleteFunction() {
var list1 = document.getElementById("myList1");
var divs = Array.from(list1.getElementsByTagName("div"));
// If the number of divs is 3, it means we're removing the last
// cloned div, hide the delete button.
if (divs.length === 3) {
document.getElementById("button").style.display = "none";
}
var lastDivToDelete = divs[divs.length - 1];
list1.removeChild(lastDivToDelete);
}
function allFunction() {
myFunction();
appearafter();
}
#button {
display: none;
}
#buttonappear {
display: none;
}
#test {
/* make it smaller so it's easier to show in a snippet */
width: 30px;
height: 30px;
background-color: red;
}
<button id="hinzufuegen" onclick="allFunction()">ADD</button>
<div id="myList1">
<button id="button" onclick="deleteFunction()">DELETE</button>
<div id="myList2">
<div id="test"></div>
</div>
</div>
<button onclick="allFunction()" id="buttonappear">ADD</button>

Making a button that shows a hidden image on click

I've found tutorials that make an image hidden with some css, javascript and html but I'm having trouble making the image hidden first, and then having the button be able to make it visible and then hidden if pressed again.
edit: hopefully this code should help! Again, sorry I can't figure some of this out, I don't really know how this site works and I'm pretty new to coding,,,,
edit 2: I added where the function is being called. It's suppose to be a multiple choice that shows an image when correct!
<style>
div.notdropdown {
margin-top: 100px;
margin-bottom: 100px;
border: 1px solid black;
background-color: rgb(181, 204, 180, 0.9);
}
.hide{
display:none;
}
</style>
</body>
<script>
function myFunction() {
var x = document.getElementById("myDIV");
if (x.style.display === "none") {
x.style.display = "block";
} else {
x.style.display = "none";
}
}
</script>
<div id="myDIV">
<img class= "hide" src="https://www.merriam-webster.com/assets/mw/static/art/dict/frig_bi.gif">
<br>
<a class= "hide" href="https://www.merriam-webster.com/dictionary/frigate%20bird">https://www.merriam-webster.com/dictionary/frigate%20bird </a>
<br>
</div>
<h1>What is a Frigate?</h1><br>
<form >
<input type="radio" name="choice" value="Bird"> A type of Bird
<input type="radio" name="choice" value="Mangrove"> A type of Mangrove tree
<input type="radio" name="choice" value="Sea Creature"> A type of Sea Creature
<input type="radio" name="choice" value="None"> None of These
</form>
<button onclick="submitAnswer();"> Submit Answer</button>
</body>
<script>
function submitAnswer() {
var radios = document.getElementsByName("choice");
var i = 0, len = radios.length;
var checked = false;
var userAnswer;
for( ; i < len; i++ ) {
if(radios[i].checked) {
checked = true;
userAnswer = radios[i].value;
}
}
if(!checked) {
alert("please select choice answer");
return;
}
// Correct answer
if(userAnswer === "Bird") {
myFunction();
alert("Answer is correct!");
}
// incorrect answer
else {
alert("Answer is wrong!");
}
}
</script>
</body>
</html>
in fact it's very simple, just use the toggle method, which allows you to easily enable and disable a class in an element
function toggleImage(){
document.querySelector('#image').classList.toggle('hidden');
}
.hidden{
display: none;
}
.w-100{
width: 100%;
}
.mb-10{
margin-bottom: 10px;
}
<button onClick="toggleImage()" class="w-100 mb-10">Show/Hide</button>
<img src="https://images.pexels.com/photos/462118/pexels-photo-462118.jpeg?auto=compress&cs=tinysrgb&dpr=1&w=500" id="image" class="hidden w-100"/>
to work with a link to just change the tag to a and use href="#"
function toggleImage(){
document.querySelector('#image').classList.toggle('hidden');
}
.hidden{
display: none;
}
.w-100{
width: 100%;
}
.mb-10{
margin-bottom: 10px;
}
<a onClick="toggleImage()" class="w-100 mb-10" href="#">Show/Hide</a>
<img src="https://images.pexels.com/photos/462118/pexels-photo-462118.jpeg?auto=compress&cs=tinysrgb&dpr=1&w=500" id="image" class="hidden w-100"/>
You just need to call your function on button tag. Add a button in your html file on which you want your div to toggle. As you are using function name myFunction, call it on that function using
onClick="myFunction()"
And your code should work fine. Don't need to add any new class or even hide your div by default.
check this code. I think this will help you.
<button id = "showhide" onclick = "showhide()">Show Hide Image</button>
<div id = "image" style="width: 100px; height : 100px;">
<h4> Image Code </h4>
</div>
<script>
$('#showhide').on('click', function(e){
$("#image").toggle();
});
</script>

MultiSelect dropdown with checkbox slection using jQuery

I am trying to create a dropdown with multi-select check box manually using jQuery.
I don't want to use any built in libraries other than jQuery. I tried implementing the functionality but the issue is, when I select the check boxes, the data will be popped up in input field, if I click for the second time, I can see that checkboxes are unchecked and data is not appending to previous one.
Please tell me where i went wrong in the code.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>Untitled Document</title>
<style>
.multiselect {
width: 200px;
}
.selectBox {
position: relative;
}
.selectBox select {
width: 100%;
font-weight: bold;
}
.overSelect {
position: absolute;
left: 0; right: 0; top: 0; bottom: 0;
}
#presentationTable {
display: none;
border: 1px #dadada solid;
}
#presentationTable label {
display: block;
}
#presentationTable label:hover {
background-color: #1e90ff;
}
</style>
</head>
<body>
<form>
<div class="multiselect">
<div class="selectBox" onClick="showCheckboxes()">
<input type="text" id="presentatioonTableimputValue"><img src="http://siged.sep.gob.mx/analytics/res/s_blafp/uicomponents/obips.CommonIconSets/dropdownfilled_en_choicelistmulti.png" />
<div class="overSelect"></div>
</div>
<div id="presentationTable"> </div>
</div>
</form>
<script src="https://code.jquery.com/jquery-2.2.4.min.js"></script>
<script>
var expanded = false;
function showCheckboxes()
{
var abc = '<label><input type="checkbox" id="one" value="1"/>First1 checkbox</label> <label><input type="checkbox" id="two" value="two"/>Second checkbox </label> <label><input type="checkbox" id="three" value="three"/>Third checkbox</label>';
$('#presentationTable').html(abc);
if (!expanded) {
$('#presentationTable').show();
expanded = true;
} else {
$('#presentationTable').hide();
expanded = false;
}
}
function updateTextArea()
{
var allVals = [];
$('#presentationTable :checked').each(function () {
allVals.push($(this).val());
});
$('#presentatioonTableimputValue').val(allVals);
}
$(document).click(function(event){
var $trigger = $(".multiselect");
if($trigger !== event.target && !$trigger.has(event.target).length){
$("#presentationTable").slideUp("fast");
updateTextArea();
}
});
</script>
</body>
</html>
Try this:
JS
var expanded = false;
populateCheckbox();
function populateCheckbox(){
var abc = '<label><input type="checkbox" id="one" value="1"/>First1 checkbox</label> <label><input type="checkbox" id="two" value="two"/>Second checkbox </label> <label><input type="checkbox" id="three" value="three"/>Third checkbox</label>';
$('#presentationTable').html(abc);
}
function showCheckboxes()
{
if (!expanded) {
$('#presentationTable').show();
expanded = true;
} else {
$('#presentationTable').hide();
expanded = false;
}
}
function updateTextArea()
{
var allVals = [];
$('#presentationTable :checked').each(function () {
allVals.push($(this).val());
});
$('#presentatioonTableimputValue').val(allVals);
}
$("#presentationTable label input").click(function(){
updateTextArea();
});
$(document).click(function(event){
var $trigger = $(".multiselect");
if($trigger !== event.target && !$trigger.has(event.target).length){
$("#presentationTable").slideUp("fast");
// updateTextArea();
}
});
Each time when you click on the input field, it is creating new checkboxes, That was the issue.
hope it will solve your problem.

Button onclick more than once, different text in javascript

So i made this button, and i made the description text change from
{description}
to "No..." upon clicking. This is what i made:
function changeText(txt){
document.getElementById('name').innerHTML = txt;
}
<p>
<b id='name'>{description}</b>.
</p>
<input type='image'
onclick='changeText("No...")'
src='http://i.imgur.com/4y6bzH9.png'
style="margin-left: 540px; margin-bottom: 20px; position: absolute; outline: none;"/>
If you want, you can view what i did on /http://yosougay.tumblr.com/
I tried to make the description text change another time upon clicking another one time on the same button, so i tried adding another onClick, to make the description text change to "Another text" the next time you click the button.
function changeText(txt){
document.getElementById('name').innerHTML = txt;
}
<p>
<b id='name'>{description}</b>.
</p>
<input type='image'
onclick='changeText("No...")';
onclick='changeText("Another text")';src='http://i.imgur.com/4y6bzH9.png'
style="margin-left: 540px; margin-bottom: 20px; position: absolute; outline: none;" />
I tested it, and it didn't work. Please, is it possible to make a JavaScript button that changes the text to different texts every time it is clicked?
So far, I've only been able two make the text change once.
Try something like this: http://jsfiddle.net/54pp2/2/
<input id="click" type="button" value="click" />
<label id="test">Test</label>
$(document).ready(function () {
var textArray = [];
textArray[0] = 'test 1';
textArray[1] = 'test 2';
textArray[2] = 'test 3';
textArray[3] = 'test 4';
var idx = 0;
$('input#click').on('click', function(){
idx++;
var newidx = idx % textArray.length;
$('label#test').text(textArray[newidx]);
});
});
Sure you can.
You can only bind one click listener that way. Duplicating the attribute onclick will only override the first one, not provide two click listeners.
What you want to do is to handle the "different text every time" in you single onclick listener.
<script>
var txts = ["first", "second", "third"]
var counter = 0;
function changeText() {
document.getElementById('name').innerHTML = txts[counter%3];
counter++;
}
</script>
<p>
<b id='name'>{description}</b>.
</p>
<input type='image'
onclick='changeText()'
src='http://i.imgur.com/4y6bzH9.png'
style="margin-left: 540px;
margin-bottom: 20px;
position: absolute;
outline: none;"/>
I think this what you want
<script>
<!--
$(document).ready(function(){
var textarray ={"No...","Another Text"};
var count = 0;
$('input[type="image"]').click(function(){
$('#name').text(textarray[count]);
count = count==0?1:0;
});
});
// -->
</script>
<p> <b id='name'>{description}</b>. </p>
<input type='image' onclick='changeText("No...")' src='http://i.imgur.com/4y6bzH9.png'
style="margin-left:540px; margin-bottom:20px; position:absolute; outline:none;"/>
<br /><br />
You could keep track of how many times the button has been clicked from inside javascript.
<script>
var clicked = 0;
function changeText(){
if (clicked == 0) {
document.getElementById('name').innerHTML = "No...";
}
else if (clicked == 1) {
document.getElementById('name').innerHTML = "Another text";
}
clicked++;
}
</script>
Notice how I removed the argument from changeText() as well.
Fiddle
My suggestion is to change the onclick to onclick='changeText()'.
Store the texts in an array, and use a count property on the element. This will also move to the first text and repeat, on the third click.
var texts = [
'No',
'Another text'
];
function changeText(){
var elem = document.getElementById('name');
if(typeof elem.count == 'undefined'){
elem.count = 0;
} else {
elem.count++;
}
if(elem.count == texts.length){
elem.count = 0;
}
elem.innerHTML = texts[elem.count];
}

Simple image gallery JS

I'm trying to create a simple image gallery with radio buttons. Images are set to Display: none; by default. What I want is for them to display as block when I click on their respective buttons.
<html>
<head>
<style>
.img { width: 250px;
max-height: 300px;
display: none;
}
</style>
<script>
function picture (a) {
var pic = document.getElementById('image')
if (a == 1) {
pic.src="julia1.jpg"
} else { pic.src="julia2.jpg"}
pic.style.display ="block";
}
</script>
</head>
<body>
<img class="img" id="image" src="julia1.jpg">
<form action="">
<input type="radio" onclick="picture(1)" name="picture"></input>
<input type="radio" onclick="picture(2)" name="picture"></input>
</form>
</body>
</html>
On the browser console it says that object is not a function. What does that mean? (thats for both input tags)
The last line should read
pic.style.display = "block";
If anyone looking for simple js gallery check this example :
https://codepen.io/zarokr/pen/ZEzBYvY
let current = document.getElementById('current');
let thumbnails = document.getElementsByClassName('thumb');
for(let i = 0; i<thumbnails.length; i++){
thumbnails[i].addEventListener('click',changeImage);
}
function changeImage(){
let getsrc = this.getAttribute('src');
current.setAttribute('src',getsrc);
}

Categories