I have a slider with 6 slides in it. My goal is to show only 3 first slides if radio button id="male" is checked and 3 last slides if id="female" button is currently checked. I've tried splicing array in half and setting slide index depending on checked button but it didn't help. Here is my HTML code:
function skinSlider() {
let slideIndex = 1,
female = document.getElementById('female'),
male = document.getElementById('male'),
skinSlider = document.getElementsByClassName('skin')[0],
skinSliderItem = document.getElementsByClassName('skin-color'),
prev = skinSlider.querySelector('.prev'),
next = skinSlider.querySelector('.next');
showSlides(slideIndex);
function plusSlides(n) {
showSlides(slideIndex += n);
}
prev.addEventListener('click', () => {
plusSlides(-1);
});
next.addEventListener('click', () => {
plusSlides(1);
});
function showSlides(n) {
// if (female.checked && slideIndex < 4) {
// slideIndex = 4;
// }
if (n > skinSliderItem.length) {
slideIndex = 1;
}
if (n < 1) {
slideIndex = skinSliderItem.length;
}
for (let i = 0; i < skinSliderItem.length; i++) {
skinSliderItem[i].style.display = 'none';
}
skinSliderItem[slideIndex - 1].style.display = 'block';
let personSkin = document.getElementById('person-skin');
personSkin.style.background = `url('./img/skin/skin-${slideIndex}.png') center no-repeat`;
personSkin.style.backgroundSize = 'cover';
}
};
<div class="radio">
<input value="male" id="male" name="sex" type="radio">
<label for="sex">Male</label>
<input value="female" id="female" checked name="sex" type="radio">
<label for="sex">Female</label>
</div>
<div class="custom-style">
<div class="style-text">
Choose skin color
</div>
<div class="skin">
<div class="prev">
<i class="flaticon-left-arrow"></i>
</div>
<div class="skin-color skin-color-1"></div>
<div class="skin-color skin-color-2"></div>
<div class="skin-color skin-color-3"></div>
<div class="skin-color skin-color-4"></div>
<div class="skin-color skin-color-5"></div>
<div class="skin-color skin-color-6"></div>
<div class="next">
<i class="flaticon-right-arrow"></i>
</div>
</div>
Any help would be appreciated.
I think this accomplishes roughly what you're looking for. Unfortunately, the slider "wraps" when moving to the right and simply stops at the lower limit when moving to the left. But I'll leave that as an additional challenge for you. :-)
function skinSlider() {
let slideIndex = 1,
female = document.getElementById('female'),
male = document.getElementById('male'),
skinSlider = document.getElementsByClassName('skin')[0],
skinSliderItem = document.getElementsByClassName('skin-color'),
prev = skinSlider.querySelector('.prev'),
next = skinSlider.querySelector('.next');
showSlides(slideIndex);
function plusSlides(n) {
showSlides(slideIndex += n);
}
prev.addEventListener('click', () => {
plusSlides(-1);
});
next.addEventListener('click', () => {
plusSlides(1);
});
female.addEventListener('click', () => {
showSlides(slideIndex);
});
male.addEventListener('click', () => {
showSlides(slideIndex);
});
function showSlides(n) {
if (slideIndex > skinSliderItem.length) {
slideIndex = 1;
}
if (slideIndex < 1) {
slideIndex = skinSliderItem.length;
}
if (female.checked && slideIndex < 4) {
slideIndex = 4;
} else if (male.checked && slideIndex > 3) {
slideIndex = 1;
}
for (let i = 0; i < skinSliderItem.length; i++) {
skinSliderItem[i].style.display = 'none';
}
skinSliderItem[slideIndex - 1].style.display = 'block';
}
};
skinSlider();
<div class="radio">
<input value="male" id="male" name="sex" type="radio">
<label for="sex">Male</label>
<input value="female" id="female" checked name="sex" type="radio">
<label for="sex">Female</label>
</div>
<div class="custom-style">
<div class="style-text">
Choose skin color
</div>
<div class="skin">
<div class="prev">
<
</div>
<div class="skin-color skin-color-1">1</div>
<div class="skin-color skin-color-2">2</div>
<div class="skin-color skin-color-3">3</div>
<div class="skin-color skin-color-4">4</div>
<div class="skin-color skin-color-5">5</div>
<div class="skin-color skin-color-6">6</div>
<div class="next">
>
</div>
</div>
As an aside, the for attribute of the label elements should use the IDs of the associated inputs, not the name of the checkbox group.
Related
I have a section containing some radio buttons and other HTML elements.
When scrolling the page reached to the section, I need to like disable the scroll of the page and instead show some styles on the radios. After reaching to last radio button, enable to scroll the page.
var enabaled = true;
window.onload = function() {
function checkVisibilityOfDiv() {
var target = $(".scene44").offset().top;
if ($(window).scrollTop() >= target ) {
return true;
}
return false;
}
function enableScroll() {
window.onscroll = function () {
};
}
function disableScroll() {
// Get the current page scroll position
scrollTop =
window.pageYOffset || document.documentElement.scrollTop;
scrollLeft =
window.pageXOffset || document.documentElement.scrollLeft,
// if any scroll is attempted,
// set this to the previous value
window.onscroll = function () {
window.scrollTo(scrollLeft, scrollTop);
};
}
let amount = 0;
let current = 1;
let max = 7;
var lastScrollTop = 0;
document.addEventListener('scroll', () => {
if (checkVisibilityOfDiv() ) {
var st = window.pageYOffset || document.documentElement.scrollTop;
amount++;
if (amount >= 9) {
amount = 0;
if (st > lastScrollTop ) { //detect scroll direction
// downscroll code
console.log(" down, " + current);
if(current===1 && enabaled=== true){
disableScroll();
enabaled=false;
}
document.getElementById('r' + current).checked = false;
//If you reach the last radio element you reset the counter
if (current === max) {
document.getElementById('r' + current).checked = true;
} else {
current += 1;
document.getElementById('r' + current).checked = true;
}
} else {
// upscroll code
console.log(" up, " + current);
amount = 0;
document.getElementById('r' + current).checked = false;
//If you reach the first radio element you reset the counter
if (current === 1) {
document.getElementById('r' + current).checked = true;
} else {
if (current === max) {
current -= 1;
if( enabaled=== true){
disableScroll();
enabaled=false;
}
} else {
current -= 1;
document.getElementById('r' + current).checked = true;
}
}
}
}
lastScrollTop = st <= 0 ? 0 : st; // For Mobile or negative scrolling
}else {
enableScroll();
}
}, false);
};
<div class="scene44" id="scene44">
<input type="radio" name="buttons" id="r1" checked>
<input type="radio" name="buttons" id="r2">
<input type="radio" name="buttons" id="r3">
<input type="radio" name="buttons" id="r4">
<input type="radio" name="buttons" id="r5">
<input type="radio" name="buttons" id="r6">
<input type="radio" name="buttons" id="r7">
<p class="discp">
We discover your potential.
</p>
<div class="controls">
<label for="r1"><span></span>
<div>LAB & Process Development</div></label>
<label for="r2"><span></span><div>Quality & Regulatory</div></label>
<label for="r3"><span></span><div>Engineering & Project Management</div></label>
<label for="r4"><span></span><div>EHS</div></label>
<label for="r5"><span></span><div>Specialized Services</div></label>
<label for="r6"><span></span><div>Data Science LAB</div></label>
<label for="r7"><span></span><div>Technology & Science LAB</div></label>
</div>
<div class="container" >
<div class="leftimage-container">
<div class="box topleft"></div>
<div class="box backleft"></div>
<div class="box bottomleft"></div>
<div class="box frontleft" ></div>
</div>
<div class="centerimage-container">
<div class="box frontcenter"></div>
<div class="box backcenter"></div>
<div class="box bottomcenter"></div>
<div class="box topcenter"> </div>
</div>
<div class="rightimage-container">
<div class="box topright"></div>
<div class="box backright"></div>
<div class="box bottomright"></div>
<div class="box frontright"></div>
</div>
</div>
</div>
I've faced 2 problems; First, it's not working correctly as you can see.
Second, I logged some text and realized that the snippet code detecting the scroll direction does not work exactly.
How can I fix them?
I want to filter my divs by type of it (hotel/hostel), and the city where it is located. I have added filtering by type of property, but don't know how to add one more filter, and how to make it work good simultaneously. First filter looks like checkboxes, second is radiobuttons.
Divs:
function change() {
var checkboxes = document.getElementsByClassName('checkbox');
var chekboxInputs = Array.from(checkboxes).map(a => a.querySelector('input'));
var allAreUnselected = chekboxInputs.every(function(elem) {
return !elem.checked;
});
if (allAreUnselected) {
chekboxInputs.forEach(function(input) {
Array.from(document.querySelectorAll("." + input.getAttribute("rel"))).forEach(function(item) {
item.style.display = 'block';
});
});
} else {
chekboxInputs.forEach(function(input) {
Array.from(document.querySelectorAll("." + input.getAttribute("rel"))).forEach(function(item) {
item.style.display = input.checked ? 'block' : 'none';
});
});
}
}
change();
<div class="lviv hotel">
<div class="hotel-info">
<p>BonApart Deluxe Hotel</p>
</div>
</div>
<h2>Select Filters</h2>
<h3>Property Type</h3>
<div class="checkbox">
<input type="checkbox" rel="hotel" onchange="change()" />
<p>Hotel</p>
</div>
<div class="checkbox">
<input type="checkbox" rel="hostel" onchange="change()" />
<p>Hostel</p>
</div>
<h3>City</h3>
<div class="radio"><input type="radio" name="cities"> Kyiv</div>
<div class="radio"><input type="radio" name="cities"> Lviv</div>
<div class="radio"><input type="radio" name="cities"> Tokyo</div>
You need to keep track of both the selections separately and finally decide what to show. type is a kind of OR operation as it is allowed to be one of many options. city is must have a property in your div classes.
The following code will work as you expect with both checkboxes and radio buttons. It can be extended as you want.
let types = [];
let city = undefined;
function change() {
var checkboxes = document.getElementsByClassName("checkbox");
types = Array.from(checkboxes)
.filter((a) => a.querySelector("input").checked)
.map((a) => a.querySelector("input").getAttribute("rel"));
var radioButtons = document.getElementsByClassName("radio");
city = Array.from(radioButtons)
.find((a) => a.querySelector("input").checked)
?.querySelector("input")
?.getAttribute("value");
if (types == [] && city == undefined) {
// no filters selected
Array.from(document.querySelectorAll(".item")).forEach(function (
item
) {
item.style.display = "block";
});
} else {
Array.from(document.querySelectorAll(".item")).forEach(function (
item
) {
let itemTags = item
.getAttribute("class")
.split(" ")
.filter((item) => item !== "item");
let visible = true;
if (city) {
visible = itemTags.indexOf(city) >= 0;
}
if (types.length > 0) {
visible =
visible && types.some((item) => itemTags.indexOf(item) >= 0);
}
item.style.display = visible ? "block" : "none";
});
}
}
<html>
<head>
<title>Page Title</title>
</head>
<body>
<div class="lviv hotel item">
<div class="hotel-info">
<p>BonApart Deluxe Hotel</p>
</div>
</div>
<div class="tokyo hostel item">
<div class="hostel-info">
<p>Hostel in Tokyo</p>
</div>
</div>
<h2>Select Filters</h2>
<h3>Property Type</h3>
<div class="checkbox">
<input type="checkbox" rel="hotel" onchange="change()" />
<label>Hotel</label>
</div>
<div class="checkbox">
<input type="checkbox" rel="hostel" onchange="change()" />
<label>Hostel</label>
</div>
<h3>City</h3>
<div class="radio">
<input
type="radio"
value="kyiv"
id="Kyiv"
name="city"
onchange="change()"
/><label for="Kyiv">Kyiv</label><br />
</div>
<div class="radio">
<input
type="radio"
value="lviv"
id="Lviv"
name="city"
onchange="change()"
/><label for="Lviv">Lviv</label><br />
</div>
<div class="radio">
<input
type="radio"
value="tokyo"
id="Tokyo"
name="city"
onchange="change()"
/><label for="Tokyo">Tokyo</label><br />
</div>
<script>
let types = [];
let city = undefined;
function change() {
var checkboxes = document.getElementsByClassName("checkbox");
types = Array.from(checkboxes)
.filter((a) => a.querySelector("input").checked)
.map((a) => a.querySelector("input").getAttribute("rel"));
var radioButtons = document.getElementsByClassName("radio");
city = Array.from(radioButtons)
.find((a) => a.querySelector("input").checked)
?.querySelector("input")
?.getAttribute("value");
if (types == [] && city == undefined) {
// no filters selected
Array.from(document.querySelectorAll(".item")).forEach(function (
item
) {
item.style.display = "block";
});
} else {
Array.from(document.querySelectorAll(".item")).forEach(function (
item
) {
let itemTags = item
.getAttribute("class")
.split(" ")
.filter((item) => item !== "item");
let visible = true;
if (city) {
visible = itemTags.indexOf(city) >= 0;
}
if (types.length > 0) {
visible =
visible && types.some((item) => itemTags.indexOf(item) >= 0);
}
item.style.display = visible ? "block" : "none";
});
}
}
</script>
</body>
</html>
Note that I have added a common CSS class ("item") to all the items you gonna either show or hide, to make it easier to select them easily.
in my JavaScript
$("#inputDatabaseName").on("keyup", function(e) {
alert("Changed!");
console.info(this.value);
var nilaicli = this.value,
skorcli = document.getElementById("skorclis");
var cli1 = parseFloat(nilaicli.value) || 2;
var x = cli1.toFixed(2);
if (x <= 39.99 && x >= 0) {
skorcli.value = 1; //its the only come out and dont want change again if i input another number in inputid="inputDatabaseName". :(
} else if (x >= 40.0 && x <= 59.99) {
skorcli.value = 2;
} else if (x >= 60.0 && x <= 79.99) {
skorcli.value = 3;
} else if (x >= 80.0 && x <= 89.99) {
skorcli.value = 4;
} else if (x >= 90.0 && x <= 100) {
skorcli.value = 5;
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="col-lg-3">
<div class="card card-chart">
<div class="card-header">
<div class="row">
<p> Input CLI</p>
</div>
<div class="card-body">
<div class="row">
<div class="col-8">
<label>Nilai CLI : </label>
<input type="text" name="nama" class="col-sm-4 nilaicli" id="inputDatabaseName">
<br>
</div>
</div>
<div class="row">
<div class="col-8">
<label> Skor CLI : </label>
<input type="text" name="nama" class="col-sm-3" id="skorclis" readonly="true" onkeypress="return onlyNumberKey(event)">
</div>
</div>
</div>
</div>
</div>
</div>
i want change value in inputid="skorclis" again if i input something in inputid="inputDatabaseName".
but my script dont want change value at inputid="skorclis" repeatly. only want the first if statement. and dont want change again. how to make it become change again?
$("#inputDatabaseName").on("keyup", function(e) {
const nilaicli = this.value;
const cli1 = parseFloat(nilaicli) || 2;
const x = cli1.toFixed(2);
hanldeChange(x);
});
const hanldeChange = (x) => {
const skorcli = document.getElementById("skorclis");
console.info(x);
if (x <= 39.99) {
skorcli.value = 1;
} else if (x <= 59.99) {
skorcli.value = 2;
} else if (x <= 79.99) {
skorcli.value = 3;
} else if (x <= 89.99) {
skorcli.value = 4;
} else if (x <= 100) {
skorcli.value = 5;
}
};
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="col-lg-3">
<div class="card card-chart">
<div class="card-header">
<div class="row">
<p> Input CLI</p>
</div>
<div class="card-body">
<div class="row">
<div class="col-8">
<label>Nilai CLI : </label>
<input type="text" name="nama" class="col-sm-4 nilaicli" id="inputDatabaseName">
<br>
</div>
</div>
<div class="row">
<div class="col-8">
<label> Skor CLI : </label>
<input type="text" name="nama" class="col-sm-3" id="skorclis" readonly="true" onkeypress="return onlyNumberKey(event)">
</div>
</div>
</div>
</div>
</div>
</div>
Have look to that:
const myForm = document.querySelector('#my-form') // use a form, it is
// usefull to access on myForm.nilaicli
// element or any one else
myForm.nilaicli.addEventListener('input',function() // use input event, it's also work with mouse copy/paste
{
let x = parseFloat(this.value) || 2
this.value = x // .toFixed(2)
switch (true)
{
case (x >= 0 && x < 40) : myForm.skorclis.value = 1; break;
case (x >= 40 && x < 60) : myForm.skorclis.value = 2; break;
case (x >= 60 && x < 80) : myForm.skorclis.value = 3; break;
case (x >= 80 && x < 90) : myForm.skorclis.value = 4; break;
case (x >= 90 && x <= 100) : myForm.skorclis.value = 5; break;
}
})
myForm.onsubmit = e => e.preventDefault() // disable form submit
fieldset {
display : block;
margin : 1em;
width : 17em;
}
label {
display : block;
margin : 1em;
}
label input {
float : right;
padding : 0 .7em;
width : 9em;
}
<form id="my-form">
<fieldset>
<legend>Input CLI</legend>
<label>
Nilai CLI :
<input type="text" name="nilaicli">
</label>
<label>
Skor CLI :
<input type="text" name="skorclis" readonly >
</label>
</fieldset>
</form>
I'm trying to make personalty quiz in HTML with javascript(no jquery)and I don't know where is my problem.
I know I need to put return false but I don't know were
I don't know how to use value well
function count() {
var first = document.querySelector('input[name=first]').value;
var second = document.querySelector('input[name=second]').value;
var dps = 0;
var tank = 0;
var sup = 0;
if (first == 'dps') {
dps++;
}
if (first == 'tank') {
tank++;
}
if (first == 'sup') {
sup++;
}
if (second == 'dps') {
dps++;
}
if (second == 'tank') {
tank++;
}
if (second == 'sup') {
sup++;
}
var count2;
if (dps > tank && dps > sup) {
count2 = "dps";
}
if (tank > dps && tank > sup) {
count2 = "tank";
}
if (sup > dps && sup > tank) {
count2 = "sup";
}
var result = document.getElementById("motek");
result.innerText = count2;
}
<form id='hello' onsubmit="count()">
<h3>what your favorite food?</h3>
<input type="radio" name="first" value="tank">hghjghj<br>
<input type="radio" name="first" value="dps">hghjfgsfghj<br>
<input type="radio" name="first" value="sup">hghsgdsdqqwj<br>
<h3>what your favoritsfde food?</h3>
<input type="radio" name="second" value="tank">hghfsghj<br>
<input type="radio" name="second" value="dps">hghesfghj<br>
<input type="radio" name="second" value="sup">hghsfdqwj<br>
<input type="submit" value="submit">
</form>
<div id="motek">
</div>
You need to stop the page from reloading.
One great way to prevent reloading the page when submitting using a form is by adding return false with your onsubmit attribute.
In pure Javascript, you can also use: e.preventDefault()
OR you can make your <button type="button">Submit</button> type as button and handle form submit manually on click of this button.
The snippet below shows return false approach.
function count() {
var first = document.querySelector('input[name="first"]:checked').value;
var second = document.querySelector('input[name="second"]:checked').value;
var dps = 0;
var tank = 0;
var sup = 0;
if (first == 'dps') {
dps++;
}
if (first == 'tank') {
tank++;
}
if (first == 'sup') {
sup++;
}
if (second == 'dps') {
dps++;
}
if (second == 'tank') {
tank++;
}
if (second == 'sup') {
sup++;
}
var count2;
if (dps > tank && dps > sup) {
count2 = "dps";
}
if (tank > dps && tank > sup) {
count2 = "tank";
}
if (sup > dps && sup > tank) {
count2 = "sup";
}
var result = document.getElementById("motek");
result.innerText = count2;
}
<form id='hello' onsubmit="count(); return false">
<h3>what your favorite food?</h3>
<input type="radio" name="first" value="tank">hghjghj<br>
<input type="radio" name="first" value="dps">hghjfgsfghj<br>
<input type="radio" name="first" value="sup">hghsgdsdqqwj<br>
<h3>what your favorite food?</h3>
<input type="radio" name="second" value="tank">Tank<br>
<input type="radio" name="second" value="dps">DPS<br>
<input type="radio" name="second" value="sup">SUPP<br>
<input type="submit" value="submit">
</form>
<div id="motek">
</div>
I have a form, which has multiple tabs that displays 10 questions in each one and include (true/false) radio groups (generated by php code, so I don't know their names OR how many will appear), and I need to check whether they are checked or not on next button clicked. If not I want to show the user which question was not answered (no alert message, but it can be in a label with a green or red check icon).
I've tried googling the problem, but none of the previous answers were good to use in my case.
Edit:
This is a part of my code:
<form id="questionForm" action="" method="post" role="form">
<input type="hidden" name="login" value="<?php echo $_SESSION['login-user']?>"/>
<input type="hidden" name="pass_user" value="<?php echo $_SESSION['pass_user']; ?>"/>
<?php
$blocks_questions = array_chunk($questions, 10);
foreach($blocks_questions as $cle=>$question_block) {?>
<div class='tab'>
<?php
foreach ($question_block as $key => $question) {
$id_quiz_qst=$question['id_quiz'].",".$question['id_qst'];?>
<div class="form-group qst-row">
<div class="row">
<div class="col-sm-10"><p><?php echo $question['question'] ?></p>
</div>
<div class="col-sm-2">
<span class="question-rbtn" >
<span class="switch radio-switch fixed-width-lg">
<input name="<?php echo $id_quiz_qst?>" id="<?php echo $id_quiz_qst."_on";?>" value="Vrai" <?php if (isset($_POST[$id_quiz_qst]) && $_POST[$id_quiz_qst]=="Vrai") echo "checked";?> type="radio">
<label for="<?php echo $id_quiz_qst."_on";?>" class="radioCheck">Vrai</label>
<input name="<?php echo $id_quiz_qst?>" id="<?php echo $id_quiz_qst."_off";?>" value="Faux" type="radio" <?php if (isset($_POST[$id_quiz_qst]) && $_POST[$id_quiz_qst]=="Faux") echo "checked";?>>
<label for="<?php echo $id_quiz_qst."_off";?>" class="radioCheck">Faux</label>
<a class="slide-button btn"></a>
<label style="display:inline; float:right; position:absolute; font-size:18px;">
<i class="good icon_check_alt2" style="color:#17944d ;"></i>
<i class="not-good icon_close_alt2" style="color:#ff5032 ;"></i>
</label>
</span>
</span>
</div>
</div>
</div>
<?php } ?>
</div>
<?php
} ?>
<div style="overflow:auto;">
<div class="text-center">
<a class="next-prev" id="prevBtn" onclick="nextPrev(-1)"><i class="fa arrow_carrot-2left_alt "></i></a>
<a class="next-prev" id="nextBtn" onclick="nextPrev(1)"><i class="fa arrow_carrot-2right_alt"></i></a>
</div>
</div>
<!-- Circles which indicates the steps of the form: -->
<div style="text-align:center;margin-top:10px;">
<span class="step"></span><span class="step"></span><span class="step"></span><span class="step"></span><span class="step"></span>
</div>
<div id="submit-area" class="text-center">
<button id="submit_answers" name="submit_answers" type="submit" onclick="myfunc();" class="btn btn-primary btn-lg">Valider</button>
<button type="reset" class="btn btn-primary btn-lg">Annuler</button>
</div>
</form>
<script>
var currentTab = 0; // Current tab is set to be the first tab (0)
showTab(currentTab); // Display the current tab
function showTab(n) {
// This function will display the specified tab of the form...
var x = document.getElementsByClassName("tab");
x[n].style.display = "block";
//... and fix the Previous/Next buttons:
if (n == 0) {
document.getElementById("prevBtn").style.display = "none";
} else {
document.getElementById("prevBtn").style.display = "inline";
}
if (n == (x.length - 1)) {
document.getElementById("submit-area").style.display="block";
document.getElementById("nextBtn").style.display = "none";
} else {
document.getElementById("nextBtn").style.display = "inline";
}
//... and run a function that will display the correct step indicator:
fixStepIndicator(n)
}
function nextPrev(n) {
// This function will figure out which tab to display
var x = document.getElementsByClassName("tab");
// Exit the function if any field in the current tab is invalid:
if (n == 1 && !validateForm()) return false;
// Hide the current tab:
x[currentTab].style.display = "none";
// Increase or decrease the current tab by 1:
currentTab = currentTab + n;
// if you have reached the end of the form...
if (currentTab >= x.length) {
// ... the form gets submitted:
document.getElementById("questionForm").submit();
return false;
}
// Otherwise, display the correct tab:
showTab(currentTab);
}
x = document.getElementsByClassName("tab");
y = x[currentTab].getElementsByTagName("input");
function changeColor(){
x = document.getElementsByClassName("tab");
y = x[currentTab].getElementsByTagName("input");
}
function validateForm() {
// This function deals with validation of the form fields
var x, y, i, good, not_good, valid = true;
x = document.getElementsByClassName("tab");
y = x[currentTab].getElementsByTagName("input");
good = document.getElementsByClassName("good");
not_good = document.getElementsByClassName("not-good");
// A loop that checks every input field in the current tab:
// alert(y[0].getElementById("btv").name);
var indexinc =0;
for (i = 0; i < y.length; i++) {
// If a field is empty...
//y[i].parentNode.className = y[i].parentNode.className.replace("invalid","");
if (!y[i].checked) {
indexinc++;
// add an "invalid" class to the field:
not_good[i].style.display="block";
// and set the current valid status to false
valid = false;
}
else{
good[i].style.display="block";
valid = true;
}
}
if(indexinc == 10)//Verify that he did answer all 22 questions and check that we have the 22 inputs not 44 inputs (vrai/faux)
valid = true;
// If the valid status is true, mark the step as finished and valid:
if (valid) {
document.getElementsByClassName("step")[currentTab].className += " finish";
}
return valid; // return the valid status
}
function fixStepIndicator(n) {
// This function removes the "active" class of all steps...
var i, x = document.getElementsByClassName("step");
for (i = 0; i < x.length; i++) {
x[i].className = x[i].className.replace(" active", "");
}
//... and adds the "active" class on the current step:
x[n].className += " active";
}
</script>
You can evaluate this with your html structure, using querySelectorAll and verifying that at least one radio button of a section is selected, this functions will work but I would recommend them to put them in a class, or a IIFE, to avoid declaring them in the global scope...
function nextTab(e) {
if (validate(e)){
console.log("go to next tab");
}
}
function validate(element) {
let val = true;
let select = element.closest("section");
select.querySelectorAll('.radio-container').forEach(function(container){
let radioChecked = container.querySelectorAll("input:checked");
container.style.backgroundColor = "white";
if(!radioChecked.length) {
val = val && false;
container.style.backgroundColor = "red";
}
});
return val;
}
<section id="tab1">
<div class="radio-container">
<input type="radio" name="gender" value="male"> Male
<input type="radio" name="gender" value="female"> Female
<input type="radio" name="gender" value="other"> Other
</div>
<div class="radio-container">
<input type="radio" name="gender1" value="male"> Male
<input type="radio" name="gender1" value="female"> Female
<input type="radio" name="gender1" value="other"> Other
</div>
<div class="radio-container">
<input type="radio" name="gender2" value="male"> Male
<input type="radio" name="gender2" value="female"> Female
<input type="radio" name="gender2" value="other"> Other
</div>
<button type="button" onclick="nextTab(this)">Continue</button>
</section>
UPDATE
You could use the same idea in your case you can get the tab section with your currentTab variable, within this tab you can get all your ".question-rbtn" elements, and with these elements you can verify if at least one radio button is checked...
function nextPrev(n) {
// Validate radio buttons
if(!validate()) return;
// This function will figure out which tab to display
var x = document.getElementsByClassName("tab");
// Exit the function if any field in the current tab is invalid:
if (n == 1 && !validateForm()) return false;
// Hide the current tab:
x[currentTab].style.display = "none";
// Increase or decrease the current tab by 1:
currentTab = currentTab + n;
// if you have reached the end of the form...
if (currentTab >= x.length) {
// ... the form gets submitted:
document.getElementById("questionForm").submit();
return false;
}
// Otherwise, display the correct tab:
showTab(currentTab);
}
function validate() {
let val = true;
let select = document.getElementsByClassName("tab")[currentTab];
select.querySelectorAll('.question-rbtn').forEach(function(container)
{
let radioChecked = container.querySelectorAll("input:checked");
container.style.backgroundColor = "white";
if(!radioChecked.length) {
val = val && false;
container.style.backgroundColor = "red";
}
});
return val;
}