Javascript: Triggering "for" loop using "if...else" statements not working - javascript

I am trying to make a simple script which automatically blocks the input boxes in the file when I tick a checkbox.
For this, I am trying to add/remove the "disabled" attribute by triggering a loop every time the checkbox is clicked. Looks something like this:
function locker() {
var boxes = document.querySelectorAll("input[type='text']");
var x = getElementById("lock")
for (i = 0; i < inputBoxes.length; i++) {
if (x.checked == true) {
boxes[i].disabled = true;
} else {
boxes[i].disabled = false;
}
}
}
<input type="checkbox" id="lock" onClick="locker()">
<input type="text"></input>
<input type="text"></input>
<input type="text"></input>
However, I can't seem to get it to work. I don't have much experience coding, and I feel like I am making a very basic mistake, but I couldn't find a solution to this problem so far... How can I solve this? Are there any other workarounds to get the same result?
Thanks in advance

You need to use document.getElementById("lock") instead of getElementById("lock") and use the correct variable names for your variables. You used inputBoxes and boxes while you meant to use the same variable.
function locker() {
var inputBoxes = document.querySelectorAll("input[type='text']");
var x = document.getElementById("lock")
for (i = 0; i < inputBoxes.length; i++) {
if (x.checked == true) {
inputBoxes[i].disabled = true;
} else {
inputBoxes[i].disabled = false;
}
}
}
<input type="checkbox" id="lock" onClick="locker()">
<input type="text"></input>
<input type="text"></input>
<input type="text"></input>

Related

Javascript: checkbox onchange/onclick function not working

I have this function for my computation that whenever the text fields are populated, it will add a stack to a variable and whenever a checkbox is checked on the text field, the text field wont add a value.
everything is working except the checkbox function, I already tried onchange and onclick but nothing happens. Can you check my codes?
Script:
function submission(){
x = 19;
ctr = 1;
ctr2 = 0;
days = ('<?php echo $query[0]->totaldays; ?>') - 1;
$('#payment').html('');
for(i = 1; i<=x ; i++){
if($('#guest'+i).val() != ""){
ctr++;
}
if(document.getElementById('kid'+i).checked){
ctr2++;
}
}
totalCount = 0;
totalCount = parseInt(ctr) - parseInt(ctr2);
totalCount = parseInt(ctr) * parseInt(days);
totalCount = parseFloat(totalCount) * 100;
$('#totalPayment').val(totalCount);
$('#payment').html(totalCount);
}
HTML:
<div class="row">
<div class="col-sm-10">
<label for="exampleInputtext1"><a style = "color:black; font-size: 10px;" ><input onchange="submission()" type="checkbox" name="kid1" id="kid1" > </a>Guest 1:</label>
<input type="text" class="form-control" onblur="submission()" name="guest1" id="guest1"/>
</div>
</div>
The onclick event handler will work for checkbox,you can try this code,
HTML:
<input onclick="submission(this)" type="checkbox" name="kid1" id="kid1" >
JS:
And you can check and see whether the checkbox is checked or not using the following code,
function submission(click){
....
var clicked=click.checked;
...
}
if it is true that means the checkbox has been checked and if it is false it has not been checked.
$("#guest1").change(function() {
if(this.checked) {
//Do this.
}
else{
// Do this.
}});
don't need to mention onclick function on html. just add this code in JS.
its calling auto based on id.
let me know if you need any help in understanding.
Ajay
thanks for your answers, it seems like I just messed up a little bit on my mathematical equation.
totalCount = 0;
totalCount = parseInt(ctr) - parseInt(ctr2);
totalCount = parseFloat(totalCount) * parseInt(days);
totalCount = parseFloat(totalCount) * 100;
$('#totalPayment').val(totalCount);
$('#payment').html(totalCount);

Hiding multiple form fields using checkboxes

I have this code that I need to edit so I can use it on multiple chkBox's and txtBox's.
Currently I can only hide one input field with one check box.
I know HTML and CSS but I am not familiar with JS.
I would like to be able to add a number at the end of each ID.
chkBox1, chkBox2, chkBox3... txtBox1, txtBox2, txtBox3...
Do I need to change getElementById to getElementsByTagName()?
JSFIDDLE for some reason it does not work here...?
This is my current code which hide the text field unless the checkbox is checked:
function showHide(){
var chkBox = document.getElementById("chkBox");
var txtBox = document.getElementById("txtBox");
if (chkBox.checked){
txtBox.style.visibility = "visible";
} else {
txtBox.style.visibility = "hidden";
}
}
The reason your code wasn't working is because it was running onLoad. Your DOM and the onclick were created before the load was complete. You could just move your code into your <head></head> tags and it will work as is. See here, all I did was select the "No wrap - in head", no code changes.
You could also continue to have your javascript run onLoad and remove your onclick and add an eventlistener in the javascript like this:
JSFiddle
var txtBox = document.getElementById("txtBox");
document.getElementById("chkBox").addEventListener("click", function() {
if (this.checked) {
txtBox.style.visibility = "visible";
} else {
txtBox.style.visibility = "hidden";
}
});
If you have multiple instances of this, I would change your DOM a bit sort of like this:
<form>
<div class="option">
<input type="text" name="txtBox1" class="hiddenInput" />
<br/>
<input type="checkbox" name="chkBox1" id="chkBox1" class="showHideCheck" />
<label for="chkBox1">Click me to show the text box</label>
</div>
<div class="option">
<input type="text" name="txtBox2" class="hiddenInput" />
<br/>
<input type="checkbox" id="chkBox2" name="chkBox2" class="showHideCheck" />
<label for="chkBox2">Click me to show the text box</label>
</div>
</form>
and do your JQuery like this (since you previously tagged jquery):
$(".hiddenInput").hide();
$(".showHideCheck").on("change", function() {
$this = $(this);
$input = $this.parent().find(".hiddenInput");
if($this.is(":checked")) {
$input.show();
} else {
$input.hide();
}
});
JSFiddle
Or with pure javascript and the similar DOM as above:
var checkBoxes = document.getElementsByClassName("showHideCheck");
for (var i = 0; i < checkBoxes.length; i++) {
checkBoxes[i].addEventListener('click', function () {
var txtBox = getAssociatedTextBox(this);
if (this.checked) {
txtBox.style.visibility = "visible";
} else {
txtBox.style.visibility = "hidden";
}
}, false);
}
function getAssociatedTextBox(ele) {
var childNodes = ele.parentNode.childNodes;
for (i = 0, j = childNodes.length; i < j; i++) {
if (childNodes[i].className == "hiddenInput") {
return childNodes[i];
}
}
}
JSFiddle
Try this,
Javascript
$(document).ready(function(){
$("input[type=checkbox]").change(function(){
var oTxt = $("#txtBox" + $(this).attr("id").replace("chkBox", ""));
if($(this).is("checked"))
oTxt.show()
else
oTxt.hide();
});
});
HTML
<input type="checkbox" id="chkBox1"/>
<input type="textbox" id="txtBox1"/>
<input type="checkbox" id="chkBox2"/>
<input type="textbox" id="txtBox2"/>

Using document.getElementsByClass with Checkboxes

I have cut this code and I'm not that familiar using Class.
<form>
<input type="checkbox" name="Symptom1" class=sound value="case1"> Poor Sound Quality<br>
<input type="checkbox" name="Symptom2" class=sound value="case2"> Only One Speaker is Working<br>
<input type="checkbox" name="Symptom3" class=sound value="case3"> No Sound<br>
<input type="checkbox" name="Symptom4" class=sound value="case4"> Low Volume<br>
<input type="checkbox" name="Symptom5" class=sound value="case5"> Crackling Sound<br>
<input type="checkbox" name="Symptom6" class=battery value="case6"> Drain Easily<br>
<input type="checkbox" name="Symptom7" class=battery value="case7"> Flickering Screen<br>
<input type="checkbox" name="Symptom8" class=battery value="case8"> Battery Physically Wobbled<br>
<input type="checkbox" name="Symptom9" class=battery value="case9"> Turn Off from Now and Then<br>
<input type="checkbox" name="Symptom10" class=battery value="case10"> Does not Charge<br>
</form>
<button onclick="Submit()">Submit</button>
Here is my submit function that I am working on.
function Submit() {
if (document.getElementsByClassName('sound').checked) {
alert("You Picked Sound");}
} else {
alert("none");
}
}
What I wanted to do is if the user checked at least one of the checkboxes under the same class (i.e. sound) then pressed submit. It would alert the user that he/she picked that class. But apparently it would not and rather it always alert me with none.
Help?
You have to loop through the collection document.getElementsByClassName returns and check the checked attribute. Here's one way to do it (untested):
function Submit() {
var pickedOne = false;
var inputs = document.getElementsByClassName('sound');
for(var i = 0, l = inputs.length; i < l; ++i) {
if(inputs[i].checked) {
pickedOne = true;
alert('You picked ' + inputs[i].className);
break;
}
}
if(!pickedOne) {
alert('none');
}
}
If you can use jQuery, you can probably do something like this instead:
function Submit() {
var selectedClass = $('input[type=checkbox]:checked').attr('class');
if(selectedClass) {
alert('You picked ' + selectedClass);
}
else {
alert('none');
}
}
"document.getElementsByClassName" return a list of nodes.
For example document.getElementsByClassName('sound') will return an array 5 checkboxes. So you can use it like this:
var sounds = document.getElementsByClassName('sound');
// Now you can access one of them through it's index
function Submit() {
if (document.getElementsByClassName('sound')[0].checked) {
alert("You Picked Sound");}
} else {
alert("none");
}
}
document.getElementsByClassName() returns an array instead of an object. You need to loop through the array.
function Submit() {
var allCheckBox = document.getElementsByClassName('sound');
var allPick = false;
for(var i = 0; i < allCheckBox.length ; i++) {
if (allCheckBox[i].checked) {
allPick = true;
break;
}
}
if(allPick) {
alert("You Picked Sound");
} else {
alert("none");
}
}

Uncheck a checkbox if another checked with javascript

I have two checkbox fields. Using Javascript, I would like to make sure only one checkbox can be ticked. (e.g if one checkbox1 is ticked, if checkbox2 is ticked, checkbox1 will untick)
<input name="fries" type="checkbox" disabled="disabled" id="opt1"/>
<input type="checkbox" name="fries" id="opt2" disabled="disabled"/>
I would also like to have a radio button beneath, if this is clicked, I would like both checkboxes to be unticked.
<input type="radio" name="o1" id="hotdog" onchange="setFries();"/>
Would the best way to do this be by writing a function, or could I use onclick statements?
Well you should use radio buttons, but some people like the look of checkboxes, so this should take care of it. I've added a common class to your inputs:
function cbChange(obj) {
var cbs = document.getElementsByClassName("cb");
for (var i = 0; i < cbs.length; i++) {
cbs[i].checked = false;
}
obj.checked = true;
}
Demo: http://jsfiddle.net/5uUjj/
Also based on tymeJV's answer above, if you want to only deactivate the other checkbox when one is clicked you can do this:
function cbChange(obj) {
var instate=(obj.checked);
var cbs = document.getElementsByClassName("cb");
for (var i = 0; i < cbs.length; i++) {
cbs[i].checked = false;
}
if(instate)obj.checked = true;
}
tymeJV's function does not let you have both unticked - this does.
(yes, weird but true.. sometimes there's a semantic reason why you want two tickboxes not radio buttons)
Hope this helps:
function setFries(){
var hotdog= document.getElementById("hotdog");
var opt1= document.getElementById("opt1");
var opt2 = document.getElementById("opt2");
if(hotdog.checked){
opt1.checked = false;
opt2.checked = false;
}else if(opt1.checked){
opt2.checked = false;
}else if(opt2.checked){
opt1.checked = false;
}
}
<input type="checkbox" name="fries" id="opt1" disabled="disabled" onclick="setFries(this);/>
<input type="checkbox" name="fries" id="opt2" disabled="disabled" onclick="setFries(this);/>
<input type="radio" name="o1" id="hotdog" onclick="setFries(this);"/>
Note that I am using onclick event:
function setFries(obj){
var fries = document.getElementsByName('fries');
if(obj.id =='hotdog') //Or check for obj.type == 'radio'
{
for(var i=0; i<fries.length; i++)
fries[i].checked = true;
}
else{
for(var i=0; i<fries.length; i++){
if(fries[i].id != obj.id){
fries[i].checked = !obj.checked;
break;
}
}
}
}
The simplest way I found for this was to not use any sort of code at all. I triggered an actions in the check box properties.
1. mouse up to reset a form. I then unselected (for reset) all of my fields accept for my desired check boxes. I then did the same thing for my other check box to go the other way. You can basically turn the check boxes into toggles or have any sort of crazy pattern you want.

Using javascript to check if a radio button is selected and return a specific answer based on the selection

I am looking, in the cleanest way possible to be able to take a simple yes or no question and test for which answer has been chosen.
For instance in this case if a "yes" I want it to return a value of "Continue" into a specified area (a 3 column table which has a question in the first, the radio buttons in the second, and I want it to update and display the answer in the third).
My code for the JS stands thus far:
<script type="text/javascript">
var answer = 'place-holder';
var user_input;
function checkForm()
{
var substanceab = document.getElementById('Sub');
for (i = 0; i < substanceab.length; i++)
{
if(substanceab.length[i].checked)
{
user_input = substanceab.length[i].value;
}
}
if (user_input ="yes")
{
return answer = "Continue";
}
else if (user_input ="no")
{
return answer = "Provide Alternate Referral";
}
else
{
return;
}
};
function writeAns()
{
document.getElementById('answerwrite').innerHTML = checkForm[user_input];
};
</script>
and the Body text (minus the actual question):
<table class="table table-bordered">
<tr>
<td width="58%"><center><strong>Required:</strong></center></td>
<td width="19%"></td>
<td width="23%"><center><u><strong>___________</strong></u></center></td>
</tr>
<tr>
<td> <span class="sub depend"> <strong><i>_________</i> </strong></span></td>
<td> <span class="sub depend ans">
<form name="Substance">
<label class="radio inline">
<input type="radio" value="yes" name="substance" onclick="writeAns()">
yes </label>
<label class="radio inline">
<input type="radio" value="no" name="substance" onclick="writeAns()">
no </label> </form></span></td>
<div id="answerwrite"></div>
<script type="text/javascript">
document.write("<td>" + writeAns() + "</td>")
</script>
</tr></table>
Ok, fixed the 'funk' but like I said, more used to java than javascript, completely tougher syntax. I agree, I only used the ID thing to try and get this to work with a different method, but it never did. Now with some of the suggestions it is just giving me undefined everywhere. And while I agree this will eventually turn to jquery, I have NO clue how to work with it, hence figuring out this in javascript first.
A few things:
document.getElementByID()
will always return the first element, as ID's are supposed to be unique.
Instead, use:
document.getElementsByName('substance');
Next, in your loop, you are improperly referencing the array's members using the .length property. Try this instead:
for (i = 0; i < substanceab.length; i++)
{
if(substanceab[i].checked)
{
user_input = substanceab[i].value;
}
}
Finally, in javascript, the '=' opertator is always an assignment statement. To do comparisons, always use '==':
if (user_input == "yes")
{
return answer = "Continue";
}
else if (user_input =="no")
{
return answer = "Provide Alternate Referral";
}
else
{
return;
}
Also, try to avoid global variables whenever possible.
Here is the working code, refactored a bit:
<input type="radio" value="no" id= "Sub" name="substance" onclick="writeAns()">
function checkForm()
{
var user_input;
var substanceab = document.getElementsByName('substance');
for (i = 0; i < substanceab.length; i++)
{
if(substanceab[i].checked)
{
user_input = substanceab[i].value;
}
}
if (user_input == "yes")
{
return "Continue";
}
else if (user_input =="no")
{
return "Provide Alternate Referral";
}
else
{
return;
}
};
function writeAns()
{
document.getElementById('answerwrite').innerHTML = checkForm();
};
Very easy if you are using JQuery.
Ensure your elements have the same "name" attribute and use:
var RadioGroupResult = $('input[name="MyRadioGroupNameHere"]:checked').val();
Nice and simple.

Categories

Resources