I'm a total beginner to JS, trying to create a radio button with two options (left/right), in which one of the two options needs to be selected for the program to continue, or else it will display an error screen.
I've got code that will either prevent the participant from continuing no matter what they press (i.e. the error pops up regardless), or code that will allow the participant to continue no matter what (i.e. the program continues even if they don't select one of the options.) I feel like this could be something with my logical operators, but I'm really not sure. I've tried using a manual XOR and that doesn't seem to be the problem.
I'm using adapted code, so please let me know if there's anything else I can/should include!
<div class="radio"><label><input id="option1" name="option1" type="radio" value="Right" />Right</label></div>
<div class="radio"><label><input id="option1" name="option1" type="radio" value = "Left" />Left</label></div>
Code that causes the error no matter what:
<input onclick="function filledOut(id) { return (document.getElementById(id).value == 'Left')} if(filledOut('option1') ) { next(); }else{ alert('Please provide a response.'); }" type="button" value="Continue" /> </div>
</div>
Code that causes the program to continue:
<input onclick="function filledOut(id) { return ((document.getElementById(id).value == 'Left')|| (document.getElementById(id).value == 'Right'))} if(filledOut('option1') ) { next(); } else{ alert('Please provide a response.'); }" type="button" value="Continue" /> </div>
</div>
<form name="formName">
<input type="radio" name="option1" id="option1" value="Right"/>Right
<input type="radio" name="option2" id="option2" value="Left"/>Left
</form>
<input onclick="checkResponse()" type="button" value="Continue" />
checkResponse function will check if any options are selcted when user clicks on the continue button.
<script type="text/javascript">
function checkResponse(){
if (isChecked('option1') || isChecked('option2')){
next();
}else{
alert("Your error message")
}
}
function isChecked(id){
return document.getElementById(id).checked; //returns true if any options are selected
}
</script>
You need to change the ID's to something different. In the case of radio buttons, the "name" is the radio button group. You don't need the ID's unless you are going individually look at each item, and if you give them ID's, they need to be distinct from every other ID, as well as the "name" attributes.
https://www.w3schools.com/tags/att_input_type_radio.asp
<input id="optionRight" name="groupName" type="radio" value="Right" />
<input id="optionLeft" name="groupName" type="radio" value="Left" />
Also, you can make one of the radio buttons as selected by default.
How to select a radio button by default?
<input id="option1" name="groupName" type="radio" value="Right" checked="checked" />
What I've understood is that you need to show an error if nothing is checked and continue if one of them is checked.
To do that, you will need to check if either of them is checked not checking it's value & give each radio button a unique id.
You can do something similar to this
function isChecked(id){//Instead of filledOut
return document.getElementById(id).checked;
//.checked returns true or false
}
if (isChecked('option1') || isChecked('option2')){
next();
}else{
alert("Your error message")
}
Another function to get the value if you need it:
function getCheckedBtnValue(){
if(isChecked('option1')) return document.getElementById('option1').value
if(isChecked('option2')) return document.getElementById('option2').value
return null
}
//You can also use this function to check if any of them is checked
const value = getCheckedBtnValue();
if(value){
next();
}else{
alert("Your error message");
}
Also, try not to write JavaScript inside of HTML elements it can be hard to read often.
Keep JavaScripting.
Related
I am trying to check if a radio button is selected or not. If the "morn_before" radiobutton is selected, the data will be stored as "2", but if the "morn_after" radiobutton is selected instead, the data will be stored as "1".
Currently my code show below is not working. For example when i select the "morn_before" radiobutton, it doesnt print "morn_before checked true" in the console, despite me putting console.log("morn_before checked true") in that if statement.
HTML:
<div class="radiobutton">
<input type="radio" id="morn_before" name="morn_time" value="morn_before">
<label for="morn_before">Before Food</label><br>
<input type="radio" id="morn_after" name="morn_time" value="morn_after">
<label for="morn_after">After Food</label><br><br>
</div>
Javascript:
function check() {
let user=firebase.
auth().currentUser;
let uid;
if(user!=null){
uid=user.uid;
}
var firebaseRef = firebase.database().ref();
if(document.getElementById("morn_before").checked){
console.log("morn_before checked true");
firebase.database().ref(uid).child('/radiobutton/').child('/morn_time/').set("2");
}
else if(document.getElementById("morn_after").checked){
firebase.database().ref(uid).child('/radiobutton/').child('/morn_time/').set("1");
}
}
check();
You don't need any JavaScript for this. You can have a completely different display than the stored value.
<div class="radiobutton">
<input type="radio" id="morn_before" name="morn_time" value="2">
<label for="morn_before">Before Food</label><br>
<input type="radio" id="morn_after" name="morn_time" value="1">
<label for="morn_after">After Food</label><br><br>
</div>
Should produce the same result. The only improvement would be to set one of these to default true, in case the user chose neither. But that'd be up to you.
ADDITIONAL INFO: You are not supposed to read a radio button group that way.
You should go over some basics of HTML INPUT tag such as
https://www.geeksforgeeks.org/how-to-get-value-of-selected-radio-button-using-javascript/
I have a edit form which is showing the selected check boxes , when submitting i want to check that either is there any change in the check boxes or not?
You could compare the current value of each of the checkboxes with their original setting. For this you can compare the checked property with the defaultChecked property.
Here is some code:
function wasAnyCheckChanged() {
return $('input[type=checkbox]').toArray().some(function(el) {
return el.checked != el.defaultChecked;
});
}
// At submission: collect them again and compare
$('form').submit(function() {
if (wasAnyCheckChanged()) {
alert('you changed checks');
} else {
alert('No changes made');
}
return false; // cancel submission
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
<input type="checkbox" name="chk1" checked>Option 1<br>
<input type="checkbox" name="chk2" >Option 2<br>
<input type="submit" name="submit" value="Submit"><br>
</form>
This code shows an alert indicating whether any of the checks were different at submission than as they were at page load. Then the submission is cancelled. You could decide what to do, and only cancel the submission in one of the two cases.
I want to click on a checkbox and if I click this box it should run a function what gets an ID and saves it into an array or deletes it from the array if it still exists in the array.
That works, but if I click on the text beside the box the function runs twice. It first writes the ID into the array and then deletes it.
I hope you can help me so that I can click on the text and it just runs once
HTML
<label><input type="checkbox" value="XXX" >Active</label>
JavaScript/jQuery
function addOrRemoveBoxes(ID){
if(boxArr.indexOf(ID) != -1){
removeFromArray(ID)
}
else{
boxArr.push(ID);
}
}
$(".checkBoxes").unbind().click(function() {
event.stopPropagation();
addOrRemoveBoxes($(this).find('input').val());
});
The problem is probably that your label and your input are picking the click. Try to bind it only to input. Like this:
$(".checkBoxes input").unbind().click(function() {
event.stopPropagation();
addOrRemoveBoxes($(this).find('input').val());
});
Your HTML is structured bad. When your label is clicked it triggers a click event for the input so you have to separate the input form the label like: <input type="checkbox" name="opt1" id="opt1_1" value="ENG"> <label for="opt1_1">hello</label>. Also your jQuery makes no sense, why do you use unbind()? And we can't see what removeFromArray() does (we can guess but I prefer to see all code used or note that you use pseudo code).
I made this in 5 min: (hopes it helps you)
$(document).ready(function(){
window.boxArr = [];
$(document).on('click','[name=opt1]',function(){
addOrRemoveBoxes(this.value);
//show contents of boxArr
if(boxArr.length == 0){
$('#output').html('nothing :/');
}
else{
$('#output').html(boxArr.join(" -> "));
}
});
});
function addOrRemoveBoxes(ID){
var arrayIndex = boxArr.indexOf(ID);
if(arrayIndex > -1){
boxArr.splice(arrayIndex, 1);
}
else{
boxArr.push(ID);
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h1>Choose</h1>
<input type="checkbox" name="opt1" id="opt1_1" value="ENG"> <label for="opt1_1">hello</label> <br>
<input type="checkbox" name="opt1" id="opt1_2" value="DUT"> <label for="opt1_2">hallo</label> <br>
<input type="checkbox" name="opt1" id="opt1_3" value="SWE"> <label for="opt1_3">hej</label>
<br><br><h2>Array contains:</h2>
<div id="output">nothing :/</div>
Side note: with [name=opt1] we select all the elements with name="opt1" attribute.
I have a form page in which the user can enter an ID, and the corresponding profile data is pulled from mysql and displayed in the form so that the user may edit it.
One element is a group of radios, so you may select a year level (ie "1", "2", "3", etc).
When a user provides an ID, an AJAX call is made to pre-populate the form with data, including selecting the appropriate radio.
problem:
The user must select a year level to submit the form. I check this with a verifyForm() method:
function verifyForm() {
if( !document.addStudentForm.elements["yearLevel"].checked ) {
alert( "You must select a year level before submitting." );
return false;
}
};
I expect this to check yearLevel and, if an option isn't selected, alert/return false.
However, when the yearLevel radio is pre-selected by the AJAX data, this is still behaving as if the user did not select a radio.
The radio is populated by js via the following code:
document.getElementById( "yearLevel_<?=$student['student']->get('yearLevel')?>" ).checked = true;
edit: Here is the relevant HTML.
<form name="addStudentForm" action="validation/updateStudentValidate.php" method="POST" onSubmit="return verifyForm()">
<input type="radio" value="1" name="yearLevel" disabled id="yearLevel_1" /> 1
<input type="radio" value="2" name="yearLevel" disabled id="yearLevel_2" /> 2
<input type="radio" value="3" name="yearLevel" disabled id="yearLevel_3" /> 3
<input type="radio" value="4" name="yearLevel" disabled id="yearLevel_4" /> 4
<input type="radio" value="5" name="yearLevel" disabled id="yearLevel_5" /> 5
<input type="radio" value="6" name="yearLevel" disabled id="yearLevel_6" /> 6
</form>
Question:
How can I have my javascript properly identify whether or not the radio has been checked, regardless of if it was selected by hand or programmatically?
Taken from this StackOverflow post and adapted for this example and for speed, you can have this in your AJAX success return:
var radios = document.getElementsByName('yearLevel'),
i = radios.length,
isChecked = false;
while(i--){
if (radios[i].checked) {
isChecked = true;
break;
}
}
Then when the function is called:
function verifyForm(){
if(!isChecked){
alert( "You must select a year level before submitting." );
return false;
}
};
This is assuming that you don't have any other items with the name yearLevel in your HTML.
This will actually return the value, I guess I'm unsure if you are wanting to see a specific item checked, or just that they have been checked at all. This function will do both.
Here is sample http://jsfiddle.net/HhXGH/57/
I am clicking radio button by jquery but knockout.js does not recognize it.Still it shows first clicked value.
<p>Send me spam: <input type="checkbox" data-bind="checked: wantsSpam" /></p>
<div data-bind="visible: wantsSpam">
Preferred flavor of spam:
<div><input type="radio" name="flavorGroup" value="cherry" data-bind="checked: spamFlavor" /> Cherry</div>
<div><input type="radio" name="flavorGroup" value="almond" data-bind="checked: spamFlavor" /> Almond</div>
<div><input type="radio" name="flavorGroup" value="msg" data-bind="checked: spamFlavor" /> Monosodium Glutamate</div>
</div>
var viewModel = {
wantsSpam: ko.observable(true),
spamFlavor: ko.observable('cherry')
};
ko.applyBindings(viewModel);
$(':radio:last').click();
alert(viewModel.spamFlavor())
This because Knockout is subscribing to the click events of checked radio/checkbox elements only. If you checkout the binding handler code for checked. It does this.
var updateHandler = function() {
var valueToWrite;
if (element.type == "checkbox") {
valueToWrite = element.checked;
} else if ((element.type == "radio") && (element.checked)) {
valueToWrite = element.value;
} else {
return; // "checked" binding only
responds to checkboxes and selected radio buttons
}
So in order to get your code to work do this.
$(':radio:last').prop('checked', true).click();
However if the goal is to check the last value, why not just do
viewModel.spamFlavor("msg");
This would achieve the same result.
Hope this helps.
Adding $(':radio:last').attr('checked', true); in addition to triggering click makes it work for me:
http://jsfiddle.net/jearles/HhXGH/61/
I have two different jsFiddles since I'm not sure exactly what your after.
The first jsFiddle will respond via alert when the last radio button is manually clicked.
The second jsFiddle is your posted /57/ jsFiddle without the alert.
Using an alert or console.log with a function will actually invoke that function. That said, after you have manually set the .click() to the last radio button, it's inadvertently reset back to cherry since that's the default value.
RE-EDIT: The second jsFiddle now includes alert written in syntax that doesn't invoke the function & now uses shorted markup.