reorder radio button list - javascript

I have the below radio button list which is based on a multiple choice question, the information in the list will be added by a non technical user, I would like to know is there a method that i can use so the the list can be suffeled, each time the page has been loaded
<fieldset id="question1">
<div id="scenario">
QUESTION
</div>
<br/><br/>
<div>
Please select the correct answer:
</div>
<label>
<input type="radio" name="q1" value="correct"> ANSWER ONE</input>
</label>
<br/>
<label>
<input type="radio" name="q1" value="wrong"> ANSWER TWO</input>
</label>
<br/>
<label>
<input type="radio" name="q1" value="wrong"> ANSWER THREE</input>
</label>
<br/>
<br/>
<div id="result"></div>
<br/><br/>
<button type="button" id="answer" class="check" onclick="mark();" >Submit</button>
</fieldset>

try this...
You need to add all labels under one div.
<div class="list">
<label>
<input type="radio" name="q1" value="correct"> ANSWER ONE </input>
<br />
</label>
<label> <input type="radio" name="q1" value="wrong"> ANSWER TWO </input>
<br />
</label>
<label>
<input type="radio" name="q1" value="wrong"> ANSWER THREE </input>
<br/>
</label>
</div>
Add following code in new shuffle.js file
(function($){
$.fn.shuffle = function() {
var allElems = this.get(),
getRandom = function(max) {
return Math.floor(Math.random() * max);
},
shuffled = $.map(allElems, function(){
var random = getRandom(allElems.length),
randEl = $(allElems[random]).clone(true)[0];
allElems.splice(random, 1);
return randEl;
});
this.each(function(i){
$(this).replaceWith($(shuffled[i]));
});
return $(shuffled);
};
})(jQuery);
call to shuffle.js file Add following line of code in script tag to shuffle
<script>
$(document).ready(function(){
$( '.list label' ).shuffle();
});
</script>

if the answer are in array you can use this method
function Shuffle(o) {
for(var j, x, i = o.length; i; j = parseInt(Math.random() * i), x = o[--i], o[i] = o[j], o[j] = x);
return o;
};
then you can call like this
var testArray = [1,2,3,4,5];
Shuffle(testArray);
for more details you can visti this link

What you need to do is:
Wrap all your answer labels in a div element, something like <div id="answers"></div>
Dispose of a <br /> elements between labels, instead specifying a style label {display: block;};
Apply following Javascript code
(with jQuery):
jQuery(function($){
var answers = $("#answers");
answers.html(
answers.find("label").sort(function(){
return Math.round(Math.random())-0.5;
})
);
});
And you're good to go.
Here's 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>

Change the value of a variable depending on a radio button

I have a variable called genderMultiplier which is used in this calculation
const bloodAlcoholContent = (gramsOfAlcohol / ((weight * 1000) * genderMultiplyer))*100;
My genderMultiplier can have 2 values and I have made a radio input for that in HTML
<div class="gender-buttons" id="gender-buttons">
<input class="gender-button" type="radio" name="tools" id="tool-1" value="0.55" checked>
<label class="for-gender-button" for="tool-1">Male</label>
<input class="gender-button" type="radio" name="tools" id="tool-2" value="0.68">
<label class="for-gender-button" for="tool-2">Female</label>
</div>
const genderButtonElement = document.getElementById("gender-buttons")
const genderMultiplyer = parseFloat(genderButtonElement.input);
One radio button is [MALE] and [FEMALE]. So if the user clicks Male then I want the genderMultiplier to be 0.55 and if the user clicks Female then I want the genderMultiplier to be 0.68
Any advice on this?
Change your last line to
const genderMultiplier = parseFloat([...genderButtonElement.children].find(c=>c.checked).value)
To calculate bloodAlcoholContent, you need to know the values gramsOfAlcohol and weight. But you did not show the method for calculating these variables.
const genderButtonElement = document.querySelectorAll('.gender-buttons .gender-button');
genderButtonElement.forEach(function(current, index) {
current.addEventListener('click', function() {
const genderMultiplyer = parseFloat(current.value);
console.log(genderMultiplyer);
});
});
<div class="gender-buttons" id="gender-buttons">
<input class="gender-button" type="radio" name="tools" id="tool-1" value="0.55" checked>
<label class="for-gender-button" for="tool-1">Male</label>
<input class="gender-button" type="radio" name="tools" id="tool-2" value="0.68">
<label class="for-gender-button" for="tool-2">Female</label>
</div>
function getMultiplier()
{
const genderMultiplyer = parseFloat(document.querySelector('input[name="tools"]:checked').value);
alert("The multiplier is: " + genderMultiplyer);
}
<div class="gender-buttons" id="gender-buttons">
<input class="gender-button" type="radio" name="tools" id="tool-1" value="0.55" checked>
<label class="for-gender-button" for="tool-1">Male</label>
<input class="gender-button" type="radio" name="tools" id="tool-2" value="0.68">
<label class="for-gender-button" for="tool-2">Female</label>
</div>
<button onclick="getMultiplier()">Get Multiplier</button>
The pure Javascript way of doing this in your example is as follows:
const genderMultiplyer = parseFloat(document.querySelector('input[name="tools"]:checked').value);
If your are using JQuery you can get it this way:
const genderMultiplyer = parseFloat($('input[name="tools"]:checked').val());

How can I show messages depending on selected radio buttons?

I am struggling to find a way how to display information based on two options in a forms.
What I mean is, there are two options in "Select Gender". If they choose "Male", then a paragraph should appear. If they choose "Female", then another paragraph should appear on the website. How can I do this?
This is the forms code:
<form>
Select Gender
<br />
<input type="radio" name="gender" id="male">
<label for="male">Male</label>
<br />
<input type="radio" name="gender" id="female">
<label for="female">Female</label>
<br />
<br />
</form>
Use CSS only
Note that I added divs around your inputs and the .popup-descriptions, otherwise this does not work.
.popup-description{
display: none;
}
[type="radio"]:checked ~ label ~ .popup-description{
display: block;
}
<form>
Select Gender
<div>
<input type="radio" name="gender" id="male">
<label for="male">Male</label>
<p class="popup-description">
This text is shown when the user selects <b>male</b>.
</p>
</div>
<div>
<input type="radio" name="gender" id="female">
<label for="female">Female</label>
<p class="popup-description">
This text is shown when the user selects <b>female</b>.
</p>
</div>
</form>
Use javascript with jQuery
Note that I added a value to your inputs, otherwise this does not work.
$(document).ready(function(){
$("[name='gender']").on("change", function(){
var v = $(this).val();
var n = $(this).attr("name");
$(".popup-description[data-for='" + n + "']").hide();
$(".popup-description[data-for='" + n + "'][data-selected-value='" + v + "']").show();
});
});
.popup-description{
display: none;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form>
Select Gender
<br />
<input type="radio" name="gender" id="male" value="male">
<label for="male">Male</label>
<p class="popup-description" data-for="gender" data-selected-value="male">
This text is shown when the user selects <b>male</b>.
</p>
<br />
<input type="radio" name="gender" id="female" value="female">
<label for="female">Female</label>
<p class="popup-description" data-for="gender" data-selected-value="female">
This text is shown when the user selects <b>female</b>.
</p>
<br />
</form>
Use plain javascript
Note that I added a value to your inputs, otherwise this does not work.
(function(){
var radios = document.querySelectorAll("[name='gender']");
if(radios !== null){
for(var i = 0; i < radios.length; i++){
var el = radios.item(i);
el.addEventListener("change", function(){
if(this.checked){
var v = this.value;
var n = this.name;
var h = document.querySelectorAll(".popup-description[data-for='" + n + "']");
if(h !== null){
for(var j = 0; j < h.length; j++){
var e = h.item(j);
if(e.getAttribute("data-selected-value") == v){
e.style.display = "block";
}
else{
e.style.display = "none";
}
}
}
}
});
}
}
})();
.popup-description{
display: none;
}
<form>
Select Gender
<br />
<input type="radio" name="gender" id="male" value="male">
<label for="male">Male</label>
<p class="popup-description" data-for="gender" data-selected-value="male">
This text is shown when the user selects <b>male</b>.
</p>
<br />
<input type="radio" name="gender" id="female" value="female">
<label for="female">Female</label>
<p class="popup-description" data-for="gender" data-selected-value="female">
This text is shown when the user selects <b>female</b>.
</p>
<br />
</form>

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

How can i convert checkboxes into dropdown list?

I have few checkboxes and I want to convert them into dropdown list. I tried something but don't know at the end what to do?
<form id="form-wysija-2" class="widget_wysija" action="#wysija" method="post">
<p class="wysija-checkbox-label">Select list(s):</p>
<p class="wysija-checkbox-paragraph">
<label>
<input class="wysija-checkbox validate[required]" type="checkbox" value="1" name="wysija[user_list][list_id][]">
General Antiques
</label>
</p>
<p class="wysija-checkbox-paragraph">
<label>
<input class="wysija-checkbox validate[required]" type="checkbox" value="3" name="wysija[user_list][list_id][]">
Antique & Collectible Tools
</label>
</p>
</form>
and i tried following jQuery to convert these checkboxes into dropdown list. but don't getting to how to done this successfully.
jQuery(document).ready(function($){
var extra, checkBoxesName,
checkBoxlabel,
checkBoxes = $('.wysija-checkbox-paragraph');
var checkBoxesLabel = $('.wysija-checkbox-label');
checkBoxesName = checkBoxes.find('input').prop('name');
checkBoxlabel = checkBoxes.find('label').text();
checkBoxesLabel.append('<select name="'+checkBoxesName+'">'+extra+'</select>');
$('.wysija-checkbox-paragraph').each(function(n){
var dataText = $(this).find('label').text();
$('select[name='+checkBoxesName+']').append('<option value="'+n+'">'+dataText+'</option>');
});
//checkBoxes.remove();
});
Try this:
var checkBoxes = $('.wysija-checkbox-paragraph'),
checkBoxesLabel = $('.wysija-checkbox-label'),
checkBoxesName = checkBoxes.find('input').prop('name')
$select = $('<select name="' + checkBoxesName + '"></select>').appendTo(checkBoxesLabel);
checkBoxes.each(function (n) {
var dataText = $(this).find('label').text();
var dataValue = $(this).find('input').val();
$select.append('<option value="' + dataValue + '">' + dataText + '</option>');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="form-wysija-2" class="widget_wysija" action="#wysija" method="post">
<p class="wysija-checkbox-label">Select list(s):</p>
<p class="wysija-checkbox-paragraph">
<label>
<input class="wysija-checkbox validate[required]" type="checkbox" value="1" name="wysija[user_list][list_id][]" /> General Antiques
</label>
</p>
<p class="wysija-checkbox-paragraph">
<label>
<input class="wysija-checkbox validate[required]" type="checkbox" value="3" name="wysija[user_list][list_id][]" /> Antique & Collectible Tools
</label>
</p>
</form>
Note, that since checkboxes allow to select multiple values, you might want to add multiple attribute to selectbox, in order to allow the same behavior.
jQuery(document).ready(function($){
var extra, checkBoxesName,
checkBoxlabel,
checkBoxes = $('.wysija-checkbox-paragraph');
var checkBoxesLabel = $('.wysija-checkbox-label');
checkBoxesName = checkBoxes.find('input').prop('name');
checkBoxlabel = checkBoxes.find('label').text();
checkBoxesLabel.append('<select name="'+checkBoxesName+'">'+extra+'</select>');
$('.wysija-checkbox-paragraph').each(function(n){
var dataText = $(this).find('label').text();
$('.wysija-checkbox-paragraph').append('<select name="'+checkBoxesName+']" > <option value="'+n+'">'+dataText+'</option></select>');
});
//checkBoxes.remove();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<form id="form-wysija-2" class="widget_wysija" action="#wysija" method="post">
<p class="wysija-checkbox-label">Select list(s):</p>
<p class="wysija-checkbox-paragraph">
<label>
<input class="wysija-checkbox validate[required]" type="checkbox" value="1" name="wysija[user_list][list_id][]">
General Antiques
</label>
</p>
<p class="wysija-checkbox-paragraph">
<label>
<input class="wysija-checkbox validate[required]" type="checkbox" value="3" name="wysija[user_list][list_id][]">
Antique & Collectible Tools
</label>
</p>
</form>

Categories