JavaScript .checked on radio buttons acting odd - javascript

I am trying to force a user to select a radio option on a page, but when the user checks the 'No' option, my .checked value is coming up false.
var long = document.getElementById('long');
if(long.checked == false){
message += '- Please select your stance\\r\\n';
errors = true;
}
<input name='long' id='long' type='radio' value='Yes' >Yes
<input name='long' id='long' type='radio' value='No' >No

Both of your inputs have an id of "long", so getElementById is probably returning the first one, which is the "Yes" button.

You can't give two elements the same "id" value. You could use .getElementsByName() to find the set of radio buttons, and then look for the one that's checked, or give them two different "id" values (which is what I'd probably do).
<input name='long' id='long_yes' type='radio' value='Yes'>Yes
<input name='long' id='long_no' type='radio' value='No'>No

IDs must be unique, according to the HTML spec, therefore your code will not work as written.
If you look at it from a FORM approach, the radio buttons are an array:
var radios = document.form1.long
for(var x=0;x<radios.length;x++) {
alert(radios[x].value)
}
So you can check if YES is selected like this because YES is the first element in the array.
var radios = document.form1.long
if(radios[0].checked) { ... }

You can't have two checkboxes with the same ID property. Give them each a different ID and it should work properly.
var long = document.getElementById('longNo');
if(long.checked == false){
message += '- Please select your stance\\r\\n';
errors = true;
}
<input name='long' id='longYes' type='radio' value='Yes' >Yes
<input name='long' id='longNo' type='radio' value='No' >No

Both radio buttons have the same ID so it is only getting the first one from the getElementById call.
Change your code to use document.getElementsByName("long") then loop over and check each one:
var long = document.getElementsByName('long'), message = "";
var checked = false;
for (var i = 0; i < long.length; i++) {
if (long[i].checked) {
checked = true;
}
}
if(!checked){
message += '- Please select your stance\\r\\n';
alert(message);
}
With none checked - http://jsfiddle.net/myFhm/
With no checked - http://jsfiddle.net/myFhm/1/

You have the same id for both radio buttons, the names need to stay the same but they must have different ids
Try this:
var longYes = document.getElementById('longYes');
var longNo = document.getElementById('longNo');
if(longYes.checked == false && longNo.checked == false){
message += '- Please select your stance\\r\\n';
errors = true;
}
<input name='long' id='longYes' type='radio' value='Yes' >Yes
<input name='long' id='longNo' type='radio' value='No' >No

Related

jQuery - Count number of checked checkboxes with a given Id value

I have a page with a table on it. Two of the columns in the table are checkbox columns. Each has a different Id value. I'm trying to count, via jQuery, the number of rows in the table where one of the checkbox columns (which has an Id value of 'InChecklist') is checked. My JS function looks as follows:
function UpdateCount() {
var totalRows = $('#checklistTable tbody tr:visible').length;
var totalSeen = $(":input#InChecklist[checked='checked']").length;
$("#rowCount").text(totalRows.toString() + " species / " + totalSeen + " seen")
}
The total row count is fine. But I must not have the syntax correct for the total seen because I cannot get it to count correctly (the value is always zero). If I remove the '#InChecklist', I do get a value greater than zero, but in this case, it's counting the total checked in both checkbox columns, not the one with an Id of 'InChecklist'.
If it helps, the portion of my HTML that renders the checkboxes look as follows. It's MVC5.
<td>
<input id="InChecklist" name="item.HasBeenSeenChecklist" type="checkbox" value="true" /><input name="item.HasBeenSeenChecklist" type="hidden" value="false" />
</td>
<td>
<input id="InLifelist" name="item.HasBeenSeenLifelist" type="checkbox" value="true" /><input name="item.HasBeenSeenLifelist" type="hidden" value="false" />
</td>
Specify the ID before the :input like this
var totalSeen = $("#InChecklist:input[checked='checked']").length;
Edit
var totalSeen = $("input#InChecklist:checked").length;
EDITED:
you can try:
var totalSeen = $("#InChecklist input:checked").length;
selects all the children inputs of #InChecklist
alternatively you can use this:
var totalSeen=0;
$("#InChecklist input").each(function(){
if($(this).is('checked')){
totalSeen++;
}
});

jQuery - serializeArray() is not getting the value of the checked checkbox

I have a checkbox in a form that acts as a flag.
In order to do it, I added a hidden input element so that if the checkbox is not checked, something will still be saved
<form action="">
...
<input type="hidden" name="foo" value="no" />
<input type="checkbox" name="foo" value="yes">
...
</form>
The problem I am having is that when I
check the checkbox
then run jQuery.serializeArray() on the form
the value set for the foo element is "no"
Object { name="foo", value="no"}
Shouldn't serializeArray() emulate browser behaviour? If so, shouldn't it return "yes" if checkbox is checked?
I am using jQuery v1.10.2
In a short word: No. The serializeArray method only returns the checkbox in the case it is checked. Thus, it will ignore it as long as it remains unchecked.
In case you checked it, though, it wiill return the value of your input directly.
Check out the demo at http://api.jquery.com/serializearray/ .
Using serializeArray on a form with multiple inputs of the same name returns more than one object for each element (if checked). This means that the following HTML will return the following object. So the data in question is there and is available. Because of this I'm assuming that you're attempting to either manipulate the data to be in 1 object or you're posting it to a server which is only taking into account the data from the first value with that key. You just need to make sure that any checkbox element takes precedence.
Returned Object:
[
{
name:"foo",
value:"no"
},
{
name:"foo2",
value:"no"
},
{
name:"foo2",
value:"yes"
}
]
HTML:
<form>
<input type="hidden" name="foo" value="no" />
<input type="checkbox" name="foo" value="yes" />
<input type="hidden" name="foo2" value="no" />
<input type="checkbox" name="foo2" value="yes" checked />
</form>
JS:
console.log($('form').serializeArray());
DEMO
Another way you can do this is get rid of the hidden fields and before you submit the form go through each unchecked checkbox and check if there is any data in the serializeArray with the same name. If not just add it in there as a off.
$('#submit').on('click', function(){
var arr = $('form').serializeArray(),
names = (function(){
var n = [],
l = arr.length - 1;
for(; l>=0; l--){
n.push(arr[l].name);
}
return n;
})();
$('input[type="checkbox"]:not(:checked)').each(function(){
if($.inArray(this.name, names) === -1){
arr.push({name: this.name, value: 'off'});
}
});
console.log(arr);
});
DEMO
Using the same name for multiple fields is problematic at best and there is no standardized way that front end systems, or back end systems, will handle it.
The only reason to use the same name is if you are trying to pass some kind of a default value, like you are in the case below, where you are doing a simple yes/no.
What you want, to emulate the browser, is serialize method, not the serializeArray.
I added the form to a page -- from my console:
JSON.stringify(f.serializeArray());
"[{"name":"foo","value":"no"}]"
NO checkmark
JSON.stringify(f.serialize());
""foo=no""
Checkmark
JSON.stringify(f.serialize());
""foo=yes&foo=no""
If your back end system gets confused and is picking up the wrong value, reverse the order of your checkmark and hidden element.
FACT: jQuery serializeArray() does not include unchecked checkboxes that probably we DO need them sent to server (no problem for radios though).
SOLUTION: create a new serialize:
//1. `sel` any collection of `form` and/or `input`, `select`, `textarea`
//2. we assign value `1` if not exists to radios and checkboxes
// so that the server will receive `1` instead of `on` when checked
//3. we assign empty value to unchecked checkboxes
function serialize(sel) {
var arr,
tmp,
i,
$nodes = $(sel);
// 1. collect form controls
$nodes = $nodes.map(function(ndx){
var $n = $(this);
if($n.is('form'))
return $n.find('input, select, textarea').get();
return this;
});
// 2. replace empty values of <input>s of type=["checkbox"|"radio"] with 1
// or, we end up with "on" when checked
$nodes.each(function(ndx, el){
if ((el.nodeName.toUpperCase() == 'INPUT') && ((el.type.toUpperCase() == 'CHECKBOX') || (el.type.toUpperCase() == 'RADIO'))){
if((el.value === undefined) || (el.value == ''))
el.value = 1;
}
});
// 3. produce array of objects: {name: "field attribute name", value: "actual field value"}
arr = $nodes.serializeArray();
tmp = [];
for(i = 0; i < arr.length; i++)
tmp.push(arr[i].name);
// 4. include unchecked checkboxes
$nodes.filter('input[type="checkbox"]:not(:checked)').each(function(){
if(tmp.indexOf(this.name) < 0){
arr.push({name: this.name, value: ''});
}
});
return arr;
}
The reason we assigned empty string to unchecked checkboxes is because a checked one will submit it's value to server which is set in html and can be a zero!!!
So, an empty value denotes a unchecked checkbox.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.3/jquery.min.js"></script>
<form url="http://application.localdev/api/v1/register" method="post" id="formReg" accept-charset="utf-8">
<input type="email" placeholder="email" name="email"><br>
<input type="text" placeholder="firstname" name="firstname"><br>
<input type="text" placeholder="lastname" name="lastname"><br>
<input type="number" placeholder="zip_code" name="zip_code"><br>
<input type="checkbox" name="general" value="true"> general<br>
<input type="checkbox" name="marketing" value="true"> marketing<br>
<input type="checkbox" name="survey" value="true"> survey<br>
<button type="submit">save</button>
</form>
<script>
$(document).ready(function() {
$('#formReg').on('submit', function(e){
// validation code here
e.preventDefault();
var values = {};
$.each($('#formReg').serializeArray(), function(i, field) {
values[field.name] = field.value;
});
$('input[type="checkbox"]:not(:checked)').each(function(){
if($.inArray(this.name, values) === -1){
values[this.name] = $(this).prop('checked')
}
});
console.log(values)
});
});
</script>
serializeArray doesn't return unchecked checkbox. I try this instead of serializeArray:
$('input, select, textarea').each(
function(index){
var input = $(this);
alert('Type: ' + input.attr('type') + 'Name: ' + input.attr('name') +
'Value: ' + input.val());
}
);

How to check the radio button is selected or not

I am working on a quiz system. In that what I want to do is that the questions are collected from database and put as follow using php :
<div class="span12" style="margin-top:140px;">
<ul id="part">
<?php //print_r($quiz);
$i = 1;
foreach($quiz as $quiz)
{
echo "<li id='div$i' style='display:none;'>
<p style='font-size:20px;'><strong>Question $i </strong>: $quiz->Question </p>
<br/><div style='margin-left:60px;font-size:14px;'>
<input type='radio' name='op11' id='op1$i' value='1' style='opacity: 0;'>$quiz->op1<br/><br/>
<input type='radio' name='op11' id='op2$i' value='2' style='opacity: 0;'>$quiz->op2<br/><br/>
<input type='radio' name='op11' id='op3$i' value='3' style='opacity: 0;'>$quiz->op3<br/><br/>
<input type='radio' name='op11' id='op4$i' value='4' style='opacity: 0;'>$quiz->op4<br/><br/></div>
</li>";
$i++;
}
?>
</ul>
<div class="span6">
<button id="next" class="btn btn-info btn-large" style="float:right;">Next → </button>
</div>
</div>
Now using jquery, when I click on next button then the value of selected answer is put into an array named as answers.
When the answer is selected then the array is being created corrected, but when I am not selecting any answers then the previous value is pushed into array.
For this purpose I am using following jquery function :
<script>
$(function(){
var items = $('ul#part li');
var answers = new Array();
if(items.filter(':visible').length == 0)
{
items.first().show();
}
$('#next').click(function(e){
//e.preventDefault();
var active = items.filter(':visible:last');
active.hide();
var val = $("input:radio[name=op11]:checked").val();
console.log(val)
answers.push(val)
var next = active.next();
if (next.length)
next.show();
else{
console.log(answers);
}
});
});
</script>
For example : I have three questions and I choose the answers 2,3,1 respectively then the array of answers is [2,3,1] that is correct but suppose I do not choose any answer of question no two, and the chosen answer of first and third question is 2,3 respectively then the created array according to my code is [2,2,3]. But I need that when I do not choose any answer then the value of that answer should be 0 means for above example the array should be [2,0,3]
How can I achieve it, please help me in correcting the code
Use id for radio buttons:
example:
if(document.getElementById('op1$i').checked) {
//radio button is checked
You should check is the current answer is selected. Try something like:
if ($("input:radio[name=op11]:checked").length == 1) {
//One item checked with that name
var val = $("input:radio[name=op11]:checked").val();
} else { var val=0; } //or handle the error some other way
var val = $("input:radio[name=op11]:checked").val();
if (typeof(val) !== "undefined" && val !== null){
answers.push(val);
}else{
answers.push(0);
}
You need to check it is not null or undefined. If it is (null or undefined) then add 0, otherwise add selected value.

JavaScript function checked if a radio button is selected

<label for="Merital Status">Marital Status:</label>
<input type="radio" title="Marital Status" name="Marital_Status" id="Marital Status" value="Single"/>Single
<input type="radio" title="Marital Status" name="Marital_Status" value="Married"/>Married
<input type="radio" title="Marital Status" name="Marital_Status" value="Divorced"/>Divorced
And I want to write a JavaScript function that checks whether a radi button named "Merital_Status" is selected. I represent the function that I wrote for this purpose. The function gets as an argument the element id and returnes boolen:
function radio_button_checker(elemId)
{
var radios = document.getElementsByTagName(elemId);
var value = false;
for (var i = 0; i < radios.length; i++)
{
if (radios[i].checked)
{
value = true;
break;
}
}
return value;
}
And I invoke this function like this:
if (radio_button_checker('Marital_Status') == false)
{
alert('Please fill in your Merital Status!');
return false;
}
But it does not work. Please tell me how to modify my function in order to check if radiobutton is checked.
What you are doing is looking for an element with the tag name "Merital_Status". Replace document.getElementsByTagName with document.getElementsByName and it should work.
You are mixing ID's and NAME's.
Your radio button "set" needs to all have the same name (which you have), and if you need to refer to them individually by id, then you'll need to add an id to the last two (currently not set... and not required if you apply the labels to each individual option). You will want the label tags for each radio button as it improves the usability by allowing the user to click on the word not just the small radio button.
Marital Status:
<label><input type="radio" name="Marital_Status" value="Single"/>Single</label>
<label><input type="radio" name="Marital_Status" value="Married"/>Married</label>
<label><input type="radio" name="Marital_Status" value="Divorced"/>Divorced</label>
However when you test... you want to see that at least 1 radio in the set is checked. You can do this with:
function radioButtonChecker(fieldNAME){
var radioSet = document.forms[0].elements[fieldName];
for(var i=0;i<radioSet.length;i++){
if(radioSet[i].checked){
return true;
}
}
return false;
}
There are a few presumptions made here.
You always have more than 1 radio button in the set
Your form is the 1st (index 0) form... if not you'll need to adjust the radioSet lookup

greasemonkey script to select radio button

i'm new here. i've a question related to greasemonkey.
A page contain multiple radio buttoned values and one choice is to made, this correct choice option is hidden within the page
the radio buttons are present in the form whose structure is
<form name="bloogs" action="/myaddres.php" id="bloogs" method="post" >
then the hidden field as
<input type=hidden value="abcd" name="ans">
then all the radio button values are followed as
<input type="radio" id="r1" name="opt" value="abcd"> abcd
<input type="radio" id="r2" name="opt" value="efgh"> efgh
<input type="radio" id="r3" name="opt" value="ijkl"> ijkl
and so on
thus i need the button with value=abcd be 'checked' as soon as the page loads. Thanks
There are some ways you can use:
1 You can pre-select it by putting in selected="selected" like this:
<input type="radio" id="r1" name="opt" value="abcd" checked="checked" /> abcd
2 You can use jQuery to do it easily (I don't know whether it will be applicable in terms of greasmonky though)
$(function(){
$('input[value="abcd"]').attr('checked', 'checked');
});
3 You can loop through all elements and selected the one with raw javascript
var form = document.getElementById('bloogs');
for(var i=0; i<form.elements.length; i++)
{
if (form.elements[i].type == 'radio')
{
if (form.elements[i].value == 'abcd')
{
form.elements[i].setAttribute('checked', 'checked');
break;
}
}
}
Update:
This uses jquery and selects a radio after reading the value from hidden field:
$(function(){
$('input[value="' + $('#hidden_field_id').val() + '"]').attr('checked', 'checked');
});
Or with raw javascript:
var form = document.getElementById('bloogs');
var hidden_value = document.getElementById('hidden_field_id').value;
for(var i=0; i<form.elements.length; i++)
{
if (form.elements[i].type == 'radio')
{
if (form.elements[i].value == hidden_value)
{
form.elements[i].setAttribute('checked', 'checked');
break;
}
}
}
Update 2:
As per the name, here is how you can go about:
$(function(){
$('input[value="' + $('input[name="ans"]').val() + '"]').attr('checked', 'checked');
});
I haven't done greasemonkey, but this may help:
use jQuery and do
$('[value="abcd"]').click()
Good luck.
If you're trying to use jQuery with GreaseMonkey you're going to have to get good at writing delayed and try / retry type code. You need to start with something like this:
var _s1 = document.createElement('script');
_s1.src = 'http://www.ghostdev.com/jslib/jquery-1.3.2.js';
_s1.type = 'text/javascript';
document.getElementsByTagName('head')[0].appendChild(_s1);
That loads jQuery into your page. Next, you set something up that operates like so:
function dojQueryStuff() {
if (jQuery == undefined) {
setTimeout(dojQueryStuff, 1000);
} else {
// In here is where all of my code goes that uses jQuery.
}
}
dojQueryStuff();
You've defined a function that'll check for jQuery's presence, and if it doesn't find it try again 1 second later. That gives the script time to load. Please note, if you don't use your own copy of jQuery the one listed in my example does not provide a $ variable. At the end of the script I have var $j = jQuery.noConflict();, so you'll access the jQuery functionality via $j or jQuery.

Categories