I have the following HTML:
<fieldset id="question1">
<legend>Which are fruit?</legend>
<label><INPUT TYPE="checkbox" NAME="q1" VALUE="wrong">tomatoes<BR></label>
<label><INPUT TYPE="checkbox" NAME="q2" VALUE="wrong">cucumber<BR></label>
<label><INPUT TYPE="checkbox" NAME="q3" VALUE="right">apples<BR></label>
<label><INPUT TYPE="checkbox" NAME="q4" VALUE="wrong">onion<BR></label>
<label><INPUT TYPE="checkbox" NAME="q5" VALUE="right">bananas<BR></label>
</fieldset>
<input type="button" id="answer">
and JavaScript:
document.getElementById("answer").onclick = validate;
function validate() {
var checkbox;
var i;
var right;
checkboxes = document.getElementById("question1").getElementsByTagName("input");
right = false;
for(i = 0; i < checkboxes.length; i++) {
if(checkboxes[i].value == "right" && checkboxes[i].checked == true) {
right = true;
}
}
if(right) {
alert("You answered correctly");
} else {
alert("Wrong answer");
}
}
My Quiz is almost working but I only want it to be correct when all the right options are checked. At the moment when one correct option is selected it still returs as correct regardless of whether other incorrect ones were also selected.
Here is the live sample: http://jsfiddle.net/nzLmxfx7/
Thanks!
Try this, which works on my computer.
HTML:
<fieldset id="question1">
<legend>Which are fruit?</legend>
<label><INPUT TYPE="checkbox" NAME="input" VALUE="wrong">tomatoes<BR></label>
<label><INPUT TYPE="checkbox" NAME="input" VALUE="wrong">cucumber<BR></label>
<label><INPUT TYPE="checkbox" NAME="input" VALUE="right">apples<BR></label>
<label><INPUT TYPE="checkbox" NAME="input" VALUE="wrong">onion<BR></label>
<label><INPUT TYPE="checkbox" NAME="input" VALUE="right">bananas<BR></label>
</fieldset>
<input type="button" id="answer" value="Submit">
JavaScript:
document.getElementById("answer").onclick = validate;
function validate() {
var checkboxes = document.getElementsByName("input");
var checkboxChecked = [];
for(var i = 0; i < checkboxes.length; i++) {
if(checkboxes[i].checked && (checkboxes[i].value === "right")) {
checkboxChecked.push(checkboxes[i]);
}
}
if(checkboxChecked.length === 2) {
alert("You answered correctly");
}
else {
alert("Wrong answer");
}
}
Do it other way. Set right to true by default and set it to false if either correct checkbox is not checked or wrong checkbox is checked.
You are only setting the value of flag (right) to true if user has selected a checkbox whose value is true.
You also need to set flag to false if user has selected a checkbox whose value is false.
For Ex:
If user checked apples and onions. Then your code will check apples checkbox and set the flag to true. There would be no code executing for the Onions.
I think you got my point
Add:
if(checkboxes[i].value == "wrong" && checkboxes[i].checked == true) {
right = false;
}
Related
I have several radio buttons, and the last radio button has a freetext option next to it. I had success getting the values of the radio button OR the freetext, but never both in the same function.
If I had 3 choices, and the 4th choice was another, I would want the function to grab the value without creating a separate Javascript function.
Here was my attempt:
<input type="radio" id = "choice1" name="snooze" value="samplechoice0" onClick='valuechanged();'/> samplechoice0<br>
<input type="radio" id = "choice2" name="snooze" value="samplechoice1" onClick='valuechanged();'/> samplechoice1<br>
<input type="radio" id = "choice3" name="snooze" value="samplechoice2" onClick='valuechanged();'/> samplechoice2 <br>
<input type="radio" id = "choice10" name="snooze" value="Normal Radio" onClick='valuechanged();'/>
<input type="text" id = "choice11" class="tb" name="tb1" placeholder="Enter Other Reason Here" onkeypress='valuechanged();' > <br>
function Submit() {
var items=document.getElementsByClassName('radio');
var selectedItems=" ";
for(var i=0; i<items.length; i++) {
if(items[i].type=='radio' && items[i].checked==true && document.getElementById('choice10').checked==false) {
selectedItems+=items[i].value+"; ";
}
}
if(document.getElementById("choice10").checked == true) {
selectedItems = document.getElementById('choice11').value;
}
alert(selectedItems);
}
Assuming I'm understanding your question, I would pair the two together using a name that matches the radio input's value. For example, if you have a radio input with value="other", just create a textbox with name="otherText"
Then, using an object like { snooze, snoozeText }, allow both values to potentially be undefined, empty string, or whatever else works in your situation. For example:
document.querySelector('.js-snooze-form').addEventListener('submit', e => {
e.preventDefault()
const formElements = e.currentTarget.elements
// Get the snooze value
const snoozeEl = Array.from(formElements.snooze).filter(el => el.checked)[0]
const snooze = snoozeEl && snoozeEl.value
// Get the paired text, if any
const snoozeTextEl = formElements[`${snooze}Text`]
const snoozeText = snoozeTextEl && snoozeTextEl.value
// "Return" the checked snooze value paired with the reason text
console.log({ snooze, snoozeText })
})
form {
display: grid;
gap: 1em;
justify-items: start;
}
<form class="js-snooze-form">
<label><input type="radio" name="snooze" value="0" />Choice 0</label>
<label><input type="radio" name="snooze" value="1" />Choice 1</label>
<label><input type="radio" name="snooze" value="2" />Choice 2</label>
<!-- Define a pairing between other & otherText -->
<div>
<label><input type="radio" name="snooze" value="other" />Other:</label>
<input name="otherText" placeholder="Enter Other Reason Here" />
</div>
<button>Submit</button>
</form>
You can change the ID of the last radio button with free text dynamically by making it equal to the text which is given in by the user.
I also added in following code that when the user gives text input next to the last radio button, the last radio button is automatically checked.
You can then grab the ID of the radio button which is checked.
<form id="radiobuttonForm" name="radiobuttonForm">
<input type="radio" name="choice" id="choice1"> samplechoice0
<br>
<input type="radio" name="choice" id="choice2"> samplechoice1
<br>
<input type="radio" name="choice" id="choice3"> samplechoice2
<br>
<input type="radio" name="choice" id="other" class="other_reason_radio"> samplechoice3
input type="text" id="other_reason_text_input"/>
</form>
var choice;
function getChoice(){
var radios = document.forms["radiobuttonForm"].elements["choice"];
for(var i = 0, max = radios.length-1; i < max; i++) {
radios[i].onclick = function() {
choice=this.id;
console.log('choice: ', choice);
}
}
radios[radios.length-1].onclick = function() {
document.getElementsByClassName("other_reason_radio")[0].id=document.getElementById("other_reason_text_input").value;
choice=this.id;
console.log('choice: ', choice);
}
}
document.getElementById("radiobuttonForm").addEventListener("click", getChoice());
document.getElementById('other_reason_text_input').addEventListener('input', function() {
document.getElementsByClassName("other_reason_radio")[0].checked = true;
document.getElementsByClassName("other_reason_radio")[0].id=document.getElementById("other_reason_text_input").value;
choice=document.getElementById("other_reason_text_input").value;
console.log('choice: ', choice);
});
I would like to create an alert that displays if none of the choices in my check box have been displayed.
<script>
function mFunction () {
if (!!this.form.checkbox.checked) {
alert('not checked');
return false;
}
};
</script>
js above
<body>
<form>
<input type="checkbox" name="choice1" value="choice1" id="confirm">choice 1<br>
<input type="checkbox" name="choice2" value="choice2" >choice 2<br>
<input type="checkbox" name="choice3" value="choice3">choice 3<br><br>
<input type="submit" value="Submit" onclick="mFunction()">
</form>
I wanted an alert if nothing selected, and no alert if something is selected.
you can check this by
[...document.querySelectorAll("input[type='checkbox']")].some(i=>i.checked)
function mFunction (e)
{
if(![...document.querySelectorAll("input[type='checkbox']")].some(i=>i.checked))
{
alert('not checked');
e.preventDefault();
}
};
function checkForm(t,e) {
e.preventDefault();
console.log('checked');
};
<form onsubmit="checkForm(this,event);">
<input type="checkbox" name="choice1" value="choice1" id="confirm">choice 1<br>
<input type="checkbox" name="choice2" value="choice2" >choice 2<br>
<input type="checkbox" name="choice3" value="choice3">choice 3<br><br>
<input type="submit" value="Submit" onclick="mFunction(event)">
</form>
You can directly check the checked items like below.
function mFunction () {
let matches = document.querySelectorAll('input[type=checkbox]:checked');
if (matches.length < 1) {
alert('not checked');
return false;
}
};
If its plain javascript, you can try adding an event listener when checkbox is clicked.
Maintain an array in the listener. If something is selected maintain a checkbox selection counter or boolean tracking selection.
var checkbox = document.querySelector("input[name=checkbox]");
checkbox.addEventListener( 'change', function() {
if(this.checked) {
// Checkbox is checked..
} else {
// Checkbox is not checked..
}
});
This question already has an answer here:
Best way to get all selected checkboxes VALUES in jQuery [duplicate]
(1 answer)
Closed 4 years ago.
I have some 20 check boxes ( dynamic number) in a HTML page which is checked by default. A user can uncheck it or leave it checked. At the end, there is a button to submit.
How to get the items that are only checked at the time of submitting?
For a plain javascript solution, you can use document.querySelectorAll().
Retrieve the checkboxes and then loop over them, then push() all of the ones that have the checked: true property to an array called checked.
var checkboxes = document.querySelectorAll("input[type=checkbox]");
var submit = document.getElementById("submit");
function getChecked() {
var checked = [];
for (var i = 0; i < checkboxes.length; i++) {
var checkbox = checkboxes[i];
if (checkbox.checked) checked.push(checkbox.value);
}
return checked;
}
submit.addEventListener("click", function() {
var checked = getChecked();
console.log(checked);
});
<input type="checkbox" value="first" checked>
<input type="checkbox" value="second" checked>
<input type="checkbox" value="third" checked>
<input type="submit" id="submit">
Get all check boxes by css Class and iterate to checked the condition element.checked on it
Check this code snippet
function checkCheckBoxes(){
$("input.abc").each(function(index, element){
if(!element.checked){
console.log(index+" not checked");
} else{
console.log(index+" checked");
}
});
return false;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form action="">
<input type="checkbox" class="abc"/>
<input type="checkbox" class="abc"/>
<input type="checkbox" class="abc"/>
<input type="checkbox" class="abc"/>
<input type="checkbox" class="abc"/>
<input type="checkbox" class="abc"/>
<input type="checkbox" class="abc"/>
<input type="checkbox" class="abc"/>
<input type="submit" onclick="return checkCheckBoxes()" value="Submit">
</form>
I have looked for few other answers and tutorials but havent been able to find what I want. For example, I found this which uses change function, however, I need to use a click event and detect when a radio button is clicked. When a radio button is click I will be showing message to show like "you have selected radio button 1".
For example, below are my 3 radio buttons and I want to assign click event to them
<input type="radio" name="one" value="first" id="radio1" checked> first
<input type="radio" name="two" value="second" id="radio2" checked> second
<input type="radio" name="three" value="third" id="radio3" checked> third
I have tried
1
var inputs = document.querySelectorAll('input');
for (var i = 0; i <= inputs.length; i++) {
$("input[id='radio'+i]").click(function(){
if(inputs == 'radio1') {
//dosomething
} else if (inputs == 'radio2') {
//dosomething
}else if (inputs == 'radio3') {
//dosomething
}
});
}
2
var inputs = document.querySelectorAll('input');
for (var i = 0; i <= inputs.length; i++) {
$("#radio"+i).click(function(){
if(inputs == 'radio1') {
//dosomething
} else if (inputs == 'radio2') {
//dosomething
}else if (inputs == 'radio3') {
//dosomething
}
});
}
Please can someone help me on this as I have searched but havent been able to find anything of help.
you do not have radio buttons group of different names. You are likely to have something like this
<form id="myForm">
<input type="radio" name="radio" value="first" checked> first
<input type="radio" name="radio" value="second"> second
<input type="radio" name="radio" value="third"> third
</form>
$('#myForm input').on("change", function() {
console.log($(this).attr('value')); // based on the value do something.
});
thanks
i have one checkbox and two radio buttons. when i check the checkbox.i want both the radio buttons to enable and when i uncheck the checkbox i want both the radio button to get disable
below is the code which i have tried
<script>
function myfunction()
{
var radio=document.getElementsByName("disableme");
var len=radio.length;
for(var i=0;i<len;i++)
{
radio[i].disabled=true;
}
}
</script>
Notification
<input type="checkbox" onclick=myfunction() checked>
<input type="radio" name="disableme" id="1"> open
<input type="radio" name="disableme" id="2">close
You should check if checkbox is checked - in order to do that you can pass the element when your calling the function.
see example below
<script>
function myfunction(el) {
var radio=document.getElementsByName("disableme");
var len=radio.length;
for(var i=0;i<len;i++) {
radio[i].disabled=!el.checked;
}
}
</script>
Notification
<input type="checkbox" onclick=myfunction(this) checked>
<input type="radio" name="disableme" id="1">open
<input type="radio" name="disableme" id="2">close