Changing a checkbox label in Javascript - javascript

I'm trying to change a checkbox label in Javascript. The site is Wordpress and the form is a plug in, so I have to use a snippet plug in to target the checkboxes.
In brief, when a session is full, the checkbox needs to be greyed out and the label text highlighted in red.
Here's the code I'm using:
var mon1 = document.getElementById('Mondays_7_1_1');
mon1.disabled = true;
mon1.style.color = "red";
<div>
<input class="" type="checkbox" name="Mondays[]" value="5.00-6.00pm: 4-6 year olds FULL" id="Mondays_7_1_1" /> 5.00-6.00pm: 4-6 year olds FULL<br>
<input class="" type="checkbox" name="Mondays[]" value="6.00-7.00pm: 7-9 year olds" id="Mondays_7_1_2" /> 6.00-7.00pm: 7-9 year olds<br>
<input class="" type="checkbox" name="Mondays[]" value="7.00-8.00pm: 10-14 year olds FULL" id="Mondays_7_1_3" /> 7.00-8.00pm: 10-14 year olds FULL
</div>
<div style="font-weight: normal;color:red;" id="checkbox_Mondays_7_1"></div>
The greying of the box isn't a problem, but I can't change the font colour of the label. Does anyone know what the issue might be?

The only way you can do this is to change your markup as the text isn't part of the checkbox. All you need to do is add labels around the checkboxes and their respective texts, and traverse to the correct label with JS.
Your checkboxes should have <label>s anyway, so that when the text is clicked it triggers its checkbox.
You can target the label using parentNode
var mon1 = document.getElementById('Mondays_7_1_1');
mon1.disabled = true;
mon1.parentNode.style.color = "red";
<label>
<input class="" type="checkbox" name="Mondays[]" value="5.00-6.00pm: 4-6 year olds FULL" id="Mondays_7_1_1" />
5.00-6.00pm: 4-6 year olds FULL
</label>
<br />
<label>
<input class="" type="checkbox" name="Mondays[]" value="6.00-7.00pm: 7-9 year olds" id="Mondays_7_1_2" />
6.00-7.00pm: 7-9 year olds
</label>
<br />
<label>
<input class="" type="checkbox" name="Mondays[]" value="7.00-8.00pm: 10-14 year olds FULL" id="Mondays_7_1_3" />
7.00-8.00pm: 10-14 year olds FULL
</label>
<br />
N.B. If you intend to trigger on the checkbox change, use change/onChange not click/onClick.

This is because the Style was only for the INPUT.
I have added a label to the text for the moment.
HTML
<div>
<input class="" type="checkbox" name="Mondays[]" value="5.00-6.00pm: 4-6 year olds FULL" id="Mondays_7_1_1" /><label id="Mondays_7_1_1-text">5.00-6.00pm: 4-6 year olds FULL</label><br>
<input class="" type="checkbox" name="Mondays[]" value="6.00-7.00pm: 7-9 year olds" id="Mondays_7_1_2" /> 6.00-7.00pm: 7-9 year olds<br>
<input class="" type="checkbox" name="Mondays[]" value="7.00-8.00pm: 10-14 year olds FULL" id="Mondays_7_1_3" /> 7.00-8.00pm: 10-14 year olds FULL
</div>
<div style="font-weight: normal;color:red;" id="checkbox_Mondays_7_1"></div>
JS
var mon1 = document.getElementById('Mondays_7_1_1');
mon1.disabled = true;
var mon1Text = document.getElementById('Mondays_7_1_1-text');
mon1Text.style.color = "red";
JSFiddle

Wrap your text around a <span> for example, because it is not a part of the input.
<div><input class="" type="checkbox" name="Mondays[]" value="5.00-6.00pm: 4-6 year olds FULL" id="Mondays_7_1_1" />
<span name="Mondays_7_1_1">5.00-6.00pm: 4-6 year olds FULL</span>
...
<script>
var monSpan = document.getElementsByName('Mondays_7_1_1')[0];
monSpan.style.color = "red";</script>

I'm unaware that I have any access to the guts of the shortcodes.
Your only workaround then afaik is DOM manipulation. Something in the taste of :
var disableFunc = function (id, index) {
var childNodes = document.getElementById(id).parentNode.childNodes;
var texts = Array();
var textIndices = Array();
for (var i = 0; i < childNodes.length; i++) {
if (childNodes[i].nodeType == 3 && childNodes[i].nodeValue.trim() != "") {
texts.push(childNodes[i].nodeValue);
textIndices.push(i);
}
}
var mon1 = document.getElementById(id);
mon1.disabled = true;
var span = document.createElement('span');
span.innerHTML = texts[index - 1];
span.style.color = 'red';
mon1.parentNode.removeChild(childNodes[textIndices[index - 1]]);
mon1.parentNode.insertBefore(span, childNodes[textIndices[index - 1]]);
}
disableFunc('Mondays_7_1_1', 1);
//disableFunc('Mondays_7_1_2', 2); //!\ doesn't work !
//disableFunc('Mondays_7_1_3', 3); //!\ doesn't work !
This will work for 1 disable, because the function doesn't take into account the new modified DOM ;) http://jsfiddle.net/sskqtL9x/4/
I suggest you prepare your DOM (to match the replace pattern) by wrapping your labels inside spans or labels and then run this func after some tweaking is done to it.

Related

Hiding and showing html elements with radio button and javascript style=none

I am trying to write a function that will show or hide an html element (contained in a div) using javascript. Right now I have 3 radio buttons (to eventually show/hide 3 elements depending on radio button selected, but right now I am just trying to hide one element (month) if year or week is selected, and to show it if month is selected. My html is:
<div id="setting">
<input type="radio" id="year" name="view" value="year"> year<br>
<input type="radio" id="month" name="view" value="month"> month<br>
<input type="radio" id="week" name="view" value="week"> week
</div>
<div id="cal">
(element here I am trying to show/hide)
</div>
My javascript is:
function defineSetting (){
var setting = document.getElementById('setting').checked;
if(setting =='year'){
document.getElementById("cal").style.display = "none";
}else if(setting =='month'){
document.getElementById("cal").style.display = "unset";
}else if(setting =='week'){
document.getElementById("cal").style.display = "none";
}
}
I am also not super experienced with javascript and am trying to figure out how to call the function (if it works). If it is in the document ready function will it run when the page is loaded or do i need to call it somewhere.
I think this is what you're going for. You want to add an event listener to the buttons, and pass the value of the input that's checked to the defineSetting() function that hides/shows your #cal element. I also simplified your test in defineSetting()
<div id="setting">
<input type="radio" id="year" name="view" value="year" class="setting"> year<br>
<input type="radio" id="month" name="view" value="month" class="setting"> month<br>
<input type="radio" id="week" name="view" value="week" class="setting"> week
</div>
<div id="cal">
(element here I am trying to show/hide)
</div>
<style>
.hidden { display: none; }
</style>
<script>
var inputs = document.getElementsByClassName('setting'),
setting;
for (var i = 0; i < inputs.length; i++) {
var el = inputs[i];
el.addEventListener('change', function() {
defineSetting(this.value);
})
}
function defineSetting(setting) {
if (setting == 'year' || setting == 'week') {
document.getElementById("cal").classList.add('hidden');
} else {
document.getElementById("cal").classList.remove('hidden');
}
}
</script>
This will help you out:
How to get value of selected radio button?
You are trying to get the checked value of a div element, but this element doesn't have that. The input element do have that property so that's where you can get it from.

Checkbox:checked order with an Array.prototype.forEach.call push,

I'm begining with Javascript, its my third project with it (first is a html5 canvas game tutorial i followed, and second a little salary calculator i made in a day.
Now i'm working on a Stargate SG1 activable door.
I'm facing a problem with a function that i used to control the adress for the "spinning door", that i found here : How to check multiple checkboxes with JavaScript?
Problem is that the values of the checkboxes, as i understand it, are .push every time a new value is entered, but the array containing all the adress set them in an numerical order.
So if i enter 4-2-3-1 i got : 1-2-3-4 and because the rotating part is fixed, the symbols according to the checkbox value, never end to the position he should.
I tryed others array method, but i didnt figure how to stop array to add values in numerical order.
Here is the code, if someone figure out where i might do some changes :
function ChoixCoord(checkboxClass) {
var checkboxes = document.querySelectorAll('input[class="' + checkboxClass + '"]:checked'),
values = [];
Array.prototype.forEach.call(checkboxes, function(el) {
values.push(el.value);
});
Coord1 = values[0];// These are values used to give position to rotating door, so symbols matchs the chevrons
Coord2 = values[1];
Coord3 = values[2];
Coord4 = values[3];
Coord5 = values[4];
Coord6 = values[5];
Coord7 = values[6];
alert(Coord1 + Coord2 + Coord3 + Coord4 + Coord5 + Coord6 + Coord7); // This is for test purpose
};
<!DOCTYPE html>
<html>
<head>
<title>Stargate</title>
<link rel='stylesheet' type='text/css' href='style.css'/>
<script type='text/javascript' src='js.js'></script>
</head>
<body scroll="no" style="overflow:hidden">
<form class="panneauDHD" name="dhd">
<input type="checkbox" class="checkSymbole" id="s1" name="checkSymbole1" value="1" onClick="return KeepCount()"></input><label class="s1" for="s1"></label>
<input type="checkbox" class="checkSymbole" id="s2" name="checkSymbole2" value="2" onClick="return KeepCount()"></input><label class="s2" for="s2"></label>
<input type="checkbox" class="checkSymbole" id="s3" name="checkSymbole3" value="3" onClick="return KeepCount()"></input><label class="s3" for="s3"></label>
<input type="checkbox" class="checkSymbole" id="s4" name="checkSymbole4" value="4" onClick="return KeepCount()"></input><label class="s4" for="s4"></label>
<input type="checkbox" class="checkSymbole" id="s5" name="checkSymbole5" value="5" onClick="return KeepCount()"></input><label class="s5" for="s5"></label>
<input type="checkbox" class="checkSymbole" id="s6" name="checkSymbole6" value="6" onClick="return KeepCount()"></input><label class="s6" for="s6"></label>
<input type="checkbox" class="checkSymbole" id="s7" name="checkSymbole7" value="7" onClick="return KeepCount()"></input><label class="s7" for="s7"></label>
<input type="checkbox" class="checkSymbole" id="s8" name="checkSymbole8" value="8" onClick="return KeepCount()"></input><label class="s8" for="s8"></label>
<input type="button" id="lancement" value="Lancer la mission" onClick="ChoixCoord('checkSymbole');">
</form>
</body>
</html>
Thank you in advance for any help !
I think you need to think about different approach.
Remove onClick function form the checkboxes and button then create function which will add checkboxes to the array in order as they are being checked
var checked = [];
$('.checkSymbole').change(function(e) {
var checkbox = $(this);
var value = $(this).val();
var index;
/*
* if checkbox is checked add to array
* else remove it
*/
if (checkbox.is(':checked')) {
checked.push(value);
} else {
index = checked.indexOf(value); // find index of value in array
checked.splice(index, 1); // remove it
}
console.log(checked); // you can see how values in array are removed/ added
});
I hope it will help

Enable radio button with another radio button

How can I enable child radio buttons when a parent radio button is selected?
<body>
<p>
<input type="radio" id="bdmain" name="educationalqualification" disabled="true" /> Bachelor's Degree
</p>
<ul>
<li>
<label>
<input type="radio" name="bd" disabled="true"/>
Four Years
</label>
</li>
<li>
<label>
<input type="radio"name="bd" disabled="true"/>
Exceeding Four Years
</label>
</li>
</ul>
</body>
Try,
$("#bdmain").parent().next("ul").find("input[type='radio']").each(function(){
$(this).removeAttr("disabled");
});
You'll have to remove disabled="true" from the parent button (I also added a label)
<body>
<p>
<label for="bdmain">
<input type="radio" id="bdmain" name="educationalqualification" />
Bachelor's Degree
</label>
</p>
<ul>
<li>
<label>
<input type="radio" name="bd" class="bdmain-child" disabled="true"/>
Four Years
</label>
</li>
<li>
<label>
<input type="radio"name="bd" class="bdmain-child" disabled="true"/>
Exceeding Four Years
</label>
</li>
</ul>
</body>
Assuming you can use jQuery:
$(function() {
// select by name to handle disabling the button if the radio is deselected
$("[name='educationalqualification']").click(function(e) {
// enable/disable child items if parent is not checked
$(".bdmain-child").prop("disabled", !$('#bdmain').is(':checked'));
});
});
JSFiddle Sample
You have radio buttons so I assume that there are multiple parent-children groups that need to behave properly. Fortunately you didn't tag jQuery so is a nice exercise not to forget javascript:
var parentChecks = document.getElementsByName('educationalqualification');
for (var i = 0; i < parentChecks.length; i++ ) {
parentChecks[i].addEventListener('change', function(e) {
for (var j = 0; j < parentChecks.length; j++) {
var radio = document.querySelectorAll('#' + parentChecks[j].dataset.group + ' input[type=radio]');
for (var k = 0; k < radio.length; k++) {
radio[k].disabled = !parentChecks[j].checked;
if (!parentChecks[j].checked) {
radio[k].checked = false;
}
}
}
}, false);
}
Demo: http://jsfiddle.net/Q9PZF/
In order to enable/disable child elements, the parent element must be enabled.
Try this code in which parent is enabled and on clicking it, its child radio elements will be enabled.
<html>
<head>
<script type='text/javascript'>
function enableChildren() {
var bdEls = document.getElementsByName('bd');
for(var i=0;i<bdEls .length;i++)
bdEls[i].disabled=false;
}
}
</script>
</head>
<body>
<p><input type="radio" name="educationalqualification" onClick="enableChildren()" id="bdmain"/>Bachelor's Degree</p>
<label><input type="radio" name="bd" disabled="true"/>Four Years</label></li>
<label><input type="radio" name="bd" disabled="true"/>Exceeding Four Years</label></li>
</body>
</html>

Changing Date with Radio Buttons in Javascript

So I've gotten my code to display the correct current date in the 1st text box, but then when I choose one of the radio buttons to choose my "Pick-Up" date, the 2nd text box does not display the date. Basically, 1st box should show current date, 2nd box should show the date chosen from the radio buttons (imagine dropping off film that needs developed and you are choosing whether you want it 1 day, 2 days, or 3 days processing). I am including my full code so you can see what I'm doing. Can someone please show me what I'm doing wrong...
<script type="text/javascript">
function my_curr_date() {
var currentDate = new Date()
var day = currentDate.getDate();
var month = currentDate.getMonth() + 1;
var year = currentDate.getFullYear();
var my_date = month+"-"+day+"-"+year;
document.getElementById("dateField").value=my_date;
}
function orderReady(orderTime){
dateToday.setDate(dateToday.getDate()+orderTime);
var ready=dateToday.getMonth()+"/"
+dateToday.getDate()+"/"+dateToday.getFullYear();
document.getElementById("duedateField").value=ready;
}
<p>Item<br />
<input type="radio" name="item" value="print_5x7" onclick="orderReady(1)" />5x7 Prints(1 day)
<input type="radio" name="item" value="poster" onclick="orderReady(1)" />Poster (1 day)
<input type="radio" name="item" value="mug" onclick="orderReady(2)" />Coffee Mug (2 days)
<input type="radio" name="item" value="shirt" onclick="orderReady(3)" />T-shirt (3 days)</p>
<p>Today's Date<br />
<input type='text' name='dateField' id='dateField' value='' /><br />
Pick-up Date<br />
<input type='text' name='duedateField' id='duedateField' value='' /></p>
You did not set the duedateField value to the result you have calculated
i think this
function orderReady(orderTime){
dateToday.setDate(dateToday.getDate()+orderTime);
var ready=dateToday.getMonth()+"/"
+dateToday.getDate()+"/"+dateToday.getFullYear();
document.getElementById("duedateField").value=due_date;
}
should be
function orderReady(orderTime){
dateToday.setDate(dateToday.getDate()+orderTime);
var ready=dateToday.getMonth()+"/"
+dateToday.getDate()+"/"+dateToday.getFullYear();
document.getElementById("duedateField").value=ready;
}
you have to set ready for the duedateField value
it is so simple dude
function orderReady(orderTime){
dateToday.setDate(dateToday.getDate()+orderTime);
var ready=dateToday.getMonth()+"/"
+dateToday.getDate()+"/"+dateToday.getFullYear();
document.getElementById("duedateField").value=due_date;
}
you should replace value=due_date with value=ready

How can I read the value of a radio button in JavaScript?

<html>
<head>
<title>Tip Calculator</title>
<script type="text/javascript"><!--
function calculateBill(){
var check = document.getElementById("check").value;
/* I try to get the value selected */
var tipPercent = document.getElementById("tipPercent").value;
/* But it always returns the value 15 */
var tip = check * (tipPercent / 100)
var bill = 1 * check + tip;
document.getElementById('bill').innerHTML = bill;
}
--></script>
</head>
<body>
<h1 style="text-align:center">Tip Calculator</h1>
<form id="f1" name="f1">
Average Service: 15%
<input type="radio" id="tipPercent" name="tipPercent" value="15" />
<br />
Excellent Service: 20%
<input type="radio" id="tipPercent" name="tipPercent" value="20" />
<br /><br />
<label>Check Amount</label>
<input type="text" id="check" size="10" />
<input type="button" onclick="calculateBill()" value="Calculate" />
</form>
<br />
Total Bill: <p id="bill"></p>
</body>
</html>
I try to get the value selected with document.getElementById("tipPercent").value, but it always returns the value 15.
In HTML, Ids are unique. Try changing the id attributes to tipPercent1, tipPercent2, etc.
Both radio buttons have the same ID - this is incorrect in HTML, as IDs should be unique. The consequence is that document.getElementById cannot be used.
Try document.getElementsByName and loop through the resulting array to find out which one is checked and what its value is.
<input type="radio" id="tipPercent" name="tipPercent" value="15" />
<input type="radio" id="tipPercent" name="tipPercent" value="20" />
First of all, id's are required to be unique identifiers, so giving two elements the same id will make problems. document.getElementById("tipPercent") after all tries to get one element, so which of those two different input elements should it return?
Second, you can only check if a radio input is checked or not, so you will need to loop through all those inpud fields and check which one is checked to get the current value.
You have two equal ids "tipPercent". getElementById returns only one first result
You should use different ids for each radio. Try something like follows:
<script type="text/javascript">
//a variable that will hold the index number of the selected radio button
for (i=0;i<document.f1.tipPercent.length;i++){
if (document.document.f1.tipPercent[i].checked==true)
var tipPercent= document.f1.tipPercent[i].value;
}
</script>
You may want to change the calculateBill() function with the following:
function calculateBill() {
var tipPercent = 0;
var check = document.getElementById("check").value;
var radioElements = document.getElementsByName("tipPercent");
for (var i = 0; i < radioElements.length; i++) {
if (radioElements[i].checked)
tipPercent = parseInt(radioElements[i].value);
}
var tip = check * (tipPercent / 100)
var bill = 1 * check + tip;
document.getElementById('bill').innerHTML = bill;
}
Note the use of document.getElementsByName(), as Oded suggested in another answer.
You should also remove the id attribute from your radio buttions:
<input type="radio" name="tipPercent" value="15" />
<input type="radio" name="tipPercent" value="20" />
The following is a screenshot showing that the above function works fine with the 20% radio button:
How can I read the value of a radio button in JavaScript? http://img695.imageshack.us/img695/6214/tipcalc.png
The id of an element has to be unique, so you can't have two elements with the same id.
When you try to get all radio buttons as a single element, you will get one of them. Which one you get is entirely up to how the browser choose to handle the incorrect id's that you have set. You could get either of the elements, or null, depending on the implementation. In this case you happen to use a browser that gets the first element.
Give the elements their own id:
Average Sevice: 15%<input type="radio" id="tipPercent15" name="tipPercent" value="15" />
<br />
Excellent Sevice: 20%<input type="radio" id="tipPercent20" name="tipPercent" value="20" />
Getting the value attribute from the element will only get the value that you have specified for each of them. Instead you used the checked attribute:
var tipPercent;
if (document.getElementById("tipPercent15").checked) tipPercent = 15;
if (document.getElementById("tipPercent20").checked) tipPercent = 20;

Categories