Show next div when button pressed - javascript

I am trying to create a list with five list items. By default there is only the first item shown and if i press a button "Next one" it shows next list item (and so on).
After reaching to the last item button shoud be disabled because there is no list items left.
How can i achieve this kind of behavior?
I have found this example here: JavaScript - show next div and hide previous
but this one hides previous one.
Maybe it can be combined with "addclass" function to add class ul siblings that haveent got a class?
Thanks for help.

According with the link you attach, if you use the same code and removes the line qElems[i].style.display = 'none'; it works as you like. But will be better if you learn javascript before coding.
Complete example (extracted from JavaScript - show next div and hide previous with some editions )
var showing = [1, 0, 0];
var questions = ['q0', 'q1', 'q2'];
function next() {
var qElems = [];
for (var i = 0; i < questions.length; i++) {
qElems.push(document.getElementById(questions[i]));
}
for (var i = 0; i < showing.length; i++) {
if (showing[i] == 1) {
showing[i] = 0;
if (i == showing.length - 1) {
document.getElementById("buttonNext").disabled = "disabled";
} else {
qElems[i + 1].style.display = 'block';
showing[i + 1] = 1;
}
break;
}
}
}
<div id="questions">
<div id="q0">
<h3>1. The color of the sky is... </h3>
<input type="radio" name="question0" value="A">Green<br>
<input type="radio" name="question0" value="B">Blue<br>
<input type="radio" name="question0" value="C">Red<br>
<input type="radio" name="question0" value="D">Purple<br>
</div>
<div id="q1" style="display: none">
<h3>2. Paper comes from... </h3>
<input type="radio" name="question1" value="A">Water<br>
<input type="radio" name="question1" value="B">Cement<br>
<input type="radio" name="question1" value="C">Trees<br>
<input type="radio" name="question1" value="D">The Sky<br>
</div>
<div id="q2" style="display: none">
<h3>3. How many hours in a day? </h3>
<input type="radio" name="question2" value="A">24<br>
<input type="radio" name="question2" value="B">22<br>
<input type="radio" name="question2" value="C">16<br>
<input type="radio" name="question2" value="D">48<br>
</div>
</div>
<button onclick="next()" id="buttonNext">Next Question</button>

I just made it using jquery:
$(document).on('click','button.next', function(){
var childID = $('#list li').index($('li.display'));
$('#list li:eq(' + childID + ')').toggleClass('display')
$('#list li:eq(' + ( childID + 1 ) + ')').toggleClass('display')
})
li{
display: none;
}
li.display{
display: block;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul id="list">
<li class="display">1</li>
<li>2</li>
<li>3</li>
<li>4</li>
<li>5</li>
</ul>
<button class="next">Next One</button>

Here is the HTML in which you create a list of five items, with first item is displayed by default and the rest is hidden.
html code
<div class='demo'>1</div>
<div class='demo' style='display:none;'>2</div>
<div class='demo' style='display:none;'>3</div>
<div class='demo' style='display:none;'>4</div>
<button class='next'>Next</button>
Here the button in action is next whenever you click the next button, it displays the next list item i.e on first click it would display second item and hides the rest. This will go on until the length of your list.
js code
var n = 2
$('.next').click(function(e){
$('.demo').hide();
$('.demo:nth-child('+n+')').show();
var demo_l = $('.demo').length;
if(n == demo_l){
$('.next').attr('disabled', 'disabled');
}
n++;
});
Here is the jsfiddle

Related

One submit button works on my form the other one refreshes the website while updating the url

Im trying to make a quiz using forms and the top submit button works perfectly while the bottom button does not work it ends up refreshing the page and it says the field selected in the address bar this is for a project for college and im a beginner to JavaScript if someone could help me out and explain how it works that would be great I understand how the script works with one from and one button and what the code does but im confused when it comes to 2 forms
var form = document.querySelector("form");
var log = document.querySelector("#log");
var points = 0;
var q1QuizAns = 0;
var q2QuizAns = 0;
form.addEventListener("submit", function(event) {
var data = new FormData(form);
var output = "";
for (const entry of data) {
output = output + entry[0] + "=" + entry[1] + "\r";
q1QuizAns = entry[1];
q2QuzAns = entry[1];
};
log.innerText = output;
event.preventDefault();
pointsAdd();
}, false);
function pointsAdd() {
if (q1QuizAns == 1) {
points = points + 1;
logPoints.innerText = points;
} else if (q2QuizAns == 1) {
points = points + 1;
logPoints.innerText = points;
}
}
<header>
<ul class="navbar">
<li>Home</li>
<li>Poland</li>
<li>Russia</li>
<li>Uzbekistan</li>
</ul>
</header>
<div class="testBody">
<div class="bodyText">
<h1>Poland Test</h1>
<form>
<p>Please select your preferred contact method:</p>
<div>
<input type="radio" id="contactChoice1" name="question1" value="1">
<label for="contactChoice1">Warsaw</label>
<input type="radio" id="contactChoice2" name="question1" value="2">
<label for="contactChoice2">Krakow</label>
<input type="radio" id="contactChoice3" name="question1" value="3">
<label for="contactChoice3">Straszyn</label>
</div>
<div>
<button type="submit">Submit</button>
</div>
</form>
<!-------------------------------------------------------------------------->
<form>
<p>What is the national animal of Poland</p>
<div>
<input type="radio" id="Question2Choice1" name="question2" value="1">
<label for="Question2Choice1">White-Tailed Eagle</label>
<input type="radio" id="Question2Choice2" name="question2" value="2">
<label for="Question2Choice1">Black-Tailed Eagle</label>
</div>
<div>
<button type="submit">Submit</button>
</div>
</form>
<!-------------------------------------------------------------------------->
<pre id="log">
</pre>
<pre id="logPoints"></pre>
<!-------------------------------------------------------------------------->
</div>
</div>
You have TWO forms. so you need an event handler for each
You have ONE log element so I suggest you might want to append the result
Move the preventDefault to the top of the handler to not have a later error submit the form
NOTE: Header ALSO goes in the body (but is irrelevant to your question).
var forms = document.querySelectorAll("form");
var log = document.querySelector("#log");
var points = 0;
var q1QuizAns = 0;
var q2QuizAns = 0;
forms.forEach(form => form.addEventListener("submit", function(event) {
event.preventDefault();
var data = new FormData(form);
var output = "";
for (const entry of data) {
output = output + entry[0] + "=" + entry[1] + "\r";
q1QuizAns = entry[1];
q2QuzAns = entry[1];
};
log.innerText += output;
pointsAdd();
}))
function pointsAdd() {
if (q1QuizAns == 1) {
points = points + 1;
logPoints.innerText = points;
} else if (q2QuizAns == 1) {
points = points + 1;
logPoints.innerText = points;
}
}
<div class="testBody">
<div class="bodyText">
<h1>Poland Test</h1>
<form>
<p>Please select your preferred contact method:</p>
<div>
<input type="radio" id="contactChoice1" name="question1" value="1">
<label for="contactChoice1">Warsaw</label>
<input type="radio" id="contactChoice2" name="question1" value="2">
<label for="contactChoice2">Krakow</label>
<input type="radio" id="contactChoice3" name="question1" value="3">
<label for="contactChoice3">Straszyn</label>
</div>
<div>
<button type="submit">Submit</button>
</div>
</form>
<!-------------------------------------------------------------------------->
<form>
<p>What is the national animal of Poland</p>
<div>
<input type="radio" id="Question2Choice1" name="question2" value="1">
<label for="Question2Choice1">White-Tailed Eagle</label>
<input type="radio" id="Question2Choice2" name="question2" value="2">
<label for="Question2Choice1">Black-Tailed Eagle</label>
</div>
<div>
<button type="submit">Submit</button>
</div>
</form>
<!-------------------------------------------------------------------------->
<pre id="log"></pre>
<pre id="logPoints"></pre>
<!-------------------------------------------------------------------------->
</div>
</div>

Showing <p> when radio button selected

I'm quite new to JS + HTML but basically i want 4 radio buttons, each with a different name like this
o PS4
o Xbox
o Nintendo DS
When one of these is clicked/checked, i want to output the price which will be held in a "p" next to them, as shown
o PS4 £400
""
""
The price is then hidden when the next is clicked, and the corresponding price for that is then shown, ive spent hours and hours trying to search for this and test things, but nothing seems to work, so ANY help is greatly appreciated
Thanks,
Dan
Here is a plain JavaScript example:
<form id="form">
<label>
<input name="console" type="radio" value="400">PS4</label>
<label>
<input name="console" type="radio" value="350">XBox</label>
<label>
<input name="console" type="radio" value="200">Nintendo DS</label>
</form>
<br>
<div>Price:
<div id="price"></div>
</div>
JavaScript (Using ES6)
document.getElementById('form').addEventListener('change', () => {
const radios = document.getElementsByName('console');
Object.keys(radios).forEach((obj, i) => {
if (radios[i].checked) {
price = document.getElementById('price');
price.innerHTML = `<p>£${radios[i].value}</p>`;
}
});
});
Sample:
JsFiddle
Here is the code that works perfectly fine:
$(document).ready(function(){
$(".price").hide();
$("input").click(function(){
$(".price").hide();
$(this).siblings().show();
});
});
<form id="form">
<span>
<input type="radio" name="drink" value="vodka"/>Vodka <span class="price">$40</span><br />
</span>
<span>
<input type="radio" name="drink" value="beer"/>Beer <span class="price">$50</span><br />
</span>
<span>
<input type="radio" name="drink" value="juice"/>Juice <span class="price">$20</span><br />
</span>
</form>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
or try this jsfiddle directly here:
https://jsfiddle.net/balyancoder/dbgkfw0f/
Here is an example using plain javascript and paragraph tag along with every radio button:
HTML:
<ul>
<li class="element"><input type="radio" class="radio_btn" name="my_radio">my radio 1
<p class="parag">price 1</p>
</li>
<li class="element"><input type="radio" class="radio_btn" name="my_radio">my radio 2
<p class="parag">price 2</p>
</li>
<li class="element"><input type="radio" class="radio_btn" name="my_radio">my radio 3
<p class="parag">price 3</p>
</li>
<li class="element"><input type="radio" class="radio_btn" name="my_radio">my radio 4
<p class="parag">price 4</p>
</li>
</ul>
Javascript:
var radios = document.getElementsByClassName("radio_btn");
for (var i = 0; i < radios.length; i++) {
radios[i].addEventListener(
'click',
function() {
var parags = document.getElementsByClassName("parag");
for (var i = 0; i < parags.length; i++) {
parags[i].style.display = "none";
}
this.nextElementSibling.style.display = "inline-block";
}
);
}
Here is the sample on JSFiddle

javascript conditional statement for a group of radio buttons

I want to make an online test, but i have some problems with the code below.
I want it to mark the correct and wrong answers, and show the score, when the button is pressed.
Now I have the following problem: I want the first switch statement to be only for the first group of radio buttons, the second switch statement for the second group of buttons, and so on.
How could I do that? When I run the code now, the colors change even though none of the radio buttons is checked, or when a button in only one of the groups is checked.
function showScore() {
var check;
var total = 0;
var yourmark = "your score is ";
switch (document.getElementById('q12').checked) {
case true:
total = total + 1;
document.getElementById('text1').style.color = "green";
break;
case false:
document.getElementById('text0').style.color = "red";
document.getElementById('text2').style.color = "red";
document.getElementById('text1').style.color = "green";
break;
}
switch (document.getElementById('q13').checked) {
case true:
document.getElementById('text0.1').style.color = "green";
total = total + 1;
break;
case false:
document.getElementById('text1.1').style.color = "red";
document.getElementById('text1.2').style.color = "red";
break;
}
alert(yourmark + total);
}
<input type="radio" name="question1" id="q11" value="false">
<text id="text0">Question 1-first option</text>
<br>
<input type="radio" name="question1" id="q12" value="true">
<text id="text1">Question 1- second option</text>
<br>
<input type="radio" name="question1" value="false">
<text id="text2">Question 1- third option</text>
<br>
<br>
<input type="radio" name="question2" id="q13" value="false">
<text id="text0.1">Question 1-first option</text>
<br>
<input type="radio" name="question2" id="q12" value="true">
<text id="text1.1">Question 1- second option</text>
<br>
<input type="radio" name="question2" value="false">
<text id="text1.2">Question 1- third option</text>
<br>
<button onclick="showScore();">Show my score</button>
Try this:
var questions = document.forms.myForm.getElementsByClassName('question');
document.getElementById('showScore').onclick = function showScore() {
var total = 0,
correct = 0;
for(var i=0; i<questions.length; ++i) {
var chosen = questions[i].querySelector(':checked');
if(chosen) {
questions[i].classList.add('show-score');
correct += chosen.value == 'true';
++total;
}
}
alert("Your score is " + correct + " out of " + total);
};
.question {
margin: 1em 0; /* Separation between questions */
}
.question > label:after { /* Line-break after each answer */
content: '';
display: block;
}
.question.show-score > input[value=true]+label {
color: green;
}
.question.show-score > input[value=false]+label {
color: red;
}
<form name="myForm">
<div class="question">
<input type="radio" name="question1" id="q-1-1" value="false">
<label for="q-1-1">Question 1 - first option</label>
<input type="radio" name="question1" id="q-1-2" value="true">
<label for="q-1-2">Question 1 - second option</label>
<input type="radio" name="question1" id="q-1-3" value="false">
<label for="q-1-3">Question 1 - third option</label>
</div>
<div class="question">
<input type="radio" name="question2" id="q-2-1" value="false">
<label for="q-2-1">Question 2 - first option</label>
<input type="radio" name="question2" id="q-2-2" value="true">
<label for="q-2-2">Question 2 - second option</label>
<input type="radio" name="question2" id="q-2-3" value="false">
<label for="q-2-3">Question 2 - third option</label>
</div>
<button id="showScore">Show my score</button>
</form>
Note those changes:
I have removed inline event listener from HTML, and added it using JS
I removed those ugly <br> and used CSS instead
I used <label> instead of invalid <text>. With <label>, you can also check a radio by clicking the text.
Instead of setting the color of correct/wrong answers with JS, I used CSS.
Well, ehr: group them. There's a lot wrong with your code and html. Id's are inconsistent, you are using inline event handlers, the code itself is bulky etc.
If you group the radiobuttons with a surrounding div, use consistent id's, labels instead of the <text> tag, leave the label-formatting to css and use querySelector[All], the code can be much shorter, really. Something like:
document.querySelector('body').addEventListener('click', showScore);
function showScore(e) {
var from = e.target || e.srcElement, fromtype = from.type;
if ( !(fromtype && /radio/i.test(fromtype)) ) { return true; }
var score = document.querySelectorAll('input:checked[value=true]').length;
// .. do stuff with [score]
}
It's demonstrated in this jsFiddle

Not able to hide, show button based on radio button select using JQuery

I have 6 groups of radio buttons with three choices each and a button to the next step. I want that a radio button in each group must be selected before the button to the next step is displayed. The button to the next step is hidden by default. It concerns a wordpress site and the code is provided by a plugin named: quform
The html code (1 group):
<div class="iphorm-group-row iphorm-clearfix iphorm-group-row-1cols"><div class="iphorm-element-wrap iphorm-element-wrap-radio iphorm_14_12-element-wrap iphorm-clearfix iphorm-labels-above iphorm-element-optional" style="display: block;">
<div class="iphorm-element-spacer iphorm-element-spacer-radio iphorm_14_12-element-spacer">
<label class="iphorm_14_12-outer-label">Group1</label>
<div class="iphorm-input-wrap iphorm-input-wrap-radio iphorm_14_12-input-wrap">
<div class="iphorm-input-ul iphorm-input-radio-ul iphorm_14_12-input-radio-ul iphorm-options-block iphorm-clearfix">
<div class="iphorm-input-li iphorm-input-radio-li iphorm_14_12-input-li">
<label class="iphorm_14_12_1_label">
<div class="radio" id="uniform-iphorm_14_12_523933240794b_1"><span><input type="radio" value="Level-1" id="iphorm_14_12_523933240794b_1" name="iphorm_14_12" class="iphorm-element-radio iphorm_14_12 iphorm_14_12_1"></span></div>
Level-1</label>
</div>
<div class="iphorm-input-li iphorm-input-radio-li iphorm_14_12-input-li">
<label class="iphorm_14_12_2_label">
<div class="radio" id="uniform-iphorm_14_12_523933240794b_2"><span><input type="radio" value="Level-2" id="iphorm_14_12_523933240794b_2" name="iphorm_14_12" class="iphorm-element-radio iphorm_14_12 iphorm_14_12_2"></span></div>
Level-2</label>
</div>
<div class="iphorm-input-li iphorm-input-radio-li iphorm_14_12-input-li">
<label class="iphorm_14_12_3_label">
<div class="radio" id="uniform-iphorm_14_12_523933240794b_3"><span><input type="radio" value="Level-3" id="iphorm_14_12_523933240794b_3" name="iphorm_14_12" class="iphorm-element-radio iphorm_14_12 iphorm_14_12_3"></span></div>
Level-3</label>
</div>
</div>
</div>
<div class="iphorm-errors-wrap iphorm-hidden">
</div> </div>
The Javascript code (6 groups):
$(".iphorm_14_12, .iphorm_14_13, .iphorm_14_14, .iphorm_14_15, .iphorm_14_16, .iphorm_14_17").click(function(){
var show = true;
$(".iphorm_14_12, .iphorm_14_13, .iphorm_14_14, .iphorm_14_15, .iphorm_14_16, .iphorm_14_17").each(function () {
if (!$(this).is(':checked')){
show = false;
}
$(".iphorm_14_12_1, .iphorm_14_12_2, .iphorm_14_12_3, .iphorm_14_13_1, .iphorm_14_13_2, .iphorm_14_13_3, .iphorm_14_14_1, .iphorm_14_14_2, .iphorm_14_14_3, .iphorm_14_15_1, .iphorm_14_15_2, .iphorm_14_15_3, .iphorm_14_16_1, .iphorm_14_16_2, .iphorm_14_16_3, .iphorm_14_17_1, .iphorm_14_17_2, .iphorm_14_17_3").each(function () {
if (!$(this).is(':checked')) {
show = false;
}
if (show) {
$('#btn-step-6').show();
} else {
$('#btn-step-6').hide();
}
});
});
});
Wrap each radio groups with a form or a div :
<div id="food">
<input type="radio" name="group1" value="Milk"> Milk
<input type="radio" name="group1" value="Butter"> Butter
<input type="radio" name="group1" value="Cheese"> Cheese
</div>
<div id="pets">
<input type="radio" name="group2" value="Dog"> Dog
<input type="radio" name="group2" value="Cat"> Cat
<input type="radio" name="group2" value="Dolphin"> Dolphin
</div>
Then in jQuery :
if ($('#food input[type=radio]:checked')[0] != undefined && $('#pets input[type=radio]:checked')[0] != undefined) {
$('#btn-step-6').show();
}
Try this:
<select name="top5" size="3">
<option onclick="showNextStep(this)">Checkbox</option>
</select>
in showNextStep(obj):
// The id of the hidden element -> displaly: none
if ($(obj).prop('checked')) {
$("#nextstep").css('display', "block");
} else {
// To hide if unselect
$("#nextstep").css('display', "none");
}
You can try jsfiddle example (http://jsfiddle.net/Lt92r/), I hope this will help.
$(".test input[type=radio]").click(function(){
$(this).parent("div").find(".btn").css("display","block");
});

Multiple selection checkbox values

I'm having trouble getting my var to accept more than one input.
When I select one checkbox, it shows me the value, however, when I select anymore I got an undefined error.
JavaScript
window.onload = function() {
var input= document.querySelectorAll('input#add2basket');
var radio= document.querySelectorAll('input#hi');
for (var j=0; j < radio.length; ++j){//loops over buttons
radio[j].onclick = function (){// find radio button
var input = findChecked(this.name);
alert (input.value)
return false;
// determine pizza size
//var size = input.value==='1'?‘Small':(input.value==='2'?'Regular':'Large');
// determine pizza price
//var price =Number(input.getAttribute('data‐price'));
// add a ‘new’ pizza to the basket
//addToBasket(newPizza(this.name,size, price));
};
};
function findChecked(name){
var css = 'input#hi[name="'+name+'"]';
var inputs = document.querySelectorAll(css);
var checked = _.filter(inputs, function (input){
document.write('<pre>'+input.checked+'</pre>')
return input.checked;
});
return checked.length===1?checked[0]:null;
}
}
HTML
<div>
<fieldset>
<legend class="Topping">Topping</legend>
<ul>
<li class="lastset"><input class="cbox" id="hi" name=
"top" type="checkbox" value="1"> <label class=
"box">Double Cheese</label></li>
<li class="lastset"><input class="cbox" id="hi" name=
"top" type="checkbox" value="2"> <label class=
"box">Peppers</label></li>
<li class="lastset"><input class="cbox" id="hi" name=
"top" type="checkbox" value="3"> <label class=
"box">Pepperoni</label></li>
<li class="lastset"><input class="cbox" id="hi" name=
"top" type="checkbox" value="4"> <label class=
"box">Olives</label></li>
<li class="lastset"><input class="cbox" id="hi" name=
"top" type="checkbox" value="5"> <label class=
"box">Beef</label></li>
<li class="lastset"><input class="cbox" id="hi" name=
"top" type="checkbox" value="6"> <label class=
"box">Seafood</label></li>
</ul>
</fieldset>
</div><!-- end topping -->
</form>
<div id="actionbtn">
<!--== action buttons==-->
<input class="apply" type="button" value=
"Back To Menu">
<input class="apply" name="top" id="add2basket" id="actionbtn2" type="button"
value="Proceed">
</div><!--==end of action buttons==-->
When I print the input.checked, it shows the selected boxes as true but where do i go from there
JavaScript solutions only please.
The attribute id must be unique across the whole document.
<li class="lastset"><input class="cbox" id="hi" name=
"top" type="checkbox" value="6"> <label class=
"box">Seafood</label></li>
updated code:
<li class="lastset"><input class="cbox" id="hi_1" name=
"top" type="checkbox" value="6"> <label class=
"box">Seafood</label></li>
(do this for every li and give each li its own id, if you really need an id in a li tag
To get all your inputs, use a different selector, like the class-attribute:
var css = 'input.cbox[name="'+name+'"]';
var radio= document.querySelectorAll('input.cbox');
Just select checkboxes by class name (and don't duplicate id's):
window.onload = function () {
var input = document.querySelectorAll('input#add2basket');
var radio = document.querySelectorAll('input.cbox');
for (var j = 0; j < radio.length; j++) {
radio[j].onchange = function () {
var input = findChecked(this.name);
return false;
};
};
function findChecked(name) {
var css = 'input.cbox:checked';
var inputs = document.querySelectorAll(css);
return inputs;
}
}
Pluss you can simplify selection of the checked only using :checked pseudo selector.
http://jsfiddle.net/BPFTp/1/

Categories