convert Checkbox into radio button using javascript? - 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.

Related

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
}
});

Jquery , Html Append value to textfield when Checkbox is checked

I have a list of four check boxes which are as shown below :
<input type="checkbox" class="checkboxstyle" id="id_peer_educator" value="Peer Educator"/>Peer Educator<br>
<input type="checkbox" class="checkboxstyle" id="id_chw" value="CHW"/>CHW<br>
<input type="checkbox" class="checkboxstyle" id="id_health_provider" value="Health Prvider"/>Health Provider<br>
<input type="checkbox" class="checkboxstyle" id="id_purchase" value="Purchase"/>Purchase<br>
<input type="text" id="CD_Supplr" class="CD_Supplr" name="CD_Supplr" placeholder=" Suppliers : "/>
The first four are check boxes while the last one is a textbox. How can I append data to the text-field Suppliers ? (When it is checked , it should be appended to the text field Supplier, if it is unchecked, then the value should be removed from the text field supplier) .
I tried implementing it the following way :
var CD_Supplr = $('#CD_Supplr').val();
var id_peer_educator = $('#id_peer_educator').val();
var id_chw = $('#id_chw').val();
var id_health_provider = $('#id_health_provider').val();
var id_purchase = $('#id_purchase').val();
$('#id_peer_educator').click(function () {
$('#CD_Supplr').val(CD_Supplr + "," + id_peer_educator;
});
$('#id_chw').click(function () {
$('#CD_Supplr').val(CD_Supplr + "," + id_chw;
});
But it's not working,what's the best way to implement it?
You can use an array to add value when checkbox is checked and remove it when unchecked and use join() function to join the array values by dispay in input.
Hope this helps.
var selected_checkbox=[];
$('.checkboxstyle').change(function()
{
if($(this).is(':checked'))
{
//If checked add it to the array
selected_checkbox.push($(this).val());
}
else
{
//If unchecked remove it from array
for (var i=selected_checkbox.length-1; i>=0; i--)
{
if (selected_checkbox[i] === $(this).val())
selected_checkbox.splice(i, 1);
}
}
$('#CD_Supplr').val(selected_checkbox.join(','));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="checkbox" class="checkboxstyle" id="id_peer_educator" value="Peer Educator"/>Peer Educator<br>
<input type="checkbox" class="checkboxstyle" id="id_chw" value="CHW"/>CHW<br>
<input type="checkbox" class="checkboxstyle" id="id_health_provider" value="Health Prvider"/>Health Provider<br>
<input type="checkbox" class="checkboxstyle" id="id_purchase" value="Purchase"/>Purchase<br>
<input type="text" id="CD_Supplr" class="CD_Supplr" name="CD_Supplr" size='50' placeholder=" Suppliers : "/>
Demo
$('.checkboxstyle').on("change",function ()
{
var str ="";
$('.checkboxstyle:checked').each(function()
{
str+= $(this).val()+" ";
});
$('#CD_Supplr').val(str);
});
Add listeners to the change event on the checkboxex, then using match() find out if the value of a checkbox is NOT already there in the CD_Suplr textbox. Then, use the result of this condition to add/remove the checkbox values:
var $target = $('#CD_Supplr');
$('[type="checkbox"]').change(function(){
if($target.val() == ''){
$target.val('Supplier: '); //default text
}
if(!$target.val().match($(this).val())){
var text = $target.val();
$target.val(text + ' ' + $(this).val() + ', ');
} else {
var text = $target.val();
$target.val(text.replace($(this).val()+', ', ''));
}
//make sure the last comma is removed
$target.val($target.val().replace(/\,$/, ''));
});
JSFiddle Demo.

Get list of all checkboxes with checked and unchecked status

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);
});

fill input if radio is selected using jquery

I have a input and two radio buttons.
The input accepts a number for a time period a person lives at a residence.
The radio buttons are months & years.
I want to fill a 2nd input using the 1st input value (numerical value of length at residence) and either the value for months or years based on the radio selected.
I've made it spit out the time, but it spits out the value for both radio button because I did not have an if statement to check. I already have jquery in my form and it works. I just need this small section of my form to work.
My question is, how do I set up the conditional statement for checking what radio is checked?
HTML
<input type="number" value="" required maxlength="5" class="form-control" name="homeLength" id="homeLength">
<input type="radio" id="years" value="Years" name="length" required> Years
<input type="radio" id="months" value="Months" name="length"> Months
jQuery
$('#months').click(function () {
if ($(this).attr("checked") == "checked") {
$('#homeLength, #months').bind('keypress blur', function () {
$('#homeTime').val($('#homeLength').val() + ' ' + ' ' + $('#months').val() + ' ' + ' ');
});
}
});
$('#years').click(function () {
if ($(this).attr("checked") == "checked") {
$('#homeLength, #years').bind('keypress blur', function () {
$('#homeTime').val($('#homeLength').val() + ' ' + ' ' + $('#years').val() + ' ');
});
}
});
You need to check the checked radio's value only and do that on keyup/blur AND click of any radio
$(function() {
$('#homeLength').on('keyup, blur', function() {
var lgt = $("input:radio[name=length]:checked").val();
$('#homeTime').val($(this).val() + ' '+lgt);
});
$("input:radio[name=length]").on("click",function() {
$('#homeLength').blur(); // trigger the blur event of the field to update
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input type="number" value="" required maxlength="5" class="form-control" name="homeLength" id="homeLength">
<input type="radio" id="years" value="Years" name="length" required> Years
<input type="radio" id="months" value="Months" name="length"> Months
<hr/>
<input type="text" value="" class="form-control" name="homeTime" id="homeTime">
The most usable conditional statement for this kind of checkings is:
if ($(this).is(':checked'))
so as you can see the response is boolean.
Replave your javascript code with this
$('#months').click(function() {
console.log($(this).prop('id'));
$('#homeLength, #months').bind('keypress blur', function() {
$('#homeTime').val($('#homeLength').val() + ' ' + ' '+$('#months').val()+ ' ' + ' ');
});
});
$('#years').click(function() {
console.log($(this).prop('id'));
$('#homeLength, #years').bind('keypress blur', function() {
$('#homeTime').val($('#homeLength').val() + ' ' + ' ' + $('#years').val()+ ' ');
});
});
whenever user will select any radio button u can get its id by
$(this).prop('id');
its value by
$(this).prop('value');

Sync Selected Radio Button between 2 radio button groups - Opposites

I need to do something similar to JQuery Sync Selected Radio Button between 2 radio button groups.
I have 2 radio groups -
<input type="radio" name="radio_A" id="radio_A_1" value="1" />1st
<input type="radio" name="radio_A" id="radio_A_2" value="2" />2nd
<input type="radio" name="radio_B" id="radio_B_1" value="1" />1st
<input type="radio" name="radio_B" id="radio_B_2" value="2" />2nd
When radio_A_1 is checked, I need radio_B_2 synced/checked. The relationships would be-
radio_A_1=>radio_B_2
radio_A_2=>radio_B_1
radio_B_1=>radio_A_2
radio_B_2=>radio_A_1
Using the answer provided #8804502
$('input[name=radio_A]').change(function() {
var index = $(this).index('input[name=radio_A]');
console.log(index);
$('input[name=radio_B]:eq(' + index + ')').attr('checked','checked');
});
I get same=>same, but only when A changes-
radio_A_1=>radio_B_1
radio_A_2=>radio_B_2
So if I copy it, changing it if from A=>B to B=>A-
$('input[name=radio_A]').change(function() {
var index = $(this).index('input[name=radio_A]');
console.log(index);
$('input[name=radio_B]:eq(' + index + ')').attr('checked','checked');
});
$('input[name=radio_B]').change(function() {
var index = $(this).index('input[name=radio_B]');
console.log(index);
$('input[name=radio_A]:eq(' + index + ')').attr('checked','checked');
});
I get same=>same, when either A or B changes -
radio_A_1=>radio_B_1
radio_A_2=>radio_B_2
radio_B_1=>radio_A_1
radio_B_2=>radio_A_2
How can I sync them 1=>2/2=>1, instead of 1=>1/2=>2? And can it be done with 1 block of code, instead of 2?
You need to add some code to take the index of the element just clicked and set it to 0 if it is 1, or 1 if it is 0. The first way that came to mind is as follows:
$('input[name=radio_A]').change(function() {
var index = $(this).index('input[name=radio_A]') === 1 ? 0 : 1;
$('input[name=radio_B]:eq(' + index + ')').attr('checked', 'checked');
});
$('input[name=radio_B]').change(function() {
var index = $(this).index('input[name=radio_B]') === 1 ? 0 : 1;
$('input[name=radio_A]:eq(' + index + ')').attr('checked', 'checked');
});
Demo: http://jsfiddle.net/cTQeJ/1/
Though you could also try:
var index = 1 - $(this).index('input[name=radio_A]');
(Or the following demo uses kind of a fun hack if you like to make your code confusing: http://jsfiddle.net/cTQeJ/)
"And can it be done with 1 block of code, instead of 2?"
If you can modify the html slightly it is pretty easy with a single, short code block. Try a change like this:
<input type="radio" name="radio_A" data-sync="1" value="1" />1st
<input type="radio" name="radio_A" data-sync="2" value="2" />2nd
<input type="radio" name="radio_B" data-sync="2" value="1" />1st
<input type="radio" name="radio_B" data-sync="1" value="2" />2nd
I've added a data-sync attribute to each radio button (and removed the id attribute since it wasn't being used, but obviously you can leave that in if needed). Then you can write a simple function like this:
var $radios = $('input[data-sync]');
$radios.change(function() {
$radios.filter('[data-sync="' + $(this).attr('data-sync') + '"]')
.prop('checked', true);
});​
...that basically says whenever any of the radio buttons is checked, find all other radio buttons with a data-sync attribute of the same value and check them too.
Note that this will work with more than two groups, as shown in this demo: http://jsfiddle.net/cTQeJ/2/

Categories

Resources