my goal is that when the user clicks the checkbox, it will count how many checked inputs there is with the same class name. I'm trying to send the var e into the counting function but I'm not sure about the right syntax. When I replace the e in here: var n = $( '.e:checked' ).length; with a className it is working. But I need it to be dynamic.
Edit for the question:
How can I get value from the console log to var in PHP?
View
<br>
<label>
<input onclick="b(this.className)"
class="tuesdayMorBar"
type="checkbox"
name="worker_name[]"
value="<?php echo $shift['fullname'];?>" />
Javascript
function b(e) {
var countChecked = function() {
var n = $('.e:checked').length;
alert(n + (n === 1 ? " is" : " are") + " checked!");
};
countChecked();
$("input[type=checkbox]").on("click", countChecked);
}
Remove onclick="b(this.className)". Define countChecked at global level. Set click event with $("input[type=checkbox]").on("click", countChecked);. Then you can use this.className inside countChecked. It will work fine.
View
<br>
<label>
<input class="tuesdayMorBar"
type="checkbox"
name="worker_name[]"
value="<?php echo $shift['fullname'];?>" />
Javascript
var countChecked = function() {
var n = $('.' + this.className + ':checked').length;
alert(n + (n === 1 ? " is" : " are") + " checked!");
};
$("input[type=checkbox]").on("click", countChecked);
You can query for selectors with specific classes and attributes using querySelectorAll.
Try with this:
function b() {
var checkedInputs = document.querySelectorAll("input.your-class-name[type='checkbox']:checked");
alert((checkedInputs.length === 1 ? "is" : "are") + " checked!");
}
I have made a working snippet for your problem #Victoria's Secret. Comments are mentioned in the snippet itself. See if this resolves your issue.
function b(e) {
let totalChecked = 0; // initialize the variable with 0;
$("input[type=checkbox]." + e).each(function() { // check every checkbox with class e(e has className)
//console.log($(this));
if ($(this).is(":checked")) { // check if checkboxed is checked
totalChecked++; // increment every time
}
});
alert(`class ${e}: ${totalChecked}`);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<br><label><input onchange="b(this.className)" class="kaka" type="checkbox"
name="worker_name[]" value="kaka1" />kaka1
<input onchange="b(this.className)" class="kaka" type="checkbox"
name="worker_name[]" value="kaka2" />kaka2
<input onchange="b(this.className)" class="kaka" type="checkbox"
name="worker_name[]" value="kaka3" />kaka3
<br><br>
<input onchange="b(this.className)" class="lala" type="checkbox"
name="worker_name[]" value="lala1" />lala1
<input onchange="b(this.className)" class="lala" type="checkbox"
name="worker_name[]" value="lala2" />lala2
<br><br>
<input onchange="b(this.className)" class="jaja" type="checkbox"
name="worker_name[]" value="jaja1" />jaja1
<input onchange="b(this.className)" class="jaja" type="checkbox"
name="worker_name[]" value="jaja2" />jaja2
Related
I am trying to create a function in Javascript that changes an attribute on a radio button (This is so that I can detect what radio button is checked) when someone clicks off/on it. Here is a jsFiddle explaining a little more of what I am looking to do. The only problem with the code in the jsFiddle is that it is in jQuery and I do not understand enough jQuery to convert it back to its pure Javascript counterpart. Here is my attempt to convert jQuery to Javascript. I could totally just copy the code and just use it but then I would not be learning anything.
I have been trying to figure this out for the last 4 ish hours and would really appreciate any help.
Thanks,
Alex
InitRadio('name');
function InitRadio(name) {
val = 0;
$.each($(':radio[name="' + name + '"]'), function() {
$(this).val(val++);
$(this).attr('chk', '0');
$(this).on("click", function(event) {
SetRadioButtonChkProperty($(this).val(), name);
document.getElementById('1').innerText = document.getElementById('input1').getAttribute('chk');
document.getElementById('2').innerText = document.getElementById('input2').getAttribute('chk');
document.getElementById('3').innerText = document.getElementById('input3').getAttribute('chk');
});
});
document.getElementById('1').innerText = document.getElementById('input1').getAttribute('chk');
document.getElementById('2').innerText = document.getElementById('input2').getAttribute('chk');
document.getElementById('3').innerText = document.getElementById('input3').getAttribute('chk');
}
function SetRadioButtonChkProperty(val, name) {
$.each($(':radio[name="' + name + '"]'), function() {
if ($(this).val() != val)
$(this).attr('chk', '0');
else {
if ($(this).attr('chk') == '0')
$(this).attr('chk', '1');
}
});
}
p {
display: inline;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
<input type='radio' class='radio-button' name='name' id="input1">
<p id="1"></p>
<input type='radio' class='radio-button' name='name' id="input2">
<p id="2"></p>
<input type='radio' class='radio-button' name='name' id="input3">
<p id="3"></p>
My understanding is that you're partially through converting jQuery to javascript and you're having difficulty with the conversion due to lack of understanding about jQuery.
Below is my conversion with jQuery lines commented out and followed by their most direct Javascript equivalent. Keep in mind that some jQuery functions have different conversions depending on how you use them (though none of your code has this issue). Also, this code could benefit from a lot of cleanup both due to the conversion and due to issues with your own code. I've avoided doing any cleanup in favor of demonstrating the jQuery/Javascript equivalency.
InitRadio('name');
function InitRadio(name) {
val = 0;
//$.each($(':radio[name="' + name + '"]'), function() {
var radioButtons = [].slice.call(document.querySelectorAll('input[type="radio"][name="'+name+'"]'));
radioButtons.forEach(function(element,index){
//$(this).val(val++);
element.value = val++;
//$(this).attr('chk', '0');
element.setAttribute('chk','0');
//$(this).on("click", function(event) {
element.addEventListener('click',function(event){
//SetRadioButtonChkProperty($(this).val(), name);
SetRadioButtonChkProperty(element.value, name);
document.getElementById('1').innerText = document.getElementById('input1').getAttribute('chk');
document.getElementById('2').innerText = document.getElementById('input2').getAttribute('chk');
document.getElementById('3').innerText = document.getElementById('input3').getAttribute('chk');
});
});
document.getElementById('1').innerText = document.getElementById('input1').getAttribute('chk');
document.getElementById('2').innerText = document.getElementById('input2').getAttribute('chk');
document.getElementById('3').innerText = document.getElementById('input3').getAttribute('chk');
}
function SetRadioButtonChkProperty(val, name) {
//$.each($(':radio[name="' + name + '"]'), function() {
var radioButtons = [].slice.call(document.querySelectorAll('input[type="radio"][name="'+name+'"]'));
radioButtons.forEach(function(element,index){
//if ($(this).val() != val)
if (element.value != val)
//$(this).attr('chk', '0');
element.setAttribute('chk','0');
else {
//if ($(this).attr('chk') == '0')
if (element.getAttribute('chk') == '0')
//$(this).attr('chk', '1');
element.setAttribute('chk','1');
}
});
}
p {
display: inline;
}
<input type='radio' class='radio-button' name='name' id="input1">
<p id="1"></p>
<input type='radio' class='radio-button' name='name' id="input2">
<p id="2"></p>
<input type='radio' class='radio-button' name='name' id="input3">
<p id="3"></p>
Maybe this is what you want.
You can try it out in this Fiddle
HTML:
<div class="RadioList">
<input type="radio" class="radioBtn" value="r1" name="radio"> R1
<input type="radio" class="radioBtn" value="r2" name="radio"> R2
<input type="radio" class="radioBtn" value="r3" name="radio"> R3
<input type="radio" class="radioBtn" value="r4" name="radio"> R4
</div>
<div class="statusRadio">
<p>Checked Radio value: <b id="statusChecked">none</b></p>
</div>
jQuery:
$(document).ready(function() {
$(document).on('click', '.radioBtn', function() {
var valRadio = this.value;
$('#statusChecked').html(valRadio);
});
});
If you just want to know whether the radio button is checked, there's no need to set a custom attribute. Just look at its checked property.
This is relatively simple, but I'm missing something. I have 10 checkboxes on a page, in a table in a form. They all have names and id's of add0, add1, add2, etc. I wanted to build a "check/uncheck all" checkbox, but my code doesn't seem to be working. On firefox, using firebug, but it can't seem to follow the script execution.
function checkboxprocess(current)
{
for (i = 0; i < 10; i++)
{
if (current.checked)
{
document.getElementById("add" + i).checked = true;
}
else
{
document.getElementById("add" + i]).checked = false;
}
}
}
Checkbox:
echo "Select All: <input type=\"checkbox\" name=\"add\" id=\"add\" value=1 onChange=\"checkboxprocess(this)\"><br>";
You have extra ] in your code:
document.getElementById("add" + i]).checked = false;
And you don't have to check if is current checked each time in the loop, you can do it easily like this:
function checkboxprocess(current) {
for (i = 0; i < 10; i++) {
document.getElementById("add" + i).checked = current.checked;
// current.checked will return true/false
}
}
<form>
Select All: <input type="checkbox" onChange="checkboxprocess(this)">
<br /> <br />
<input type="checkbox" id="add0">
<input type="checkbox" id="add1">
<input type="checkbox" id="add2">
<input type="checkbox" id="add3">
<input type="checkbox" id="add4">
<input type="checkbox" id="add5">
<input type="checkbox" id="add6">
<input type="checkbox" id="add7">
<input type="checkbox" id="add8">
<input type="checkbox" id="add9">
</form>
I m learning jquery a bit so i created this fiddle here http://jsfiddle.net/8FXFE/17/
this is my html code
<div class="textForm">
<input type="radio" name="txtNumber" value="100" checked="checked" />100
<input type="radio" name="txtNumber" value="200" />200
<input type="radio" name="txtNumber" value="500" />500
<input type="radio" name="txtNumber" value="1000" />1000
<input type="radio" name="txtNumber" value="10000" />10000
<input type="radio" name="txtNumber" value="other" />other
<input type="text" name="other_field" id="other_field" onblur="checktext(this);"
/>
</div>
<div class="formText">
<input type="radio" name="txtSpace" value="RJ" checked="checked"
/>Space 1.
<br />
<input type="radio" name="txtSpace" value="SM" />Space 2.
<br />
</div>
<h3>Output:</h3>
this is css
#other_field {
display: none;
}
this is jquery
$(document).ready(function () {
console.log("parsed");
$("input[name='txtNumber'],input[name='txtSpace']").change(function () {
$("#output").text("Changed to "+$("input[name='txtNumber']:checked").val() + " " +$("input[name='txtSpace']:checked").val() + " +++++SOME FIXED VALUE OF TXTSPACE (i.e. SAY if RJ = 100 or if SM = 50) x VALUE OF TXTNUMBER++++++"
);
});
});
$(':radio').on('change', function () {
$('#other_field')[$(this).val() === 'other' ? 'show' : 'hide']();
});
$('#other_field').on('blur', function () {
var val = $(this).val();
if(isNaN(val)) {
alert('only numbers are allowed..');
}
else if(parseInt(val, 10) % 10 > 0) {
alert('only multiples of 10..');
}
});
How can i achieve actual output those shown in capital letters inside +++++++++++
SOME FIXED VALUE OF TXTSPACE (i.e. SAY if RJ = 100 or if SM = 50) x VALUE OF TXTNUMBER
Also How can i add dynamic value of hidden other_field (if selected)
var value = $("input[name='txtNumber']:checked").val();
if(value == "other"){
value = parseInt($("#other_field").val());
}
if(!value || isNaN(value)) value = 0;
var type = $("input[name='txtSpace']:checked").val();
var fixedMultiplier;
switch(type){
case "RJ": fixedMultiplier = 100; break;
case "SM": fixedMultiplier = 50; break;
default: fixedMultiplier = 1; break;
}
var computedValue = value * fixedMultiplier;
$("#output").text("Changed to "+ value + " " + type + " (" + computedValue + ")");
http://jsfiddle.net/8FXFE/19/
Maybe you should also add a handler to the textfield to update output on keyup.
For instance, radiobutton one = value 1, radiobutton two = value 2.
Here is the code I have:
Script file:
<script type="text/javascript">
$(document).ready(function () {
$("div[data-role='footer']").prepend('Back');
$(".Next").click(function () {
$.mobile.changePage("#" + $("#Answer").val());
});
$("input[type=radio]").click(function () {
var answer = $(this).val();
$("#Answer").val(answer);
});
$('.Answer').live("click", function () {
var NextQuestionID = $(this).attr('NextQuestionId');
if (NextQuestionID == '') {
location.href = "/Surveys/Index";
}
$("#survey").load('/Questions/GetQuestion', { Id: NextQuestionID }, function () {
$('#answerInput').textinput();
$(".Answer").button();
});
});
});
and here is my markup:
<input type="radio" name="Answer" id="radio-choice-1" value="Question2" />
<input id="Answer" class="Answer" type="hidden" value="first" />
<div class="innerspacer">
Next
</div>
How do I assign the radio button as value from 1 to 4 and sum up the value for all the question?
There is a lot going on in your question and it is unclear what you want. I'm taking a guess and assuming you have a say 5 radio buttons and you want the 5th radio button value to be the sum of the other 4 values. Is that correct?
Here is an example of doing that: jsfiddle
HTML:
<div id="container">
<label>
<input type="radio" name="something" value="1">
A?
</label>
<label>
<input type="radio" name="something" value="3">
B?
</label>
<label>
<input type="radio" name="something" value="5">
C?
</label>
<label>
<input type="radio" name="something" value="">
All?
</label>
</div>
JavaScript:
$(document).ready(function() {
var choices = $('input[name="something"]');
var total = 0;
choices.each(function() {
var choice = $(this);
var value = parseInt(choice.val(), 10);
if (!isNaN(value)) {
total += value;
}
});
choices.filter(':last').val(total);
});
You will need to adapt this to your HTML.
I have two radio groups. I wish to put a condition where if pRange is checked (val=pRange) and periodType value is 'one', 'two' or 'three', it displays a div called message. but my js code below doesn't seem to work. Any help is much appreciated.
$("input[name$='periodType']").change(function() {
var grpname = $(this).val();
var pname = $("input:radio[name='mainPeriod']:checked").val();
if (((grpname == "one") || (grpname == "two") || (grpname == "three")) && (pname=="pRange")) {
alert( pname + ' gname= ' + 'yes'); $('.message').show;
}
else {
alert( pname + ' gname= ' + 'no');
}
});
GROUP 1
<input type="radio" name="mainPeriod" id="pRange" val="pRange" />
<input type="radio" name="mainPeriod" id="pHour" val="pHour" />
<input type="radio" name="mainPeriod" id="pDay" val="pDay" />
<input type="radio" name="mainPeriod" id="pWeek" val="pWeek" />
<input type="radio" name="mainPeriod" id="pMonth" val="pMonth" />
GROUP 2
<input type="radio" name="periodType" val="one" />
<input type="radio" name="periodType" val="two" />
<input type="radio" name="periodType" val="three" />
<input type="radio" name="periodType" val="four" />
<input type="radio" name="periodType" val="five" />
<div class="message" style="display:none;">Message</div>
Whipped up a quick fiddle jsfiddle
your radio values are written as val="" not value="" don't know if that was just for the test or in your actual code.
I checked the console of your values
var grpname = $(this).val();
var pname = $("input:radio[name='mainPeriod']:checked").val();
The both return on/off only which is causing the issue. What you need to get is the .attr('val') so you can check the values
var grpname = $(this).attr('val');
var pname = $("input:radio[name='mainPeriod']:checked").attr('val');
Here's a fiddle http://jsfiddle.net/B9GyV/