Combining a Javascript function - javascript

I'm trying to create a voting style system where the user selects 2 numbers from 2 separate groups of radio buttons.
I've been able to do this, however I don't feel it's as optimised as it should be:
http://jsfiddle.net/f54wpLzg/11/
function updateQuality() {
var quality = document.getElementsByClassName('quality');
for (var i = 0, length = quality.length; i < length; i++) {
if (quality[i].checked) {
totalQuality = parseInt(quality[i].value);
break;
}
}
qualityVal = totalQuality;
document.getElementById('totalQuality').innerHTML = qualityVal;
}
Is there anyway to combine the functions? I'd prefer not to have the
onclick="updateService();
On every single radio button as well...

You can both simplify and DRY up your code. Firstly add a data attribute to the containers to identify which element should be used to display the total:
<div id="quality" data-target="totalQuality">
<input type="radio" class="quality" name="quality" value="1" />
<input type="radio" class="quality" name="quality" value="2" />
<input type="radio" class="quality" name="quality" value="3" />
</div>
<div id="service" data-target="totalService">
<input type="radio" class="service" name="service" value="1" />
<input type="radio" class="service" name="service" value="2" />
<input type="radio" class="service" name="service" value="3" />
</div>
<br>
<span id="totalQuality">0</span>
<span id="totalService">0</span>
Then you can remove the onclick attribute and use jQuery to attach a single event handler to all the radios:
$('#quality input, #service input').change(function() {
var total = $(this).parent().data('target');
$('#' + total).html($(this).val());
});
Example fiddle

Since you are using jQuery you can remove the onclick attributes and do
$('#quality').on('change', '.quality', updateQuality);
$('#service').on('change', '.service', updateService);
in your script
To use a single method you could alter a bit your html to specify a target for each group (to display the value)
<div id="quality" data-target="#totalQuality">
<input type="radio" class="quality" name="quality" value="1">
<input type="radio" class="quality" name="quality" value="2" >
<input type="radio" class="quality" name="quality" value="3">
</div>
<div id="service" data-target="#totalService">
<input type="radio" class="service" name="service" value="1">
<input type="radio" class="service" name="service" value="2">
<input type="radio" class="service" name="service" value="3">
</div>
And then you can just do
function update() {
var target = $(this).closest('[data-target]').data('target');
$(target).text(this.value);
}
$('#quality, #service').on('change', 'input', update);
But it will not update global variables (if you required those)

you could just add a parameter inside the function then put a condition inside
something like this..
function updateVote(str) {
var data = document.getElementsByClassName(str);
for (var i = 0, length = data.length; i < length; i++) {
if (data[i].checked) {
totalCount = parseInt(data[i].value);
break;
}
}
val = totalCount;
if(str=="quality")
document.getElementById('totalQuality').innerHTML = val;
}
else{
document.getElementById('totalService').innerHTML = val;
}
on your html file..
onclick="updateVote('service')"
or
onclick="updateVote('quality')"

Related

How to check if all radio buttons (that are rendered) are selected in Jquery/Javascript

I am able to check for all radio buttons that are selected.
However ,I only want to check for those that are rendered (the ones that don't have "display:none").
So if only the 1 and 3 division is selected, it should display true. Currently, it will only display true if all 3 is selected.
EDIT
: I have taken Shree33 answer and made it work with input:radio:visible.
$(document).ready(function() {
$("a").click(function(e) {
e.preventDefault();
var all_answered = true;
$(".division input:radio:visible").each(function() {
var name = $(this).attr("name");
if ($("input:radio[name=" + name + "]:checked").length == 0) {
all_answered = false;
}
});
alert(all_answered);
})
});
.test{
//display:none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
<div class="division">1
<input type="radio" name="radio1" value="false" />
<input type="radio" name="radio1" value="true" />
</div>
<div class="division test">2
<input type="radio" name="radio2" value="false" />
<input type="radio" name="radio2" value="true" />
</div>
<div class="division">3
<input type="radio" name="radio3" value="false" />
<input type="radio" name="radio3" value="true" />
</div>
<div>4
<input type="radio" name="radio4" value="false" />
<input type="radio" name="radio4" value="true" />
</div>
</form>
click
Just use a selector that excludes the non-displayed ones and compare the amount of found elements to the amount of checked radio buttons in that same set (using JQuery context). If the amounts are the same, all visible buttons have been selected.
Also, you really shouldn't use a link when you aren't actually navigating anywhere. If you just need to trigger some code (as is the case here), just about any element can have a click event handler bound to it. By not using an a, you don't have to cancel the native behavior of the link (evt.preventDefault()) and those that rely on assistive technologies, like screen readers won't have problems that occur when the screen reader encounters a link that doesn't actually navigate.
$(function() {
$("#click").click(function(e) {
// Get only the visible DIVs that have the "division" class
var visibleDIVs = $("div.division:not(.hide)");
// Now that we have a collection that contains only the div elements
// that are visible, we can get the count of them easily with: visibleDIVs.length
// We can also search the document for any checked radio buttons, but only those
// that are part of the visible divs collection like this: $("input:radio:checked", visibleDIVs).
// (the second argument (, visibleDIVs) constrains the search for radio buttons to just
// the collection of visilbe divs we've already gotten) and once we have those,
// we can also get the count of them by checking the .length of that collection.
// If the count of visible divs (visibleDIVs.length) equals the count of the visible
// checked radio buttons, then all buttons have been checked:
if(visibleDIVs.length === $("input:radio:checked", visibleDIVs).length){
alert("All Answered");
}
})
});
/* Make the clickable div look like a link */
#click {
text-decoration:underline;
cursor:pointer;
}
.hide { display:none; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
<div class="division">1
<input type="radio" name="radio1" value="false">
<input type="radio" name="radio1" value="true">
</div>
<div class="division hide">2
<input type="radio" name="radio2" value="false">
<input type="radio" name="radio2" value="true">
</div>
<div class="division">3
<input type="radio" name="radio3" value="false">
<input type="radio" name="radio3" value="true">
</div>
</form>
<div id="click">click</div>
You were close, just change the $("input:radio") selector to $("input:radio:visible"). That should work.
$(document).ready(function() {
$("a").click(function(e) {
e.preventDefault();
var all_answered = true;
$("input:radio:visible").each(function() {
var name = $(this).attr("name");
if ($("input:radio[name=" + name + "]:checked").length == 0) {
all_answered = false;
}
});
alert(all_answered);
})
});
.test{
display:none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
<div class="division">1
<input type="radio" name="radio1" value="false" />
<input type="radio" name="radio1" value="true" />
</div>
<div class="division test">2
<input type="radio" name="radio2" value="false" />
<input type="radio" name="radio2" value="true" />
</div>
<div class="division">3
<input type="radio" name="radio3" value="false" />
<input type="radio" name="radio3" value="true" />
</div>
</form>
click
Where you're getting the length,
if ($("input:radio[name=" + name + "]:checked").length == 0) {
try
if ($("input:radio[name=" + name + "]:checked").length == 0 && $(this).is(":visible") {
Is that what you are looking for? Also do you need to get the name and concat it, as won't $(this) get you your object as well?
You can check for the parent visible state too:
if (($("input:radio[name=" + name + "]:first").parent().is(':visible')) &&
($("input:radio[name=" + name + "]:checked").length == 0)) {
all_answered = false;
}
https://jsfiddle.net/StepBaro/bLp8wbnh/3/
Pls have a look at this. Seems to solve your "if visible" issue with window.getComputedStyle.

display the value of all selected radio buttons on a form

I have multiple radio buttons generated in a php loop which looks something like this
while(){
<input type="radio" id="picks'.$x.'" name="picks['.$x.']" value="'.$row['team1'].' " onclick="return disp()""><span>'.$team1.'</span>
<input type="radio" id="picks'.$x.'" name="picks['.$x.']" value="'.$row['team2'].' "onclick="return disp()""><span>'.$team2.'</span>
<input type="radio" name="picks'.$x.'" value="draw" onclick="return disp()">
}
What I want to do
Display all selected radio buttons in a div on the bottom of page
My Code
var elmnts = document.getElementById("makePicksForm").elements
var lngth = document.getElementById("makePicksForm").length;
var div = document.getElementById("dispPicks");
for (var x = 0; x < lngth; x++) {
if (elmnts[x].type == "radio" && elmnts[x].checked == true) {
div.innerHTML = elmnts[x].value;
}
}
My Problem
Only the value of first selected radio button is displayed in div, other radio buttons are ignored
My Question
Any idea how I can modify my javascript to display the values of ALL selected radio buttons?
Since you've tagged your question with jQuery, here is a jQuery solution. Run the snippet to see it work:
$(document).ready(function () {
$(':radio').change(function (e) {
//clear the div
$('#dispPicks').html('');
//update the div
$(':radio:checked').each(function (ind, ele) {
$('#dispPicks').append($(ele).val() + '<br/>');
});
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input type="radio" name="foo" value="foo1" />
<input type="radio" name="foo" value="foo2" />
<input type="radio" name="foo" value="foo3" />
<br/>
<input type="radio" name="bar" value="bar1" />
<input type="radio" name="bar" value="bar2" />
<input type="radio" name="bar" value="bar3" />
<br/>
<input type="radio" name="wow" value="wow1" />
<input type="radio" name="wow" value="wow2" />
<input type="radio" name="wow" value="wow3" />
<div id="dispPicks"></div>
You're using lngth in your for loop, but that's defined by getting an element by ID which should only be 1 element. Your loop will only run once that way...
Assuming the element with ID makePicksForm contains all your radio buttons, you need to get the length of the elements:
var elmnts = document.getElementById("makePicksForm").elements;
var div = document.getElementById("dispPicks");
for (var x = 0; x < elmnts.length; x++) {
if (elmnts[x].type == "radio" && elmnts[x].checked == true) {
div.innerHTML += elmnts[x].value;
}
}
Also, you need to add the value to the innerHTML property, using +=
as a side note: your PHP loop is creating duplicate ID's, which will result in failures in your javascript code if you need to reference the elements...
Another jQuery-Fiddle
<input type="radio" id="bob" name="boys" value="Bob"><label for="bob">Bob</label><br>
<input type="radio" id="jim" name="boys" value="Jim"><label for="jim">Jim</label><br>
<input type="radio" id="pete" name="boys" value="Pete"><label for="pete">Pete</label><br>
<input type="radio" id="mary" name="girls" value="Mary"><label for="mary">Mary</label><br>
<input type="radio" id="jane" name="girls" value="Jane"><label for="jane">Jane</label><br>
<input type="radio" id="susan" name="girls" value="Susan"><label for="susan">Susan</label>
<h3><span id="boy">?</span> and <span id="girl">?</span></h3>
$("input[name=boys]").click(function () {
$("#boy").text($(this).val());
});
$("input[name=girls]").click(function () {
$("#girl").text($(this).val());
});

default radio button selection using javascript

Here is what i wanted to accomplish. I have 2 sets of radio buttons. Radio button at the same index position in the 2 sets should not be selected at the same time. If a user tries to select, it must show alert and the defaut radio button must be selected.
Here is my html
<input type="radio" name="A" checked="checked" onclick="return check();" />
<input type="radio" name="A" onclick="return check();" />
<br />
[enter link description here][1]
<input type="radio" name="B" onclick="return check();" />
<input type="radio" name="B" checked="checked" onclick="return check();" />
Here is the JS
function check() {
//logic to check for duplicate selection
alert('Its already selected');
return false;
}
It works perfectly fine. demo
Now suppose, one of the check box is not selected , say in the second set. If the user selects first radio button from second set, which is already selected in the first, an alert is showed. But the radio button remains selected.
Here is modified html
<input type="radio" name="A" checked="checked" onclick="return check();" />
<input type="radio" name="A" onclick="return check();" />
<br />
<input type="radio" name="B" onclick="return check();" />
<input type="radio" name="B" onclick="return check();" />
Here is a demo.
NOTE: i can't use jquery since the code is already a part of some legacy application
To me it seems you should arrange the radio buttons in the other way:
<input type="radio" name="col1" value="A1">
<input type="radio" name="col2" value="A2">
<input type="radio" name="col3" value="A3">
<input type="radio" name="col1" value="B1">
<input type="radio" name="col2" value="B2">
<input type="radio" name="col3" value="B3">
That means the user only can select one value in each column without the obtrusive alert or javascript.
This works without jQuery:
// get all elements
var elements = document.querySelectorAll('input[type="radio"]');
/**
* check if radio with own name is already selected
* if so return false
*/
function check(){
var selected_name = this.name,
selected_value = this.value,
is_valid = true;
// compare with all other elements
for(var j = 0; j < len; j++) {
var el = elements[j];
// does the elemenet have the same name AND is already selected?
if(el.name != selected_name && el.value == selected_value && el.checked){
// if so, selection is not valid anymore
alert('nope')
// check current group for previous selection
is_valid = false;
break;
}
};
return is_valid;
}
/**
* bind your elements to the check-routine
*/
for(var i = 0, len = elements.length; i < len; i++) {
elements[i].onmousedown = check;
}
Here is a DEMO
Does this fit your needs?
Give value to your radios:
<input type="radio" name="A" checked="checked" value="1" />
<input type="radio" name="A" value="2" />
<br />
<input type="radio" name="B" value="1" />
<input type="radio" name="B" value="2" />
Then you can do as follows:
var radios = document.querySelectorAll('input[type="radio"]');
for(var i=0;i<radios.length;i++){
radios[i].addEventListener('click', check);
}
function check(){
var index= this.value-1;
if(this.name=='A'){
if(document.getElementsByName('B')[index].checked){
alert('already selectedin other set');
var otherIndex= (index==0)?1:0;
var other = document.getElementsByName("A")[otherIndex];
other.checked= true;
}
}
else{
if(document.getElementsByName('A')[index].checked){
alert('already selected in other set');
var otherIndex= (index==0)?1:0;
var other = document.getElementsByName("B")[otherIndex];
other.checked= true;
}
}
}
check this fiddle

How do I get the value of the checked radio button?

I have this simple script attached to a questionnaire and am having a problem getting the selected answer to show up in a textarea. Here is the script:
function check() {
var complete = 0;
var total = 0;
for (i=0;i<document.form.length;i++)
{
if (document.form.elements[i].checked == true && complete < 10) {
complete++;
total = (total) + (Math.round(document.form.elements[i].value));
}
}
if (complete >= 10) {
document.form.message.value = document.form.question1.value;
}
}
And here is the HTML:
<input type="radio" value="1" name="question1" onclick="check()"> A<br />
<input type="radio" value="2" name="question1" onclick="check()"> B<br />
<input type="radio" value="3" name="question1" onclick="check()"> C<br />
<input type="radio" value="4" name="question1" onclick="check()"> D<br />
<input type="radio" value="1" name="question2" onclick="check()"> E<br />
<input type="radio" value="2" name="question2" onclick="check()"> F<br />
<input type="radio" value="3" name="question2" onclick="check()"> G<br />
<input type="radio" value="4" name="question2" onclick="check()"> H<br />
<textarea name="message"></textarea>
I would like the value to be returned, but I am getting undefined. If I alter the line in the script that returns the text to:
document.form.message.value = document.form.question1;
I get [object NodeList]. I know I am missing something so simple but for the life of me I cannot find it.
Also, is it possible I can return the letters A through H along with the value? I know I can replace the value with the letters but need the numbers there for calculations.
My answer is going under the assumption that you would like the <textarea> to be populated with text similar to:
User answered 1 for Question A
User answered 2 for Question F
To get the A or F passed back, I needed to modify your html in the following way:
<input type="radio" value="1" name="question1" onclick="check(this, 'A')"> A<br />
<input type="radio" value="2" name="question1" onclick="check(this, 'B')"> B<br />
<input type="radio" value="3" name="question1" onclick="check(this, 'C')"> C<br />
<input type="radio" value="4" name="question1" onclick="check(this, 'D')"> D<br />
<input type="radio" value="1" name="question2" onclick="check(this, 'E')"> E<br />
<input type="radio" value="2" name="question2" onclick="check(this, 'F')"> F<br />
<input type="radio" value="3" name="question2" onclick="check(this, 'G')"> G<br />
<input type="radio" value="4" name="question2" onclick="check(this, 'H')"> H<br />
<textarea name="message"></textarea>
Otherwise, there's no actual connection between the letter and the radio input.
Anyway, here's what I done did:
I noticed that each group was repeating the same functionality, so I created a single Object Constructor:
var Answer = function () {
this.text = '';
};
this.text will contain the special answer string per group.
Now let's create the two answer group objects:
var answerOne = new Answer();
var answerTwo = new Answer();
Next comes the check() function where we pass the input element as well as it's associated answer character:
var check = function (_input, _question) {
if (_input.name === "question1") {
answerOne.text = "User answered " + _input.value + " for Question " + _question + "\n";
}
if (_input.name === "question2") {
answerTwo.text = "User answered " + _input.value + " for Question " + _question + "\n";
}
document.getElementsByName('message')[0].value = answerOne.text + answerTwo.text;
};
Now, as the user selects an answer, the appropriate answer group's string gets updated accordingly without affecting the other group's answer string.
Here's a jsfiddle with it working: http://jsfiddle.net/smokinjoe/uC76f/13/
Hope that helps!
You are referencing a form element in your script, do you define a form?
The answer seems to be addressed here
Attach event listener through javascript to radio button
Because it's a radio button, you need to loop through all values to find the one that has been selected. Something like this should work:
for (var i=0; i < document.form.question1.length; i++)
{
if (document.form.question1[i].checked)
{
document.form.message.value = document.form.question1[i].value;
}
}
}
Here you go the complete solution.
Couple of things went wrong in your code.
1. The way you get values from radio group. You need to iterate and find out which is checked
2. Setting value to textarea. You need to do getElemenetsByName[x]
<script>
function check() {
var complete = 0;
var total = 0;
var x = document.getElementsByTagName('input');
for(var k=0;k<x.length;k++){
if (x[k].checked && complete < 10) {
complete++;
total = total + Math.round(x[k].value);
}
}
(document.getElementsByName('message')[0]).value = total;
}
</script>
<input type="radio" value="1" name="question1" onclick="check()"> A<br />
<input type="radio" value="2" name="question1" onclick="check()"> B<br />
<input type="radio" value="3" name="question1" onclick="check()"> C<br />
<input type="radio" value="4" name="question1" onclick="check()"> D<br />
<input type="radio" value="1" name="question2" onclick="check()"> E<br />
<input type="radio" value="2" name="question2" onclick="check()"> F<br />
<input type="radio" value="3" name="question2" onclick="check()"> G<br />
<input type="radio" value="4" name="question2" onclick="check()"> H<br />
<textarea name="message"></textarea>
Not tested this, and as I don't know the name (or id) of your form(s), or indeed how many forms you have in your document, I have referenced your form by it's id.
function check() {
var complete = 0;
var total = 0;
var formId = 'EnterYourFormId'; // This could be passed as a paramter to the function instead (e.g. "function check(formId) {")
var _from = document.getElementById(formId); // The form could also be referenced by it's index, e.g. document.forms[0]
for (i=0; i < _from.elements.length; i++) {
if (_from.elements[i].type=='checkbox' && _from.elements[i].checked && complete < 10) {
complete++;
total = total + parseInt(_from.elements[i].value);
}
}
if (complete >= 10) {
_form.message.value = _form.question1.value;
}
}

How to find the value of a radio button with pure javascript?

<input checked=checked type="radio" name="colors" value="red" />Red
<input type="radio" name="colors" value="green" />Green
<input type="radio" name="colors" value="blue" />Blue
Given the above, I set the red button to be selected by default (so I give it the checked=checked attribute. With this, if I ever call .checked on that input element, it will always return true, even if another option is selected.
In plain javascript (no jQuery), how can you get the actual selected option?
Try this:
var options = document.getElementsByName("colors");
if (options) {
for (var i = 0; i < options.length; i++) {
if (options[i].checked){
alert(options[i].value);
}
}
}
Would be so much easier with jQuery though... just saying.
I believe you will find it in the document.all collection:
var selectedColor = document.all["colors"];
plain javasript:
document.querySelector('input[name=colors]:checked').value;
you can try like this .....
This is example
<form name="frmRadio" method="post">
<input name="choice" value="1" type="radio" />1
<input name="choice" value="2" type="radio" />2
<input name="choice" value="3" type="radio" />3
<input name="choice" value="4" type="radio" />4
</form>
function to get the selected value
<script language="JavaScript">
function getRadioValue() {
for (index=0; index < document.frmRadio.choice.length; index++) {
if (document.frmRadio.choice[index].checked) {
var radioValue = document.frmRadio.choice[index].value;
break;
}
}
}
</script>
Well, they all have the same name. So naturally at least one of them has to be selected. Give them different ID's and try again.

Categories