Dynamically, check radio button with for loop - javascript

I'm trying to create a 5 star radio picker.
This is the 1 of the radio buttons:
<input onclick="check(3)" type="radio" name="three" id="num_3_star" value="3">
After the method gets called and "3" is passed on this is my javascript function:
function check(stars)
{
for(i = 0 ; i < stars; i++)
{
document.getElementById("num_" + stars + "_star").checked = true;
}
}
When I run the code, it does not perform the checked to = true, though if remove the for loop, it works just fine.
Any ideas why the for loop is preventing from checking the radio boxes?
This is my entire code:
<script>
function check(stars)
{
for(i = 0 ; i < stars; i++)
{
document.getElementById("num_" + stars + "_star").checked = true;
}
}
</script>
<form>
<input onclick="check(1)" type="radio" name="one" id="num_1_star" value="1">
<input onclick="check(2)" type="radio" name="two" id="num_2_star" value="2">
<input onclick="check(3)" type="radio" name="three" id="num_3_star" value="3">
<input onclick="check(4)" type="radio" name="four" id="num_4_star" value="4">
<input onclick="check(5)" type="radio" name="five" id="num_5_star" value="5">
</form>
Thanks!

i had to be 1 initially as ids are starting from 1
Also reset all the checked status when click is initiated! Use i instead of stars in getElementById
Try this:
function check(stars) {
for (var j = 1; j <= 5; j++) {
document.getElementById("num_" + j + "_star").checked = false;
}
for (var i = 1; i <= stars; i++) {
document.getElementById("num_" + i + "_star").checked = true;
}
}
<input onclick="check(1)" type="radio" name="one" id="num_1_star" value="1">
<input onclick="check(2)" type="radio" name="two" id="num_2_star" value="2">
<input onclick="check(3)" type="radio" name="three" id="num_3_star" value="3">
<input onclick="check(4)" type="radio" name="four" id="num_4_star" value="4">
<input onclick="check(5)" type="radio" name="five" id="num_5_star" value="5">

Put var before the iteration variable i. You are creating a global variable.

Related

get all elements by class name of text boxes in javascript

I have a few text boxes on my javascript page with the class of textID. So if I were to do
function UpdateTotals() {
getText = document.getElementsByClassName('textID').value;
}
All of the values will be numbers, so how do I add all of the values in this class together? Example: there are 4 text boxes, each one has the number 2 in it. I want to get 8 by adding them all together (but only the text boxes that are in that class).
One example could be using Array.prototype.reduce()
const textID = document.querySelectorAll('.textID');
const total = [...textID].reduce((a, el) => a + (+el.textContent.trim()), 0);
console.log(total); // 8
<div class="textID">2</div>
<div class="textID">2</div>
<div class="textID">2</div>
<div class="textID">2</div>
For INPUT elements:
const textID = document.querySelectorAll('.textID');
const total = [...textID].reduce((a, el) => a + (+el.value), 0);
console.log(total); // 8
<input class="textID" type="number" value="2">
<input class="textID" type="number" value="2">
<input class="textID" type="number" value="2">
<input class="textID" type="number" value="2">
Using NodeList.forEach()
const textID = document.querySelectorAll('.textID');
let total = 0;
textID.forEach(el => total += +el.value);
console.log(total); // 8
<input class="textID" type="number" value="2">
<input class="textID" type="number" value="2">
<input class="textID" type="number" value="2">
<input class="textID" type="number" value="2">
Try this code:
HTML code:
<input type="checkbox" class="textID" name="qty" value="2"/> 2<br>
<input type="checkbox" class="textID" name="qty" value="2"/> 2<br>
<input type="checkbox" class="textID" name="qty" value="2"/> 2<br>
<input type="checkbox" class="textID" name="qty" value="2"/> 2<br>
<br><br>
Total : <input type="text" name="total" id="total"/>
Sum
JS code:
window.sumInputs = function() {
var inputs = document.getElementsByClassName('textID'),
result = document.getElementById('total'),
checkboxes = document.querySelectorAll(`input[name="qty"]:checked`),
sum = 0;
for(var i=0; i<checkboxes.length; i++) {
var ip = inputs[i];
if (ip.name && ip.name.indexOf("total") < 0) {
sum += parseInt(ip.value) || 0;
}
}
result.value = sum;
}
Try it in jsfiddle : https://jsfiddle.net/u62tyj45/

Get Radio Button Value into another function in javascript

Here is my radio buttons' code:
<div class="col-md-6 alert alert-success" dir="rtl" >
Select an Option <br>
<label class="radio">
<input type="radio" name="sp" id="sp1" value="1" checked>
<span style="margin-right: 30px;">Option-1</span>
</label><br>
<label class="radio-inline">
<input type="radio" name="sp" id="sp2" value="2">
<span style="margin-right: 30px;">Option-2</span>
</label>
</div>
and I want to get value of button in following script audio src, so by clicking on radio button I can switch between media folder:
function PlayVerse(surat,n) {
var aud=document.getElementById("myaudio");
aud.src= "http://data.quranacademy.com/AUDIOS/Media-/01_"
+TxtFormat(surat,"000")
+"_"
+TxtFormat(n,"000")
+".mp3";
}
var x = document.getElementsByTagName("IMG");
var i;
for (i = 0; i < x.length; i++) {
x[i].style = 'display: inline-block; '
+'border: 1px solid #ddd; '
+'border-radius: 4px; padding: 5px;';
}
Try something like this with plain javascript
function PlayVerse(){
var radio = document.getElementsByName('sp');
var check;
for (var i = 0, length = radio.length; i < length; i++)
{
if (radio[i].checked)
{
console.log(radio[i].value);
check = radio[i].value;
break;
}
}
}
<div class="col-md-6 alert alert-success" dir="rtl" >Select an Option</br>
<label class="radio">
<input type="radio" name="sp" id="sp1" value="1" checked><span style="margin-right: 30px;">Option-1
</span></label></br>
<label class="radio-inline">
<input type="radio" name="sp" id="sp2" value="2"><span style="margin-right: 30px;">Pption-2
</span></label>
</div>
<button type = "button" onclick="PlayVerse();">Get Radio button value </button>
if you want to do something by clicking on radio button it can help you
window.onload=function(){
(function (){
var radios = document.getElementsByName('sp');
radios.forEach(function(radio){
radio.onclick = function(){
alert(this.value);
//do something
}
})
})();
}
Red color
Yelow color
<p id="demo"></p>
<script>
function myFunction() {
//var x = document.getElementById("myRadioRed").value;
//document.getElementById("demo").innerHTML = x;
var radios = document.getElementsByName('colors');
for (var i = 0, length = radios.length; i < length; i++) {
if (radios[i].checked) {
// do whatever you want with the checked radio
document.getElementById("demo").innerHTML = radios[i].value;
// only one radio can be logically checked, don't check the rest
break;
}
}
}
</script>
<input type="radio" name="colors" value="red" id="myRadioRed" onchange="myFunction()" checked="checked" />Red color
<input type="radio" name="colors" value="yellow" id="myRadioYellow" onchange="myFunction()" />Yelow color
<p id="demo"></p>
function PlayVerse() {
var selected_radio_button_value = getRadioButtonValue("sp");
alert(selected_radio_button_value);
}
function getRadioButtonValue(elementName) {
var array1 = document.getElementsByName(elementName), rValue = null;
array1.forEach(function(element) {
if( element.checked ) {
rValue = element.value;
return true;
}
});
return rValue;
}
<div class="col-md-6 alert alert-success" dir="rtl" >Select an Option</br>
<label class="radio">
<input type="radio" name="sp" id="sp1" value="1" checked><span style="margin-right: 30px;">Option-1
</span></label></br>
<label class="radio-inline">
<input type="radio" name="sp" id="sp2" value="2"><span style="margin-right: 30px;">Pption-2
</span></label>
</div>
<button type = "button" onclick="PlayVerse();">Get Radio button value </button>
here you can get value of radio button using javascript i have created an function which will give you value of selected radio button you can store that value in variable and access it anywhere you want you can do it in both way
Here is how you can get value of radio button which one is checked. Get all NodeList by getElementsByName and iterate over each one and check if it is checked.
function getVal(elementName) {
var radios = document.getElementsByName(elementName), rValue = null;
for (var i = 0; i < radios.length; i++) {
if (radios[i].checked) {
rValue = radios[i].value;
break;
}
}
console.log(rValue);
}
<div class="col-md-6 alert alert-success" dir="rtl" >
Select an Option <br>
<label class="radio">
<input type="radio" onchange="getVal('sp')" name="sp" id="sp1" value="1" checked>
<span style="margin-right: 30px;">Option-1</span>
</label><br>
<label class="radio-inline">
<input type="radio" onchange="getVal('sp')" name="sp" id="sp2" value="2">
<span style="margin-right: 30px;">Option-2</span>
</label>
</div>

Disable last checkbox multiple choice required

Scenario :
I have a vote page, you have to select 3 of 4 candidates from the list.
Needs :
I need to make the last checkbox disabled after checking 3 of them (4).
Code :
HTML
<input class="cb" type="checkbox" name="condidate" value="1" onchange="cbChange(this)" />
<input class="cb" type="checkbox" name="condidate" value="2" onchange="cbChange(this)"/>
<input class="cb" type="checkbox" name="condidate" value="3" onchange="cbChange(this)"/>
<input class="cb" type="checkbox" name="condidate" value="4" onchange="cbChange(this)"/>
JS
function cbChange(obj) {
var cbs = document.getElementsByClassName("cb");
for (var i = 0; i < cbs.length - 3; i++) {
cbs[i].disabled = true;
}
obj.disabled = false;
}
Question :
How Can I make the last choice disabled after selecting the 3 others.
you need to call cbChange on click event of checkboxes.
function cbChange(obj) {
var cbs = document.getElementsByClassName("cb");
var checkCount = 0;
for (var i = 0; i < cbs.length; i++) {
if (cbs[i].checked === true)
checkCount++;
cbs[i].disabled = false;
}
if (checkCount >= 3){
for (var i = 0; i < cbs.length; i++) {
if (cbs[i].checked === false)
cbs[i].disabled = true;
}
}
}
<input class="cb" type="checkbox" name="condidate" value="1" onclick="cbChange(this)"/>
<input class="cb" type="checkbox" name="condidate" value="2" onclick="cbChange(this)"/>
<input class="cb" type="checkbox" name="condidate" value="3" onclick="cbChange(this)"/>
<input class="cb" type="checkbox" name="condidate" value="4" onclick="cbChange(this)"/>
When one of the checkboxes has changed, count the number that are unchecked. If there is only one, you can disable it; otherwise, if one is disabled, it must be re-enabled.

Javascript - get the radio button index number

**I have a php page with an array of option like this... and I need to get by javascript **the index of the selected option. Above I put the code of the javascript that is not working... Any help will be appreciated!
<input type="radio" name="option[1]" value="1">
<input type="radio" name="option[1]" value="2">
<input type="radio" name="option[1]" value="3">
<input type="radio" name="option[1]" value="4">
<input type="radio" name="option[2]" value="1">
<input type="radio" name="option[2]" value="2">
<input type="radio" name="option[2]" value="3">
<input type="radio" name="option[2]" value="4">
<input type="radio" name="option[3]" value="1">
<input type="radio" name="option[3]" value="2">
<input type="radio" name="option[3]" value="3">
<input type="radio" name="option[3]" value="4">
...
Can anyone help me?
I am trying something like this but it didnĀ“t work
<script type="text/javascript">
function validateForm(form) {
for (var i = 0; i < form.elements.length; i++ ) {
if (form.elements[i].type == 'radio') {
if (form.elements[i].checked == true) {
if (form.elements[i].value == 1 || form.elements[i].value == 6){
var comentario=document.getElementsByName('comentario[]'[i]);
var opcao = form.elements[i];
alert(clickedElm(opcao));
submitFlag = true;
if (comentario.value.length < 100){
submitFlag=false;
alert(i);
}
return submitFlag;
}
}
}
}
}
function clickedElm(element)
{
var index = 0;
for (var i = 0; document.forms[0].elements.length; i++)
{
if (document.forms[0].elements[i] == element)
{
index = i;
}
}
return index;
}
</script>
If I correctly understood the questuion, it can be solved like this:
$(document).on('change','input[type=radio]', function(){
alert($(this).prop('name').charAt(7));
});
Here is fiddle http://jsfiddle.net/Goodluck/ynkgr/
the name attribute is used for group the radio buttons, you have to use the id attribute to access the control asking if it's checked.
Example
<html>
<head>
</head>
<body>
<form id="frmTest">
<input type="radio" name="option[1]" id="option1-item1" value="1" >
<input type="radio" name="option[1]" id="option1-item2" value="2" >
<input type="radio" name="option[1]" id="option1-item3" value="3" >
<input type="radio" name="option[1]" id="option1-item4" value="4" >
<input type="radio" name="option[2]" id="option2-item1" value="1" >
<input type="radio" name="option[2]" id="option2-item2" value="2" >
<input type="radio" name="option[2]" id="option2-item3" value="3" >
<input type="radio" name="option[2]" id="option2-item4" value="4" >
<input type="radio" name="option[3]" id="option3-item1" value="1" >
<input type="radio" name="option[3]" id="option3-item2" value="2" >
<input type="radio" name="option[3]" id="option3-item3" value="3" >
<input type="radio" name="option[3]" id="option3-item4" value="4" >
</form>
<input type="button" onclick="validateForm(document.getElementById('frmTest'))" />
<script type="text/javascript">
function validateForm(form) {
for (var i = 0; i < form.elements.length; i++ ) {
if (form.elements[i].type == 'radio') {
if (form.elements[i].checked == true) {
if (form.elements[i].value == 1 || form.elements[i].value == 6){
var comentario=document.getElementsByName('comentario[]'[i]);
var opcao = form.elements[i];
alert(clickedElm(opcao));
submitFlag = true;
if (comentario.value.length < 100){
submitFlag=false;
alert(i);
}
return submitFlag;
}
}
}
}
}
function clickedElm(element)
{
return element.id;
}
</script>
</body>
</html>
You forgot to check the condition in this line:
(the loop in function clickedElm)
for (var i = 0; document.forms[0].elements.length; i++)
So, you enter in an infinite loop.
the correct line:
for (var i = 0; i < document.forms[0].elements.length; i++)

Checkbox value added by default

I'm attempting to make a code that will display the divs when checked and also add the values of the checkboxes together. I've managed to come up with this but now I want to make some of the checkboxes checked and their values added together by default. I can make the checkbox checked, however, I need the value to be added by default as well. Any help would be appreciated. Here is my code:
a
This is the first paragraph
This is the second paragraph
This is the third paragraph
<form name="formex">
<input onclick="clickCh(this) ; showPara()" class="classone" type="checkbox" name="one" value="10"> $10.00<br>
<input onclick="clickCh(this) ; showPara()" type="checkbox" name="two" value="12"> $12.00<br>
<input onclick="clickCh(this) ; showPara()" type="checkbox" name="three" value="1"> $1.00<br>
<input onclick="clickCh(this) ; showPara()" type="checkbox" name="four" value="2"> $2.00<br>
<input onclick="clickCh(this) ; showPara()" type="checkbox" name="five" value="24"> $24.00<br>
<br>
<input id="total" type="text" name="total">
</form>
My script
<script language="JavaScript" type="text/javascript">
var total = document.getElementById("total")
function clickCh(caller){
if(caller.checked){
add(caller)
} else {
subtract(caller)
}}
function add(caller){ total.value = total.value*1 + caller.value*1}
function subtract(caller){ total.value = total.value*1 - caller.value*1}
function showPara()
{
document.getElementById("first").style.display=(document.formex.one.checked) ? "inline" : "none";
document.getElementById("second").style.display=(document.formex.two.checked) ? "inline" : "none";
document.getElementById("third").style.display=(document.formex.three.checked) ? "inline" : "none";
return true;
}
</script>
jsFiddle: http://jsfiddle.net/TCZ6t/1/
You should be able to just add the attribute "checked" to the end of the tag to have it checked by default. In other words, if I wanted $10 to be checked by default I would just change the tag to:
<input checked onclick="clickCh(this) ; showPara()" class="classone" type="checkbox" name="one" value="10" checked> $10.00<br>
You could just loop all the checked checkboxes and call the add method like
var els = document.querySelectorAll('form[name="formex"] input[type="checkbox"]');
for (var i = 0; i < els.length; i++) {
if (els[i].checked) {
add(els[i])
}
}
Demo:
var total = document.getElementById("total");
function clickCh(caller) {
if (caller.checked) {
add(caller)
} else {
subtract(caller)
}
}
function add(caller) {
total.value = total.value * 1 + caller.value * 1
}
function subtract(caller) {
total.value = total.value * 1 - caller.value * 1
}
function showPara() {
document.getElementById("first").style.display = (document.formex.one.checked) ? "inline" : "none";
document.getElementById("second").style.display = (document.formex.two.checked) ? "inline" : "none";
document.getElementById("third").style.display = (document.formex.three.checked) ? "inline" : "none";
return true;
}
var els = document.querySelectorAll('form[name="formex"] input[type="checkbox"]');
for (var i = 0; i < els.length; i++) {
if (els[i].checked) {
add(els[i])
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="first" style="display:none;">This is the first paragraph</div> <br />
<div id="second" >This is the second paragraph</div> <br />
<div id="third" style="display:none;">This is the third paragraph</div> <br />
<form name="formex">
<input onclick="clickCh(this) ; showPara()" class="classone" type="checkbox" name="one" value="10"/> $10.00<br/>
<input onclick="clickCh(this) ; showPara()" type="checkbox" name="two" value="12"/> $12.00<br/>
<input onclick="clickCh(this) ; showPara()" type="checkbox" name="three" value="1"/> $1.00<br/>
<input onclick="clickCh(this) ; showPara()" type="checkbox" name="four" value="2" checked /> $2.00<br/>
<input onclick="clickCh(this) ; showPara()" type="checkbox" name="five" value="24" checked /> $24.00<br/>
<br/>
<input id="total" type="text" name="total"/>
</form>

Categories