Save Radio Box Value in Variables - javascript

I want to save the checked values of the radio boxes but when I try to submit the button and redirect to a url based on the 3 choices it doesnt work. I debugged it, and apparently the problem is that my program is only saving the last value in the variable but not the values before. What can I do to save all the choices in 3 different variables?
HTML:
<div id="schritt1">
<p stlye="text-align:center;">frage 1</p>
<input id="1a" type="radio" name="a" value="eins" onclick="checkedvalue('a')"/>
<label for="1a">1</label><br/>
<input id="1b" type="radio" name="a" value="zwei" onclick="checkedvalue('a')"/>
<label for="1b">2</label></br>
<input id="1c" type="radio" name="a" value="drei" onclick="checkedvalue('a')"/>
<label for="1c">3</label>
</div>
<div id="schritt2" style="display:none;">
<p stlye="text-align:center;">Frage 2</p>
<input id="2a" type="radio" name="b" value="zweieins" onclick="checkedvalue('b')"/>
<label for="2a">1</label><br/>
<input id="2b" type="radio" name="b" value="zweizwei" onclick="checkedvalue('b')"/>
<label for="2b">2</label></br>
<input id="2c" type="radio" name="b" value="zweidrei" onclick="checkedvalue('b')"/>
<label for="2c">3</label>
</div>
<div id="schritt3" style="display:none;">
<p stlye="text-align:center;">Frage 3</p>
<input id="2a" type="radio" name="c" value="dreieins" onclick="checkedvalue('c')"/>
<label for="2a">1</label><br/>
<input id="2b" type="radio" name="c" value="dreizwei" onclick="checkedvalue('c')"/>
<label for="2b">2</label></br>
<input id="2c" type="radio" name="c" value="dreidrei" onclick="checkedvalue('c')"/>
<label for="2c">3</label>
</div>
<div id="finish-button" style="display:none;">
<a class="btn btn-buy" onclick="checkedvalue('finish')">Ergebnis</a>
</div>
JS:
<script>
function checkedvalue(choice){
var eins;
var zwei;
var drei;
if(choice == "a") {
eins = (jQuery('input[name=a]:checked').val());
window.alert(eins);
document.getElementById('schritt1').style.display = 'none';
document.getElementById('schritt2').style.display = 'block';
}
else if(choice == "b") {
zwei = (jQuery('input[name=b]:checked').val());
window.alert(zwei);
window.alert(eins + zwei);
document.getElementById('schritt2').style.display = 'none';
document.getElementById('schritt3').style.display = 'block';
document.getElementById('finish-button').style.display = 'block';
}
else if(choice == "c") {
drei = (jQuery('input[name=c]:checked').val());
}
else if(choice == "finish") {
window.alert(eins + zwei + drei);
if(eins == "eins" && zwei == "zweieins" && drei == "dreieins" )
{
console.log("If 2 works");
window.location.href = "//";
}
}
}

The issue is every time this onclick() method is calling and refreshing the Javascript method.So it will be loose the previously saved values.
You can Collect all the radio Button group values At the time of form submitting using
var eins;
var zwei;
var drei;
declare these variable globally(Outside of all functions) and add below code inside form submit method (write a OnSubmit method in your submit button and write the code inside )
$('input:radio').each(function() {
if($(this).is(':checked')) {
// You have a checked radio button here...
var val = $(this).val();
var name = $(this).attr('name');
if(name=="a")
{
eins=val;
}
else if(name=="b")
{
zwei=val;
}
else
{
drei=val;
}
}
else {
// Or an unchecked one here...
}
});
I didn't test the code,So modify as per your requirements.

Related

Div not showing when radio button checked

I have a radio button that will show a div with an input text when it is checked 'NO'. But it is not showing the div, however when I play around the radio button then the div will show. Where am I missing?
function CheckboxCheck(checkbox) {
var firstCheckbox = document.getElementById('check1');
var secondCheckbox = document.getElementById('check2');
var rmk = document.getElementById("rmk");
if (firstCheckbox.checked == true) {
rmk.style.display = "none";
} else if (secondCheckbox.checked == true) {
rmk.style.display = "block";
document.getElementById("rmk").required = true;
}
}
<div>
<label>Have you registered the course?</label>
<table border=0>
<tr>
<td>YES </td>
<td><input type="radio" name="register" value="Y" id="check1" onclick="CheckboxCheck('first')">  </td>
<td>NO </td>
<td><input type="radio" name="register" value="N" checked id="check2" onclick="CheckboxCheck('second')"></td>
</table>
</div>
<div id="rmk" style="display:none">
<label>Reasons</label>
<input type="text" name="remarks" class="form-control">
</div>
There are a few structure and accessibility proposals going on in this suggestion but I think strictly speaking, the easiest solve for you is to invoke the function on page load. Give this example a look:
function CheckboxCheck(checkbox) {
var firstCheckbox = document.getElementById('check1');
var secondCheckbox = document.getElementById('check2');
var rmk = document.getElementById("rmk");
var rmkdiv = document.getElementById("rmk-div");
if (firstCheckbox.checked == true) {
rmkdiv.style.display = "none";
} else if (secondCheckbox.checked == true) {
rmkdiv.style.display = "block";
rmk.required = true;
}
}
CheckboxCheck()
<div>
<p>Have you registered the course?</p>
<label>
YES<input
type="radio"
name="register"
value="Y"
id="check1"
onclick="CheckboxCheck()"
/></label>
<label>NO
<input
type="radio"
name="register"
value="N"
checked
id="check2"
onclick="CheckboxCheck()"
/>
</label>
<div id="rmk-div" style="display: none">
<label>Reasons</label>
<input id="rmk" type="text" name="remarks" class="form-control" />
</div>
</div>
Your input field will only be visible when the function CheckboxCheck is executed. Since "NO" is checked from the beginning, the function will not be executed because it is only called when a change takes place.

Link Radiobox button to Input

I have 2 radio button, each valued Yes and No respectively and 1 textbox.. If I checked on No button, the input textbox will open. If checked on Yes, textbox will disabled.
This code is working fine but I want to delete content that input to the textbox if the user checked Yes
function ismcstopu() {
var chkNo = document.getElementById("radio2_ismcstop");
var mcnostopreason = document.getElementById("mcnostopreason");
mcnostopreason.disabled = chkNo.checked ? false : true;
if (!mcnostopreason.disabled) {
mcnostopreason.focus();
} else {
mcnostopreason.val('');
}
}
<input type="radio" class="form-check-input" id="radio1_ismcstop" name="ismcstop" onclick="ismcstopu()" value="Yes">Yes
<input type="radio" class="form-check-input" id="radio2_ismcstop" name="ismcstop" onclick="ismcstopu()" value="No">No
<label for="mcnostopreason">If No, Reason:</label>
<input class="inputstyle-100" type="text" id="mcnostopreason" name="mcnostopreason" value="" disabled>
.val is a jQuery construct but you are using DOM
Here is a better version using eventListener
Change the document.getElementById("container") to whatever container you have (your form for example)
Note: It is often better to test true than to test false
I also added labels to the radios so we can click the yes or no too
document.getElementById("container").addEventListener("click", function(e) {
const tgt = e.target;
if (tgt.name === "ismcstop") {
const mcnostopreason = document.getElementById("mcnostopreason");
mcnostopreason.disabled = tgt.value === "Yes";
if (mcnostopreason.disabled) {
mcnostopreason.value = '';
} else {
mcnostopreason.focus();
}
}
})
<div id="container">
<label><input type="radio" class="form-check-input" id="radio1_ismcstop" name="ismcstop" value="Yes">Yes</label>
<label><input type="radio" class="form-check-input" id="radio2_ismcstop" name="ismcstop" value="No">No</label>
<label for="mcnostopreason">If No, Reason:
<input class="inputstyle-100" type="text" id="mcnostopreason" name="mcnostopreason" value="" disabled>
</label>
</div>
jQuery version
$("[name=ismcstop]").on("click", function() {
if (this.name === "ismcstop") {
const $mcnostopreason = $("#mcnostopreason");
$mcnostopreason.prop("disabled", this.value === "Yes");
if ($mcnostopreason.is(":disabled")) {
$mcnostopreason.val("");
} else {
$mcnostopreason.focus();
}
}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<label><input type="radio" class="form-check-input" id="radio1_ismcstop" name="ismcstop" value="Yes">Yes</label>
<label><input type="radio" class="form-check-input" id="radio2_ismcstop" name="ismcstop" value="No">No</label>
<label for="mcnostopreason">If No, Reason:
<input class="inputstyle-100" type="text" id="mcnostopreason" name="mcnostopreason" value="" disabled>
</label>
mcnostopreason is not a jQuery object. therefore you could do: var mcnostopreason = $("#mcnostopreason");
Or you could just change mcnostopreason.val('') to mcnostopreason.value = '' ( this will mean you don't need to change anything else)

check if at least one radio button is selected from inputs with the same class javascript

I am trying to make a small quiz web app using javascript/html. The individual questions on the page are separated by div tags with the same "quiz" class. There are 2 buttons on the page, a previous and a next button. Depending on what the user clicks, the page will display the next quiz on the page by hiding/showing the divs. What I am trying to do is add an input validation to the application. Before the user moves onto the next question I want to make it so that one radio button must be selected, otherwise show an alert box. The radio buttons that belong to the same question all have the same class (i.e. the radio buttons for question 1 all have the same class quiz1). Currently app is able to check which input has been selected (by using if element.checked). Following this logic, I tried using if(!element.checked) create an alert, however the alert box get stuck in a loop. Thus, so far the only other solution I have been able to come up with is to check if at least one radio button within the same class has been selected, which I am unsure how to achieve.
let savedAns = [];
const nextBtn = document.getElementById('next');
const prevBtn = document.getElementById('prev');
const quizes = document.querySelectorAll('.quiz');
const form = document.querySelector('form');
const inputEl = document.querySelectorAll('input');
const total = quizes.length;
//a variable to increment the classes
let ind = 0;
//get all the input elements for each question, assign a class
quizes.forEach(function(element) {
ind++;
let inputs = element.querySelectorAll('input');
inputs.forEach((input) => {
input.classList.add(`quiz${ind}`)
})
})
//keep a track of which question is visible
let count = 0;
//function to hide all the quizes
const hide = function() {
quizes.forEach((element) => {
element.style.display = 'none'
})
}
//show and hide divs when user presses next
nextBtn.addEventListener('click', function() {
if (count < total - 1) {
inputEl.forEach(function(element) {
if (element.checked) {
savedAns[count] = element.value;
console.log(savedAns)
}
})
count++;
} else {
inputEl.forEach(function(element) {
if (element.checked) {
savedAns[count] = element.value;
console.log(savedAns)
}
})
alert('no more questions left')
return
}
hide();
quizes[count].style.display = 'block'
})
prevBtn.addEventListener('click', function() {
if (count > 0) {
count--;
} else {
alert('no more previous questions')
return
}
hide();
quizes[count].style.display = 'block'
})
<div class="content">
<form>
<div class="quiz">
<p>Question 1</p>
<input type="radio" name="answer" value="1">
<input type="radio" name="answer" value="2">
<input type="radio" name="answer" value="3">
</div>
<div class="quiz" style="display: none;">
<p>Question 2</p>
<input type="radio" name="answer" value="1">
<input type="radio" name="answer" value="2">
<input type="radio" name="answer" value="3">
</div>
<div class="quiz" style="display: none;">
<p>Question 3</p>
<input type="radio" name="answer" value="1">
<input type="radio" name="answer" value="2">
<input type="radio" name="answer" value="3">
</div>
<div class="quiz" style="display: none;">
<p>Question 4</p>
<input type="radio" name="answer" value="1">
<input type="radio" name="answer" value="2">
<input type="radio" name="answer" value="3">
</div>
</form>
<button id="prev">Prev</button>
<button id="next">Next</button>
</div>
If there are any other ways to solve the problem, hints towards the right direction is greatly appreciated. I am also writing this application using purely javascript so no jquery please. Thank you.
Since you already know which question is active currently, you can check if any of the input under the active question is checked.
let selectedAnswer = -1;
const activeInputs = quizes[count].querySelectorAll('input');
activeInputs.forEach((input, index) => {
if(input.checked) selectedAnswer = index;
});
if (selectedAnswer === -1) {
alert('Select answer');
return;
}
below is the working code snippet.
let savedAns = [];
const nextBtn = document.getElementById('next');
const prevBtn = document.getElementById('prev');
const quizes = document.querySelectorAll('.quiz');
const form = document.querySelector('form');
const inputEl = document.querySelectorAll('input');
const total = quizes.length;
//a variable to increment the classes
let ind = 0;
//get all the input elements for each question, assign a class
quizes.forEach(function(element) {
ind++;
let inputs = element.querySelectorAll('input');
inputs.forEach((input) => {
input.classList.add(`quiz${ind}`)
})
})
//keep a track of which question is visible
let count = 0;
//function to hide all the quizes
const hide = function() {
quizes.forEach((element) => {
element.style.display = 'none'
})
}
//show and hide divs when user presses next
nextBtn.addEventListener('click', function() {
let selectedAnswer = -1;
const activeInputs = quizes[count].querySelectorAll('input');
activeInputs.forEach((input, index) => {
if(input.checked) selectedAnswer = index;
});
if (selectedAnswer === -1) {
alert('Select answer');
return;
}
if (count < total - 1) {
inputEl.forEach(function(element) {
if (element.checked) {
savedAns[count] = element.value;
console.log(savedAns)
}
})
count++;
} else {
inputEl.forEach(function(element) {
if (element.checked) {
savedAns[count] = element.value;
console.log(savedAns)
}
})
alert('no more questions left')
return
}
hide();
quizes[count].style.display = 'block'
})
prevBtn.addEventListener('click', function() {
if (count > 0) {
count--;
} else {
alert('no more previous questions')
return
}
hide();
quizes[count].style.display = 'block'
})
<div class="content">
<form>
<div class="quiz">
<p>Question 1</p>
<input type="radio" name="answer" value="1">
<input type="radio" name="answer" value="2">
<input type="radio" name="answer" value="3">
</div>
<div class="quiz" style="display: none;">
<p>Question 2</p>
<input type="radio" name="answer" value="1">
<input type="radio" name="answer" value="2">
<input type="radio" name="answer" value="3">
</div>
<div class="quiz" style="display: none;">
<p>Question 3</p>
<input type="radio" name="answer" value="1">
<input type="radio" name="answer" value="2">
<input type="radio" name="answer" value="3">
</div>
<div class="quiz" style="display: none;">
<p>Question 4</p>
<input type="radio" name="answer" value="1">
<input type="radio" name="answer" value="2">
<input type="radio" name="answer" value="3">
</div>
</form>
<button id="prev">Prev</button>
<button id="next">Next</button>
</div>

Several input checkbox using one JS with different var

I have 3 input checkboxes. Each of them displays a div if checked. Because the three has the same JS I have decided to have just one JS including 3 variables (one per input) but it is not working. Before I had three independent JS and it worked fine.
CODE
document.getElementById()
var cb1 = document.getElementById('checkbox1'); checkbox1.onchange = {
if (checkbox1.checked) {
course1.style.display = 'block';
} else {
course1.style.display = 'none';
};
var cb2 = document.getElementById('checkbox2'); checkbox2.onchange = {
if (checkbox2.checked) {
course2.style.display = 'block';
} else {
course2.style.display = 'none';
};
var cb3 = document.getElementById('checkbox3'); checkbox3.onchange = {
if (checkbox3.checked) {
course3.style.display = 'block';
} else {
course3.style.display = 'none';
};
<form>
<label class="switch">
<input type="checkbox" id="checkbox1"> Course 1
</label>
</form>
<form>
<label class="switch">
<input type="checkbox" id="checkbox2"> Course 2
</label>
</form>
<form>
<label class="switch">
<input type="checkbox" id="checkbox3"> Course 3
</label>
</form>
<br>
<div id ="course1">
Text course 1
</div>
<br>
<div id ="course2">
Text course 2
</div>
<br>
<div id ="course3">
Text course 3
</div>
Fiddle: https://codepen.io/antonioagar1/pen/YOwBeE?editors=1010
After fixing your syntax errors (identation is very imporant, if it was correct in your code you would had see that you have many if statements not closing correclty)
Well, besides those errors, I managed a way to you that you only need a single function to achieve your desired result.
If you see in the HTML part, you'll note that I added some new attributes to checkboxes and divs, called data-idCheck, where the checkbox with data-idCheck will display the div whose have that same attribute.
Check below to see if my code helps you.
var cb1 = document.getElementById('checkbox1');
cb1.onchange = checkChecked;
var cb2 = document.getElementById('checkbox2');
cb2.onchange = checkChecked;
var cb3 = document.getElementById('checkbox3');
cb3.onchange = checkChecked;
function checkChecked(){
let idCheck = this.getAttribute("data-idCheck");
let relatedDiv = document.querySelector("div[data-idCheck='" + idCheck + "']");
if (this.checked) {
relatedDiv.style.display = 'block';
} else {
relatedDiv.style.display = 'none';
}
}
.hiddenDiv{
display: none;
}
<form>
<label class="switch">
<input type="checkbox" id="checkbox1" data-idCheck="1"> Course 1
</label>
</form>
<form>
<label class="switch">
<input type="checkbox" id="checkbox2" data-idCheck="2"> Course 2
</label>
</form>
<form>
<label class="switch">
<input type="checkbox" id="checkbox3" data-idCheck="3"> Course 3
</label>
</form>
<br>
<div id ="course1" class="hiddenDiv" data-idCheck="1">
Text course 1
</div>
<br>
<div id ="course2" class="hiddenDiv" data-idCheck="2">
Text course 2
</div>
<br>
<div id ="course3" class="hiddenDiv" data-idCheck="3">
Text course 3
</div>

how to make an image disappear by clicking on word?

I'm trying to create a small game . I have four pics of animals and blow the pic i have four names . what the game suppose to do is when the users click on right image and right name both the image and the name has to disappear. But in my case just the image disappear. Any help really appreciate it .
var selectedImage;
var selectedName;
//Change the value of the selectedImage and check the values
function selectImage(event){
selectedImage = event.target;
checkValues();
}
//Change the value of the selectedName and check the values
function selectName(event){
selectedName = event.target;
checkValues();
}
function checkValues() {
console.log(selectedImage);
console.log(selectedName);
//Check if both values are selected
if (!selectedImage || selectedImage == 'undefined' || !selectedName || selectedName == 'undefined'){
return ;
}
//Check if values are equals
if (selectedImage.value == selectedName.value) {
alert("good");
//remove the button and the image
selectedImage.parentNode.style.display = 'none';
selectedName.style.display = 'none';
} else {
alert("no");
}
//Reset the selected image and name.
selectedImage = 'undefined';
selectedName = 'undefined';
}
<div class="content">
<form>
<input type="radio" name="animals" id="cow" class="input-hidden" value="cow"/>
<label for="cow">
<img src="images/cow.jpg" onclick="this.style.display='none';" alt=""/>
</label>
<input type="radio" name="animals" onclick="this.style.display='none';" id="dog" class="input-hidden" value="dog"/>
<label for="dog">
<img src="images/dog.jpg" alt=""/>
</label>
<input type="radio" name="animals" onclick="this.style.display='none';" id="horse" class="input-hidden" value="horse"/>
<label for="horse">
<img src="images/horse.jpg" alt=""/>
</label>
<input type="radio" name="animals" onclick="this.style.display='none';" id="pig" class="input-hidden" value="pig"/>
<label for="pig">
<img src="images/pig.jpg" alt=""/>
</label>
</form>
</div>
<div class="content">
<button type="button" onclick="this.style.display='none';image_select2()" value="dog" id="dog_t">Chien</button>
<button type="button" onclick="this.style.display='none';image_select()" value="cow" id="cow_t">Vache</button>
<button type="button" onclick="this.style.display='none';image_select4()" value="pig" id="pig_t">Cochon</button>
<button type="button" onclick="this.style.display='none';image_select3()" value="horse" id="horse_t">Cheval</button>
</div>
Instead of putting the code in the button click, add to each of the JavaScript inside the if statement like this:
if (pic4 == text4) {
Text4.style.display = 'none'
}
Here is working and I think simpler snippet of what your are trying to achieve.
You have to variables, one that represent the selected image, and an other that represents the selected button. When you click on any Image that will change the value of selectedImage, and when you click on a button that will change the value of selectedName. After the value change, the checkValues function check if the two values are selected and equal.
var selectedImage;
var selectedName;
//Change the value of the selectedImage and check the values
function selectImage(event){
selectedImage = event.target;
checkValues();
}
//Change the value of the selectedName and check the values
function selectName(event){
selectedName = event.target;
checkValues();
}
function checkValues() {
console.log(selectedImage);
console.log(selectedName);
//Check if both values are selected
if (!selectedImage || selectedImage == 'undefined' || !selectedName || selectedName == 'undefined'){
return ;
}
//Check if values are equals
if (selectedImage.value == selectedName.value) {
alert("good");
//remove the button and the image
selectedImage.parentNode.style.display = 'none';
selectedName.style.display = 'none';
} else {
alert("no");
}
//Reset the selected image and name.
selectedImage = 'undefined';
selectedName = 'undefined';
}
<div class="content">
<form>
<label for="cow">
<input type="radio" name="animals" id="cow" onclick="selectImage(event)" class="input-hidden" value="cow"/>
<img src="images/cow.jpg" alt=""/>
</label>
<label for="dog">
<input type="radio" name="animals" onclick="selectImage(event)" id="dog" class="input-hidden" value="dog"/>
<img src="images/dog.jpg" alt=""/>
</label>
<label for="horse">
<input type="radio" name="animals" onclick="selectImage(event)" id="horse" class="input-hidden" value="horse"/>
<img src="images/horse.jpg" alt=""/>
</label>
<label for="pig">
<input type="radio" name="animals" onclick="selectImage(event)" id="pig" class="input-hidden" value="pig"/>
<img src="images/pig.jpg" alt=""/>
</label>
</form>
</div>
<div class="content">
<button type="button" onclick="selectName(event)" value="dog" id="dog_t">Chien</button>
<button type="button" onclick="selectName(event)" value="cow" id="cow_t">Vache</button>
<button type="button" onclick="selectName(event)" value="pig" id="pig_t">Cochon</button>
<button type="button" onclick="selectName(event)" value="horse" id="horse_t">Cheval</button>
</div>

Categories

Resources