Get list of all checkboxes with checked and unchecked status - javascript

I have following code, to show an image along with its checkbox. It is either enabled or disabled
if($ring["status"] != '1')
echo '<td><input type="checkbox" name="ringIds[]" value="'.$ring["id"].'">'
. '<input type="image" onClick="openGalleryRing(\''.$ring['imagePath'].'\', \''.$ring['id'].'\');" src="http://thevowapp.com/iphoneapp/vowstore/rings/'. $ring['imagePath'] .'" name="checked" value="' . $ring['id'].'" data-my-info="'. $ring['ringSetName'] .'" style="width:200px; height:200px; margin-left: 10px;"></td>';
else
echo '<td><input type="checkbox" checked="checked" name="ringIds[]" value="'.$ring["id"].'">'
. '<input type="image" onClick="openGalleryRing(\''.$ring['imagePath'].'\', \''.$ring['id'].'\');" src="http://thevowapp.com/iphoneapp/vowstore/rings/'. $ring['imagePath'] .'" name="checked" value="' . $ring['id'].'" data-my-info="'. $ring['ringSetName'] .'" style="width:200px; height:200px; margin-left: 10px;"></td>';
In my javascript i am using something like
$('.updateBtn').on('click', function()
{
var checked = $('input[name="ringIds[]"]:checked').serialize();
if(checked !== '')
window.location.href = 'actions.php?j=24&' + checked;
else
alert('No Rings are selected');
});
This works, i can get all the checked checkboxes, but what i actually want is to get all hte list of checkboxes, which are checked and which are not. How can i modify this code?

Note: Only "successful controls" are serialized to the string. No
submit button value is serialized since the form was not submitted
using a button. For a form element's value to be included in the
serialized string, the element must have a name attribute. Values from
checkboxes and radio buttons (inputs of type "radio" or "checkbox")
are included only if they are checked. Data from file select elements
is not serialized.
Thus .serialize() will return only checked checkboxes whether or not you include the pseudo selector :checked.
You may want to use .each() or .map() to get the unselected checkboxes.
var unchecked = "";
$('input[name="ringIds[]"]').not(':checked').each(function() {
unchecked += (unchecked.length ? '&' + '') + this.name + '=' + this.value;
});
Or:
var unchecked = $('input[name="ringIds[]"]').not(':checked').map(function(i,v) {
return this.name + '=' + this.value;
})
.get().join('&');

Here is the code which you are looking for:
$('.updateBtn').on('click', function()
{
var check_boxes = $('input[name="ringIds[]"]').serialize();
// Try below line to see all checkboxes
console.log(check_boxes);
});

Related

convert Checkbox into radio button using javascript?

I am trying to convert checkbox into radio button which is working partially , but not deselecting previous selected radio button.I am looking solution to show one button at a time as a selected.
var layers = {
'Esri_WorldImagery': Esri_WorldImagery.addTo(this.baseMap),
'World_Topo_Map': World_Topo_Map//.addTo(this.baseMap)
};
var layerHtml = '<ul class="fa-ul">';
for (var key in layers) {
if (layers.hasOwnProperty(key)) {
var state = this.baseMap.hasLayer(layers[key]) ? 'checked="checked"' : '';
//layerHtml += '<li><label><input type="checkbox" ' + state + ' value="' + key + '" >' + key + '</label>';
layerHtml += '<li><label><input type="radio" ' + state + ' value="' + key + '" >' + key + '</label>';
}
}
layerHtml += '</ul>';
var widget = $('<div id="layer-control" class="sidebar-widget">' + layerHtml + '</div>');
widget.on('click', 'input[type="radio"]', function (e) {
var was_Active = $(this).prop('checked');
var value = $(this).val();
if (was_Active) {
layers[value].addTo(self.baseMap);
}
else {
self.baseMap.removeLayer(layers[value]);
}
});
First, regarding the current code with radio elements, as #Aswin Ramesh has told you, yo should add the name attribute. From MDN:
A radio group is defined by giving each of radio buttons in the group the same name. Once a radio group is established, selecting any radio button in that group automatically deselects any currently-selected radio button in the same group.
Besides the shape (circle vs square) that's the only difference between the radio and checkbox elements. So consider that checkboxes that behave like radio buttons might be confusing for the user.
That said, if you really want to replicate that functionality on checkboxes, use JavaScript to deselect all the elements but the one which raised the click event.
$('#checkboxes').on('click', ':checkbox', function(e) {
$('#checkboxes :checkbox').each(function() {
if (this != e.target)
$(this).prop('checked', false);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="radios">
<input type="radio" name="rOptions" value="radio1" checked>
<input type="radio" name="rOptions" value="radio2">
<input type="radio" name="rOptions" value="radio3">
</div>
<div id="checkboxes">
<input type="checkbox" value="checkbox1" checked>
<input type="checkbox" value="checkbox2">
<input type="checkbox" value="checkbox3">
</div>
Note: you forgot to close the <li> tags.

How to insert the value of dynamically radio button using PHP?

I have a html table, each table row have a radio button dynamically generated. Each option in the radio button have a unique id that generated dynamically also. But this id is not yet save in the database.
How to insert the option id? And how to update the option answer in that option id? Please help me. I tried to insert the values but I have no luck
Scenario:
There's a default value for the radio button, which is "No". When the user change the default value, there's a confirmation box that will ask the user if he/she want to processed. If the user click "Ok" the default value will change into "Yes".
PHP for html table:
echo '<td id="resumeFile'.$optionId.'">' . $record_s->attachment_resume_id . '</td>';
echo '<td id="processedYes><label for="Yes">Yes</label>
<input type="radio" id="processedOptionYes'.$optionId.'" name="processedOption" value="Yes" onclick="proccessedCheck('.$optionId.',\'Yes\')"/>
<label for="No">No</label>
<input type="radio" id="processedOptionNo'.$optionId.'" name="processedOption" value="No" checked="checked" onclick="proccessedCheck('.$optionId.',\'No\')" echo $record_s->process_resume === "No" checked="checked"/>/>No</td>';
echo '</tr>';
}
echo '</table>';
}
if (isset($_POST['optionId']) && $_POST['optionId']){
$optionId = $_POST['optionId'];
$queryOptionId = $wpdb->query("INSERT INTO resume_databank(process_resume_id) VALUES ('$optionId')");
}
Hidden Form:
<form id='hiddenForm' method='POST' action=''>
<input type="hidden" id="inputHidden1" name="optionId" />
<input type="hidden" id="inputHidden2" name="optionAnswer" />
</form>
JS:
function proccessedCheck(optionId,optionAnswer){
if(optionAnswer == 'Yes'){
if (confirm('You have chosen ' + optionAnswer + ', is this correct?')){
jQuery("#processedOptionYes" + optionId).attr('disabled',true);
jQuery("#processedOptionNo" + optionId).attr('disabled',true);
var withlink = jQuery("#resumeFile"+ optionId).html();
var withoutlink = jQuery(withlink).html();
jQuery("#resumeFile"+optionId).html("").append(withoutlink);
jQuery("#inputHidden1").val(optionId);
jQuery("#inputHidden2").val(optionAnswer);
jQuery("#hiddenForm").submit();
}
}
}
Hi u can change the jquery by using like below with using a class instead of function in the input type, add a class radiods to input type= radio.
$(".radiods").click(function(){
var clickid = this.id;
if($('input:radio[name=processedOption]:checked').val() == "Yes")
{
if (confirm('You have chosen YES, is this correct?'))
{
$("#inputHidden1").val(clickid);
$("#inputHidden2").val("Yes");
}
}
});
and then use ajax to update in database,so no need of form
I dont use Jquery, but Javascript is pretty simple to read the value. It is the same as a checkbox value in that it is .checked when true.
Loop through your form fields looking for checked items
var formObj = document.getElementById('hiddenform');
for(var i = 0;i < formObj.elements.length;i++){
radiovalues[] = escape(formObj.elements[id].checked);
}
Most fields have a value, ie text, hidden, password etc
escape(formObj.elements[id].value)
The checkbox and radio doesnt have a value, you are looking for "checked" which will return true or false.

Verify checked checkbox javascript

I'm trying to update in "real time" if I check and uncheck in a list of checkboxs.
With this code:
window.onload = function () {
var input = document.getElementById('listTaxi');
function check() {
var a = input.checked ? "checked" : "not checked";
console.log(a);
}
input.onchange = check;
check();
}
I can do this for one checkbox, but how can I make for multiple checkboxs? A list(div) of checkboxs?
Thanks!!
Assign a class on all checkboxes you want to check if checked or not.
Checkboxes
<input type="checkbox" class="checkboxes" id="checkbox1"/>
<input type="checkbox" class="checkboxes" id="checkbox2"/>
<input type="checkbox" class="checkboxes" id="checkbox3"/>
<input type="checkbox" class="checkboxes" id="checkbox4"/>
Pure Javascript
// getting all checkboxes
var checkboxes = document.getElementsByClassName('checkboxes');
// go through all checkboxes
for(var i = 0; i <= checkboxes.length - 1; i++){
checkboxes[i].onchange = function(e){
alert('Element with id ' + e.target.getAttribute('id') + ' is checked ' +e.target.checked);
}
}
Codepen http://codepen.io/todorutandrei/pen/rLBQOX
Or you can use JQUERY - is it more simple
$('.checkboxes').change(function(){
var item = $(this);
alert('Element with id ' + item.attr('id') + ' is ' + item.is(':checked'));
})
Codepen http://codepen.io/todorutandrei/pen/MegzwR
make them all the same class or give the all the same custom attribute
$(".classname")
$("input[name='customName'])
Jquery will then select all with those
$("#id").change(function() {//if using class name or custom attr loop through the return elements and use a function below to handle the cases
if($(this).is(":checked")) {
//code if checked
}
else{
//code if not checked
}
});

Insert in query string only the values of the selected checkboxes with their respective quantities inputs

I'm having a problem here in mounting a query string with the variables that I need.
I have the following part of the code:
echo "<form class='additionals'>";
foreach($connection->query($sql2) as $additional)
{
echo "
<input class='additional-checkbox' type='checkbox' name='additional_id' value='{$additional['additional_id']}'/>{$additional['additional_name']} - ${$additional['additional_price']} <input type='number' name='additional_quantity' value='1' min='1' max='5'/><br/>
";
}
echo "</form>";
In this code snippet I get the values from database and insert each of them into a checkbox.
To get the values of the selected checkboxes I'm using jQuery:
$(document).ready(function()
{
$('.add').on('submit', function()
{
var product_id = $(this).closest('tr').find('.product-id').text();
var product_name = $(this).closest('tr').find('.product-name').text();
var quantity = $(this).closest('tr').find('input').val();
if ($(this).closest('tr').find('input.additional-checkbox').is(':checked'))
{
var additionals = $(this).closest('tr').find( '.additionals' ).serialize();
window.location.href = "add_to_cart.php?product_id=" + product_id + "&product_name=" + product_name + "&quantity=" + quantity + "&" + additionals;
}
else
{
window.location.href = "add_to_cart.php?product_id=" + product_id + "&product_name=" + product_name + "&quantity=" + quantity;
}
return false;
});
});
Let's assume that only the checkbox with value 1 is selected and the input in front related to their quantity value is 3. My output should be something like:
add_to_cart.php?product_id=4&product_name=Pizza&quantity=1&additional_id=1&additional_quantity=3
Here is my little problem. I have part of the output as I want, but the values of the other quantity inputs are also inserted to serialize. By this way the output is like:
add_to_cart.php?product_id=4&product_name=Pizza&quantity=1&additional_id=1&additional_quantity=3&additional_quantity=1&additional_quantity=1
How to make only the quantity of inputs relating to the selected checkboxes appear in the Query String? How to relate the inputs of checkboxes with the quantity inputs?
It looks like
var additionals = $(this).closest('tr').find('.additionals')
returns multiple forms. Is it possible, that in single TR you have more than one such form?
Try this
<input name="quantity_id" type="checkbox" data-quantity-input="quantity">
<input name="quantity" type="input" value="">
// get the data-quantity-input
var qtyInput = $(this).data('quantity-input');
// find the corresponding value if checkbox is checked
find('input[name='"+ qtyInput +'"]').val();
"data" attribute should be unique. You can use the index inside "for" loop.

Unable to check if a javascript checkbox array element is checked or not?

What is want is - when the checkbox is checked option no. 5 in select list will be selected and when the checkbox is unchecked option no. 0 will be selected in the select list.
The select list and the checkboxes are generated dynamically in the php code as below :
echo "<select name='coupons".$i."' id='coupons".$i."'>";
------- All Options --------
echo "</select>";
<input type='checkbox' name='myCheckbox[]' value='<?php echo $i."_".$row->id; ?>' onclick='setCCode("myCheckbox[]",<?php echo $i;?>)'>
-----------------------------------------------------------------------------
Solved the second requirement on my own now ..... thanks to all for your inputs
just added the following line in the checkAll() within the for loop
setCCode(children[i],i+1);
The javascript function :
function setCCode(checkbox_name,i)
{
var form_object = document.getElementsByName(checkbox_name+"["+i+"]");
var selname = document.getElementsByName("coupons"+i)[0];
if(form_object.checked) {
selname.selectedIndex = 5;
}
else {
selname.selectedIndex = 0;
}
}
The above issue is solved....... thanks to all
Now what i need to do is when a user checks a checkbox to select or deselect all the dynamically generated checkboxes on the form the above logic should work.
<input type='checkbox' name='checkall' onChange="checkAll(this, 'myCheckbox[]')">
<span class="chkall">Check / Uncheck All</span>
<input type='checkbox' name='myCheckbox[]' value='<?php echo $i."_".$row->id; ?>' onclick='setCCode(this,<?php echo $i;?>)'>
The javascript code i am using to select/deselect all checkboxes on form is as below :
function checkAll(parent, field)
{
var children = document.getElementsByName(field);
var newValue = parent.checked;
for (i = 0; i < children.length; i++){
if (children[i].disabled == false) {
children[i].checked = newValue;
}
}
}
function setCCode(Sender,i)
{
document.getElementsByName("coupons"+i)[0].selectedIndex = Sender.checked ? 5 : 0;
}
getElementsByName returns an array of objects. Replace the line with:
var form_object = document.getElementsByName(checkbox_name+"["+i+"]")[0];
You can pass refference to the checkbox itself as a parameter
<input type='checkbox' name='myCheckbox[]' value='<?php echo $i."_".$row->id; ?>' onclick='setCCode(this,<?php echo $i;?>)'>
function setCCode(Sender,i)
{
document.getElementsByName("coupons"+i)[0].selectedIndex = Sender.checked ? 5 : 0;
}
If you have a reference to the form that the checkbox is in, and it has a unique name in the form, then you can access it as:
form_object = form.elements[ checkbox_name + "[" + i + "]" ];
and you can also use the ternary operator to make the code more concise:
selname.selectedIndex = form_object.checked? 5 : 0;
Edit
Sorry, missed the obvious. If you pass a refereference to the checkbox in the handler, then you can also get the form (all form controls have a form property that references the form they are in). So as Jan Pfeifer suggested (abbreviated markup):
<input ... onclick='setCCode(this, <?php echo $i;?>)'>
then the script is just:
function setCCode(checkbox, i)
{
checkbox.form.elements['coupons' + i].selectedIndex = checkbox.checked? 5 : 0;
}

Categories

Resources