How to check the radio button is selected or not - javascript

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.

Related

javascript/jquery: how to add/remove variables from array depending on whether a checkbox is selected

I'm outputting order addresses for a takeout restaurant: each individual order is output as a table, each table has a checkbox. I want to put the addresses into an array when the .ordercollected checkbox is ticked, and remove it from the array if it is unticked.
At the moment, rather than appending each new address I get each order address on its own in the array, which updates each time I tick the .ordercollected checkbox.
Really new to programming so any help appreciated!
//get the addresses from selected tables
$('.ordercollected').change(function() {
var activeaddress = [];
//loop through checkboxes with class .ordercollected
$(this).each(function() {
//if checkbox is ticked
if ($(this).is(':checked')) {
//get address from table
var address = $(this).closest('.ordertable').find('.address').text();
//append value of address into activeaddress array
activeaddress.push(address);
};
});
console.log('active address: ', activeaddress);
});
edit to add in the tables I am creating:
<table class="ordertable">
<tr>
<td>
<p>Order #
<?php echo $order_id; ?> —
<time datetime="<?php the_time('c'); ?>">
<?php echo the_time('d/m/Y g:i:s A'); ?>
</time>
</p>
</td>
<td>
<?php echo $order->billing_first_name . ' ' . $order->billing_last_name ?>
</td>
<td>
<?php if ($order->billing_phone) : ?>
Tel.
<?php endif; ?>
</td>
<td>
<p class="address"><?php echo $order->shipping_address_1 . ' ' . $order->shipping_postcode ?></p>
<td/>
<td>
<a class="maps-activate" href="#">Open in Maps</a>
</td>
<td>
<form action="">
<input type="checkbox" class="ordercollected" value="0" />
</form>
</td>
</tr>
</table>
Rather than remake your entire activeaddress array every time a checkbox changes, the best thing to do here would be to add or remove only the selected address when a checkbox changes. To do this activeaddress will have to be available outside of that function. I also think it will be cleaner if you use a JS object instead of an array.
var activeaddress = {};
$('.ordercollected').change(function() {
// get table id
var orderTableID = $(this).closest('.ordertable').attr('id');
// if checkbox is ticked
if($(this).is(':checked')) {
// get address from table
var address = $(this).closest('.ordertable').find('.address').text();
// append value of address into activeaddress object
activeaddress[orderTableID] = address;
} else { // checkbox is NOT ticked
// remove address from object
delete activeaddress[orderTableID];
}
console.log("active address: ", activeaddress);
});
As you can see, this code assumes that each table with class .ordertable has a unique id that can be used as the key in the activeaddress object. This is better than looping over the entire array/object each time because, especially if you have a very big set of orders. If you had included your HTML I would be able to help more, but as the question is this is as far as I can help. Let me know if you have any follow up questions.
A couple of things to note:
Using pascalCase for variable names and class names makes code more readable (e.g. activeAddress instead of activeaddress)
In my opinion, using an object instead of an array is a better way to add and remove a specific item
When asking question on SO, please give as much information as possible, such as including your HTML
Finally some links:
Adding a key value pair to an object
Removing a key value pair from an object
try something like this?
HTML:
<input type="checkbox" class="ordercollected" value="apple" />
<input type="checkbox" class="ordercollected" value="mango" />
JS
$('.ordercollected').change(function() {
var activeaddress = [];
//loop through checkboxes with class .ordercollected
if (this.checked) {
activeaddress.push(this.value);
}
else {
var index = activeaddress.indexOf(this.value);
if (index > -1) {
activeaddress.splice(index, 1);
}
}
console.log('active address: ', activeaddress);
});

Check if fields are edited or not? [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I have 7 textfields put inside a table. These textfields data i get from server when user presses submit. After filling textfield with fetched data, user submits that data to the server from a new button submit.
If the user submits the data as it is, I need to show an error message that 'at least one field must be edited'. If it edits at least one field and then submits I will update data on the server.
How can I check whether user has changed a field or not?
Problem is I will need to store data fetched for comparison, which I will have to do it in global variable in my JavaScript (which is not a good practice).
You can create an hidden input (like say #lastr2d2) named haschange like
<input type="hidden" name="haschange" id="haschange" value="0" />
and add an jquery or javascript function witch change the value of haschange from 0 to 1
when happens an event onChange on each textfields. for example you can create a function like bellow:
$(document).ready(function(){
//Check this link
$("#textfields1").change(function(){
$("#haschange").val(1);
});
});
Finally when you click the button of finally submit then you can check if haschange value is 0 or 1
--- Edit ---
If you want check for original changing (see #antindexer comments) then you can use below code
$(document).ready(function(){
//Check this link
$("#textfields1").change(function(){
var defaultValue = document.getElementById('textfields1').defaultValue;
var currentValue = document.getElementById('textfields1').value;
if( currentValue != currentValue ) {
$("#haschange").val(1);
}
});
});
You could do something like this:
Add data attributes to your input fields. Replace "<%= serverValue %>" with whatever syntax your server code uses.
<form id="form">
<table>
<tr>
<td><input type="text" value="<%= serverValue %>" data-original-value="<%= serverValue %>" /></td>
</tr>
</table>
<input type="submit" value="submit" />
</form>
And then place a script tag on the page with something like this (assuming you're using jQuery):
<script>
$(function () {
var $form = $('#form');
$form.on('submit', function (e) {
$(form).find('[data-original-value]').each(function (index, el) {
var $el = $(el);
if ($el.val() === $el.attr('data-original-value]')) {
e.preventDefault();
console.log('please edit at least one value');
}
});
});
});
</script>
Here is a JSFiddle - http://jsfiddle.net/X4S4y/1/
You can use attr data-value ( or any name you want ) to keep your original value
Example: ( Assume you use PHP )
<input type="text" value="<?php echo $value_1?>" data-value="<?php echo $value_1?>" class="input_text">
<input type="text" value="<?php echo $value_2?>" data-value="<?php echo $value_2?>" class="input_text">
<input type="text" value="<?php echo $value_3?>" data-value="<?php echo $value_3?>" class="input_text">
<input type="text" value="<?php echo $value_4?>" data-value="<?php echo $value_4?>" class="input_text">
In Jquery you can check if there are any change in input text then submit form
Example:
$(document).ready(function(){
$("form").submit(function(){
var is_changed = false;
$(".input_text").each(function(){
if ( $(this).val() == $(this).attr("data-value") {
return false;
} else {
is_changed = true;
}
});
if( is_change == true ) {
alert("Please change at least one input");
return false;
}
});
})

Check Box Values to List Jquery

Hi all I am struggling to achieve my my goal and I really need some help.
I have a list of single check boxes that I need to be able to get the values and be able to put them in to a list
So for example 3 check boxes on the screen there could be more, the user clicks on one one or all of the them, and I want to be able to output the following:
<ul>
<li>Checkbox1 Value</li>
<li>Checkbox2 Value</li>
<li>Checkbox13Value</li>
</ul>
I also need to be able to save the selected values to a hiiden field as well like this if possible:
Checkbox1 Value | Checkbox2 Value | Checkbox3 Value
There will be 2 sections on the page with where I will need this functionality so I assume I will be looking into the div tags that contain the check boxes.
I have found some code but I get it to do what I need
function updateTextArea() {
var allVals = [];
$('#c_b :checked').each(function() {
allVals.push($(this).val());
});
$('#EXCUR').val(allVals)
$('#t').val(allVals)
}
$(function() {
$('#c_b input').click(updateTextArea);
updateTextArea();
});
My HTML will be like this:
<div id="c_b">
<div>
<input type="checkbox" value="one_name">
<input type="checkbox" value="one_name1">
<input type="checkbox" value="one_name2">
</div>
</div>
<div id="c_G">
<div>
<input type="checkbox" value="one_name" checked>
<input type="checkbox" value="one_name1">
<input type="checkbox" value="one_name2">
</div>
</div>
<textarea id="t"></textarea> <!-- UL LIST SHOULD GO HERE -->
<input type="hidden" id="EXCUR" />
<div id="OP"></div>
Any help with this would be great, I just cant get it to work
Many thanks in advance
Jason
Here is a fiddle of what I think you're looking for but if you answer my comment above I'll be able to help you further.
You can use jQuery's map() to extract the values you want into an array and then join the items in the array however you want.
Something like this:
function updateTextArea() {
var items = $.map($('#c_b :checked'),function(el, ix) {
return 'Checkbox' + (ix+1) + ' ' + $(el).val();
});
if(items.length > 0) {
$('#t').val('<ul><li>' + items.join('</li><li>') + '</li></ul>');
$('#EXCUR').val(items.join(' | '))
} else {
$('#t').val('');
$('#EXCUR').val('');
}
}
$(function() {
$('#c_b input').click(updateTextArea);
updateTextArea();
});
Fiddle to demonstrate
function updateTextArea(){
var vals = []
var str="<ul>";
//iterate over checked boxes
$("input:checked").each(function(){
var v = $(this).val()
vals.push(v)
str += "<li>" + v + "</li>"
})
str+="</ul>"
$("#EXCUR").val(vals.join("|"));
$("#t").val(str);
}
$(function(){
//bind click to all checkboxes in the page
$(":checkbox").click(updateTextArea);
})

JavaScript .checked on radio buttons acting odd

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

How to Uncheck A radio button

I have two forms, one with a radio button that users must select to edit.
[form name="A"]
<li>[input type="radio" name="BookItem" value="1" /]</li>
<li>[input type="radio" name="BookItem" value="2" /]</li>
<li>[input type="radio" name="BookItem" value="3" /]</li>
[form]<p>
After "BookItem" is selected from form (A) I call the $("#EditFormWrapper").load("callEditData.cfm? ID="+ID); function to load the second form (B)
<div id="EditFormWrapper"><div></p>
<!---// begin dynamic form generated by external file callEditData.cfm //--->
[form id="editForm" name="B"]
<ul class="hourswrapper">
<li><input type="checkbox" id="TOR2Hours" class="TOR2Hours" name="TOR2Hours" value="AM2Hrs1" /> 2 Hours AM</li>
<li><input type="checkbox" id="TOR2Hours" class="TOR2Hours" name="TOR2Hours" value="PM2Hrs1" /> 2 Hours PM</li>
<li><input type="checkbox" id="TOR2Hours" class="TOR2Hours" name="TOR2Hours" value="AM2Hrs2" /> 2 Hours AM</li>
<li><input type="checkbox" id="TOR2Hours" class="TOR2Hours" name="TOR2Hours" value="PM2Hrs2" /> 2 Hours PM</li>
</ul>
[input type="image" src="images/submit-btn.gif" id="addBTN" name="addBTN" class="buttons" alt="SubmitRrequest" /]
[input type="image" src="images/cancel-btn.gif" id="editBTNcancel" name="editBTNcancel" class="buttons" alt="Cancel Request" /]
[/form]
<!---// end dynamic form from external file //--->
I want to uncheck the radio button on form (A) when user click on cancel button (editBTNcancel) in form(B).
Here's my script:
$("#editBTNcancel").live("click", function(event){
event.preventDefault();
$("#EditFormWrapper").slideUp("fast").empty();
//$('.TOR2Hours').removeAttr('checked');
$('.TOR2Hours').attr('checked', false);
});
I hope I clearly state my problem, any suggestion would be greatly appreciated!
you can access form like so ...
var exampleForm = document.forms['form_name'];
then loop through the form
for( var i=0; i<exampleForm.length; i++ ){
alert( exampleForm[i].type );
}
you can test for checked like so ...
if( exampleForm[i].checked )
to deselect the checked radio button try ...
exampleForm[i].checked=false;
the final code would look like this ...
var exampleForm = document.forms['form_name'];
for( var i=0; i<exampleForm.length; i++ ){
if( exampleForm[i].type ) == 'radio' && exampleForm[i].checked == true ){
exampleForm[i].checked = false;
}
}
I'm not sure exactly what you want but you might try using a reset input.
<input type='reset' />
Seeing as this is pretty much the easiest DOM task there is and works in every scriptable browser, I suggest not using the jQuery methods for it:
$(".TOR2Hours")[0].checked = false;
The other thing that ocurs to me is whether your selector is correct. Did you mean to select a set of elements by class or should it be an ID selector?
Your selector is simply wrong.
If you want to uncheck the radio button from first form you should use $('input[name="BookItem"]') and not $('.TOR2Hours') :
$("#editBTNcancel").on("click", function(event){
$("#EditFormWrapper").slideUp("fast").empty();
$('input[name="BookItem"]').attr('checked', false);
});
As far as which method to use to uncheck radio buttons, The following 3 methods should all work:
$('input[name="BookItem"]').attr('checked', false);
$('input[name="BookItem"]').removeAttr('checked');
$('input[name="BookItem"]').prop('checked', false);
However, check out jQuery's docs on jQuery prop() for the difference between attr() and prop().
I just discovered a great solution to this problem.
Assuming you have two radios that need to be able to be checked/unchecked, implement this code and change what's necessary:
var gift_click = 0;
function HandleGiftClick() {
if (document.getElementById('LeftPanelContent_giftDeed2').checked == true) {
gift_click++;
memorial_click = 0;
}
if (gift_click % 2 == 0) {document.getElementById('LeftPanelContent_giftDeed2').checked = false; }
}
var memorial_click = 0;
function HandleMemorialClick() {
if (document.getElementById('LeftPanelContent_memorialDeed2').checked == true) {
memorial_click++;
gift_click = 0;
}
if (memorial_click % 2 == 0) { document.getElementById('LeftPanelContent_memorialDeed2').checked = false; }
}
:) your welcome
I use this way to solve your problem in ASP.net, check this..
radioButton.InputAttributes["show"] = "false";
string clickJs = " if(this.show =='true'){this.show ='false'; this.checked = false;}else{this.show='true'; this.checked = true;};";
radioButton.Attributes["onClick"] = clickJs;
In asp.net, you can use this way to add an attribute. And you can also to add an attribute manually to the radioButton, and do the function(clickJs) to change the ckecked attributes!!!

Categories