Getting value of radio button with Javascript in same HTML page - javascript

I'm new on javascript coding.
I'm kinda creating a survey page by myself. I will ask question as a 'True or False' and will get True as a 1 point, false as a 0 point. there will be multiple questions.
I tried to do it by getElementsByName but it didn't worked. my code is like that. can anyone help me please?
<form>
<input type="radio" name="question1" value="1" id="q1"> true
<input type="radio" name="question1" value="0" id="q1"> false
</form>
<button onclick="myFunction()">try</button>
<script>
function myFunction()
{
var x=document.getElementsByName("question1").value;
window.alert("your score is " +x);
}
</script>

Radio buttons grouped by name behave differently from select element, i.e. the group hasn't a single value. Also getElementsByName() returns a HTMLCollection, which is an array-like object (see Felix Kling's comment).
I'd suggest you to do something like this (after giving an idto the form):
function myFunction () {
var form = document.getElementById('form'), // a reference to the form element
question = form['question1'], // creates a HTMLCollection from elements having attribute name="question1"
n; // loop index
for (n = 0; n < question.length; n++) { // iterates through items in HTMLCollection
if (question[n].checked) { // checks the current item's 'checked' property
alert("your score is " + question[n].value); // found the checked-one
break; // "checked" found, no need to search more
}
}
}
A live demo at jsFiddle.
Bracket notation in question definition is used for future purposes. Just in case you'd have more radio button groups, which could be handled with this same function, you can pass the name of the group to function, and then use that argument within brackets instead of literal value ('question1').

Related

What is the opposite of :checked [duplicate]

I have a list of checkboxes:
<input type="checkbox" name="answer" id="id_1' value="1" />
<input type="checkbox" name="answer" id="id_2' value="2" />
...
<input type="checkbox" name="answer" id="id_n' value="n" />
I can collect all the values of checked checkboxes; my question is how can get all the values of unchecked checkboxes? I tried:
$("input:unchecked").val();
to get an unchecked checkbox's value, but I got:
Syntax error, unrecognized expression: unchecked.
Can anybody shed a light on this issue?
Thank you!
As the error message states, jQuery does not include a :unchecked selector.
Instead, you need to invert the :checked selector:
$("input:checkbox:not(:checked)")
$("input:checkbox:not(:checked)") Will get you the unchecked boxes.
Also it can be achieved with pure js in such a way:
var matches = document.querySelectorAll('input[type="checkbox"]:not(:checked)');
You can do so by extending jQuerys functionality. This will shorten the amount of text you have to write for the selector.
$.extend($.expr[':'], {
unchecked: function (obj) {
return ((obj.type == 'checkbox' || obj.type == 'radio') && !$(obj).is(':checked'));
}
}
);
You can then use $("input:unchecked") to get all checkboxes and radio buttons that are checked.
$("input[type='checkbox']:not(:checked):not('\#chkAll\')").map(function () {
var a = "";
if (this.name != "chkAll") {
a = this.name + "|off";
}
return a;
}).get().join();
This will retrieve all unchecked checkboxes and exclude the "chkAll" checkbox that I use to check|uncheck all checkboxes. Since I want to know what value I'm passing to the database I set these to off, since the checkboxes give me a value of on.
//looking for unchecked checkboxes, but don’t include the checkbox all that checks or unchecks all checkboxes
//.map - Pass each element in the current matched set through a function, producing a new jQuery object containing the return values.
//.get - Retrieve the DOM elements matched by the jQuery object.
//.join - (javascript) joins the elements of an array into a string, and returns the string.The elements will be separated by a specified separator. The default separator is comma (,).
You can use like this :
$(":checkbox:not(:checked)")
To select by class, you can do this:
$("input.className:checkbox:not(:checked)")
$(".clscss-row").each(function () {
if ($(this).find(".po-checkbox").not(":checked")) {
// enter your code here
} });

How do I retrieve values from checkboxes in JavaScript, using onchange to trigger a function?

I'm a High School student who takes a programming course (JavaScript) at school. We just had a test (which I miserably failed), but we are allowed to try again.
I have a couple of checkboxes. They all have an onchange which triggers a function later. I want to retrieve their values when I click on the checkboxes.
I've browsed around here a bit and seen something called jQuery. I have no idea what that is, so I would highly appreciate to get my help in pure JavaScript.
Okay, here is what I have of code. Note: Some variables and such are in Norwegian. I don't think it should be a problem, since I show the references to all.
My inputs (checkboxes):
<input type="checkbox" class="tur" value="0" onchange="funcSjekkBoks(this)">
<input type="checkbox" class="tur" value="1" onchange="funcSjekkBoks(this)">
<input type="checkbox" class="tur" value="2" onchange="funcSjekkBoks(this)">
<input type="checkbox" class="tur" value="3" onchange="funcSjekkBoks(this)">
<input type="checkbox" class="tur" value="4" onchange="funcSjekkBoks(this)">
I only need their value to be numbers, since I will use those in reference to an array list I have later.
Here is my function:
var inputTur = document.getElementsByClassName("tur");
console.log(inputTur);
function funcSjekkBoks(checkboxEl) {
var resultatListe = [];
if (checkboxEl.checked) {
resultatListe.push(inputTur.value);
console.log(resultatListe);
}
else {
console.log("usant")
}
}
What I would like to happen (if all checkboxes are checked from top to bottom):
resultatListe = [0, 1, 2, 3, 4]
When I uncheck a checkbox, it's value will be removed from the array.
Here is what currently happens:
When I check a checkbox I get [undefined] in my console, when I uncheck a checkbox I get usant (although that is the expected response, I haven't worked with the else part of my if-sentence yet.)
Below code will work for you:
var resultatListe = [];
function funcSjekkBoks(checkboxEl) {
var value = parseInt(checkboxEl.value);
if (checkboxEl.checked) {
resultatListe.push(value);
console.log(resultatListe);
}
else {
console.log("usant");
var indexToRemove = resultatListe.indexOf(value);
resultatListe.splice(indexToRemove,1);
}
}
You need to keep the array resultatListe outside the function other it will be initialized to empty everytime a checkbox is checked/un-checked, triggering the onchange handler. You were getting undefined as you were accessing 'value' property on HTMLCollection object which does not contain that property. Read more about it on MDN
var inputTur = document.getElementsByClassName("tur");
var resultatListe = [];
console.log(inputTur);
function funcSjekkBoks(checkboxEl) {
if (checkboxEl.checked) {
resultatListe.push(parseInt(checkboxEl.value));
}
else {
resultatListe = resultatListe.filter(d => d != checkboxEl.value)
}
console.log(resultatListe);
}
There were 2 mistakes in your logic:
1) You need to define resultatListe outside the function so that it won't get initialized to an empty array everytime
2) In you code resultatListe.push(inputTur.value); inputTur is the HTMLCollection of checkboxes whereas you need the single checkbox.
For the else logic, if the value of each checkbox is going to be unique you can use array.prototype.filter method to filter out the value of checkbox from resultatListe

Best way to detect changes when values might not exist anymore?

I've been trying to detect changes in multiple inputs on a web page.
To do that, I used a query like this:
$(.InputClass).data("InitialValues",$(.InputClass).serialize())
(I'm not in front of my code sadly but it should look like this)
Then later I compared the values in .data with the new values and it worked perfectly fine but for one single thing, a GridGiew.
In that GridView, the user can add or remove rows dynamically (adding or removing data). If I save the initial values in the .data, it will be destroyed with the row and both will be undefined (initial and new values). The input I need to check is hidden and the unique value can be accessed using $(.myNewClass).val() (as I tried to use a different class for this specific hidden input)
I was wondering what woudld be the best solution.
I tried to concatenate all val() from myNewClass using something like
var initialValues = $(.myNewClass).map(Function(x){
return x.val()
})
(Again, I am not in fron of my computer, and I am new to javascript and jquery).
It was not working. Intellisense could not see .map (and it crashed).
If there is no better way, could you help me with the way I record the concatenation of my val() values?
If there is a better way, could you please point me in the right direction?
Thank you very much!
At
var initialValues = $(.myNewClass).map(Function(x){
return x.val()
})
.myNewClass should be a String , within quotes $(".myNewClass") .
F at .map() callback should be lowercase f , to prevent calling native Function .
x at first parameter of .map(x) would be the index of the element or object within the collection of elements or objects - not the element ; try adjusting to .map() callback function parameters to .map(function(index, elem)) to correspond to their values within loop.
x.val() within .map() would return error , as x would be the DOM element <input> , not the jQuery object $(x) ; try utilizing x.value , or el.value to retrieve value of current element within loop
Try opening console , clicking "Run code snippet" twice at stacksnippets below . The alert does not appear to be called at stacksnippets, though the error message displays the contents of items at console
// create `items` object ,
// containing `initialValues` , `currentValues` properties,
// set initially to `undefined` ; set to `Array`
// at `load` , `unload` events
var items = {
"initialValues": undefined,
"currentValues": undefined
};
$(window)
.on({
"load": function() {
// set `items.initialValues` array
items.initialValues = $(".myNewClass").map(function(index, elem) {
return elem.value
}).toArray();
console.log("load", items);
},
"unload": function() {
// set `items.currentValues` array
items.currentValues = $(".myNewClass").map(function(index, elem) {
return elem.value
}).toArray();
console.log("unload", items);
alert(JSON.stringify(items, null, 4));
}
});
$(function() {
setTimeout(function() {
// do stuff
// remove first `.myNewClass` element "row"
$(".myNewClass").first().remove();
// change element at index 3 within `.myNewClass` collection
$(".myNewClass").eq(3).val(123);
}, 1500);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js">
</script>
<input type="hidden" value="1" class="myNewClass" />
<input type="hidden" value="2" class="myNewClass" />
<input type="hidden" value="3" class="myNewClass" />
<input type="hidden" value="4" class="myNewClass" />
<input type="hidden" value="5" class="myNewClass" />
See .map() , .toArray()

How to receive values from 'HTML form' to a javascript code? [duplicate]

This question already has answers here:
How can we access the value of a radio button using the DOM?
(12 answers)
Closed 9 years ago.
The form includes Radio, Select, Input etc..
var variable = document.getElementById('anyId').value;
It works fine with input element, but with radio button element it's not working as desired!
On my HTML page (for radio) the code looks something like this,
<input type="radio" id="radioValue" name="radio" value="2">Radio_1
<input type="radio" id="radioValue" name="radio" value="1">Radio_2
and in the script
var radio_value = document.getElementById('radioValue').value;
radio_value is always equal to 2, it doesn't matter whether you select radio_1 or radio_2.
By using getElementsByName
var selectedradio;
var radios = document.getElementsByName("radio");
for(var i = 0; i < radios.length; i++) {
if(radios[i].checked == true) {
alert(radios[i].value);
selectedradio = radios[i].value;
}
}
ID's must be unique. So you should change your code to this:
<input type="radio" id="radioValue1" name="radio" value="2">Radio_1
<input type="radio" id="radioValue2" name="radio" value="1">Radio_2
And then you can get those values by:
var radio_value1 = document.getElementById('radioValue1').value;
var radio_value2 = document.getElementById('radioValue2').value;
//or
var radio_value=document.querySelector('input[name="radio"]:checked').value;
// in this last case you don't need even to have id's in the buttons
Otherwise trying to read two values with the same ID will give you just the first one of them.
Pure javascript for most modern browsers.(works also in ie 9)
if you have just one form and only one group of radio's use querySelector
it's the new proper way.
var radio_value=document.querySelector('input[type="radio"]:checked').value
You can also easely extend it if you have multiple radio groups and forms.
var radio_value=document.querySelector('#YOURFORM input[name="radio"]:checked').value

Naming Lots of Input Checkboxes with a Counter

This is a pretty straightforward question, but I wasn't able to find the answer to it.
Is it possible to do something like this with JavaScript and HTML? So below the names of the checkboxes in order would be 1, 2, 3, 4
<input type="checkbox" name=counter()>
<input type="checkbox" name=counter()>
<input type="checkbox" name=counter()>
<input type="checkbox" name=counter()>
function counter() {
i++;
return i;
}
No, but yes in a different way. Don't include the name attribute (or set the value as ""), and put this code after your checkboxes:
<script type="text/javascript">
var chx = document.getElementsByTagName("input");
for (var i = 0; i < chx.length; i++) {
var cur = chx[i];
if (cur.type === "checkbox") {
cur.name = "checkbox" + i;
}
}
</script>
DEMO: http://jsfiddle.net/bLRLA/
The checkboxes' names will be in the format "checkbox#". This starts counting at 0. If you want to start the names with 1 instead (like you did say), use cur.name = "checkbox" + i + 1;.
Another option for getting the checkboxes is using:
var chx = document.querySelectorAll('input[type="checkbox"]');
With this, you don't have to check the .type inside the for loop.
In either case, it's probably better not to use document, and instead use some more specific container of these elements, so that not all checkboxes are targeted/modified...unless that's exactly what you want.
In the demo, I added extra code so that when you click on the checkbox, it will alert its name, just to prove it's being set properly. That code obviously isn't necessary for what you need....just the code above.
This code could be run immediately after the checkboxes, at the end of the <body>, or in window.onload.
You can get a nodeList of all inputs on the page and then loop through them adding the loop index to whatever the common name string you want for those that have a type of "checkbox". In the following example I have used Array.forEach and Function.call to treat the array like nodeList as an array, to make looping simple.
<input type="checkbox" />
<input type="checkbox" />
<input type="checkbox" />
<input type="checkbox" />
var inputs = document.getElementsByTagName("input");
Array.prototype.forEach.call(inputs, function (input, index) {
if (input.type === "checkbox") {
inputs.name = "box" + index;
}
});
on jsfiddle
Finally, though this has been demonstrated as possible, I think you need to be asking yourself the question "why would I do it this way?". Perhaps there is a better alternative available to you.
Since you're most probably processing the form server-side. you can possibly not bother altering the form markup client-side. For example, simple changing your form markup to the following will do the trick:
<input type="checkbox" value="One" name=counter[]>
<input type="checkbox" value="Two" name=counter[]>
<input type="checkbox" value="Tre" name=counter[]>
<input type="checkbox" value="For" name=counter[]>
Then, for example, using PHP server-side:
<?php
if ( isset( $_REQUEST['counter'] ) ) {
print_r( $_REQUEST['counter'] );
}
?>
I think you're better off creating the elements in code. add a script tag in replace of your controls and use something like this (create a containing div, I've specified one named container in my code below)
for(int i = 0; i < 4; i ++){
var el = document.createElement('input');
el.setAttribute('name', 'chk' + i.toString());
document.getElementById('container').appendChild(el);
}

Categories

Resources