I want to get value from radio button by onclick and I will use this value for sql query.
What should I do for this?
I want when I click on radio button I will get the value of the button and this value will work for sql query to change data or information
I use php and mysql.
<td><input type="radio" name="ac" value="AC"/>AC</td>
<td><input type="radio" name="ac" value="Non AC" />Non AC</td>
First, note that you shouldn't use tabular elements for non-tabular data. But it makes sense using label element, and use change event instead of click.
<div id="wrapper">
<label><input type="radio" name="ac" value="AC"/>AC</label>
<label><input type="radio" name="ac" value="Non AC" />Non AC</label>
</div>
To get the value, you can use event delegation:
document.getElementById('wrapper').onchange = function(e) {
/* Maybe you should also check: e.target.type==='radio' */
if(e.target.tagName.toLowerCase() === 'input') {
var value = e.target.value;
/* do something */
}
};
Demo
Another possibility is creating an event listener for each radio:
var els = document.getElementById('wrapper').getElementsByTagName('input'),
handler = function() {
var value = this.value;
/* do something */
};
for(var i = 0; i<els.length; ++i) {
els[i].onchange = handler;
}
Demo
Related
I want on page load to check a radio button by default using pure javascript.
Here is my code:
window.onload = function() {
var radioman = document.getElementById("btn-Man").value;
radioman.checked = true;
}
<input required="required" type="radio" id="btn-Man" name="gender" value="1" class="radio-class">
<label for="btn-Man">Man</label>
<input required="required" type="radio" id="btn-Woman" name="gender" value="2" class="radio-class">
<label for="btn-Woman">Woman</label>
but it doesn't work. On page load the first radio button with the id="btn-Man" should be checked. What in the world i 'm doing wrong ?
Try without '.value' like:
var radioman = document.getElementById("btn-Man");
radioman.checked = true;
remove the .value on setting the variable
window.onload = function() {
var radioman = document.getElementById("btn-Man");
radioman.checked = true;
}
No need for variable assignment. Just change it's value on load.
You also don't need to get it's value.
When you include the value, your variable will hold the value of the element selected and you'll lose the reference to the element thus changing the element's value is not possible
window.onload = function() {
document.getElementById("btn-Man").checked = true;
};
We have two radio buttons when we change the button need to call function. Below is my code.
<input id="ordertype" type="radio" align="top" name="ordertype" value="NEW ORDER" checked="">
<input id="ordertype" type="radio" align="top" name="ordertype" value="ADDITIONAL ORDER (add items to previous order)">
Jquery code
jQuery(document).ready(function(){
$('input:radio[name="ordertype"]').change(function(){
if($(this).val() === 'ADDITIONAL ORDER (add items to previous order)'){
var removepages = 'boothlightingDiv';
}else{
var removepages = 'furnishingsprovidedDiv';
}
});
});
Call function ToggleDiv('boothsizeDiv', removepages);
Based radio button need to change the ToggleDiv function parameter.Any help?
I would do something like this:
http://jsfiddle.net/bobrierton/5Lc17p1t/1/
$(document).on('change', 'input[name=ordertype]', function() {
var value = $(this).val();
if (value == "ADDITIONAL ORDER (add items to previous order)") {
//whatever your trying to do
var removepages = 'boothlightingDiv';
}else{
//or whatever your trying to do
var removepages = 'furnishingsprovidedDiv';
}
alert(removepages)
});
instead of $(this) use $('input:radio[name="order type"]:checked') to access the one that is checked, because when one changes, they both change.
I am using a plugin that only triggers on click of checkbox , I need All button checkbox to existing code.
I have made it so that on click of ALL CHECKBOX I manually TRIGGER click selecting all checkbox and firing the existing jquery code
The problem comes when user clicks on one of checkbox I want that option to be as selected option so if all checkbox are checked (including the All) and user clicks on 3rd checkbox it should automatically select 3rd checkbox trigger click on all others (making them unchecked) including all
but my own conflicts i.e. my trigger clicks doesn't lets this happen and code gets into loop between All checkbox checked clicks and single checkbox click
I have created JS Fiddle.
In short I need toggle from checkbox button as well if all are selected on click on one of the checkbox it should make that one selected and rest all unselected
Here is the jQuery code
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.1/jquery.min.js"></script>
<script>
jQuery(window).ready(function() {
//check ALl checkbox onClick
jQuery('body').on('click', '.chktaxoall,.chkcmfall',function (e) {
if(this.checked){
var i = 0;
var sList;
jQuery(this).closest('.togglecheck').find('input:checkbox').each(function () {
var sThisVal = (this.checked ? "1" : "0");
i++;
if(sThisVal==0 && i>1){
jQuery(this).trigger('click','bot');
}
});
}
else{
jQuery(this).closest('.togglecheck').find('input:checkbox').prop('checked', this.checked);
}
});
//IF ALL IS SELECTED but if a user clicks on a particular checkbox uncheck all except the one user checked
jQuery('body').on('click', '.wrap_acf input:checkbox',function (e) {
//if all is checked and someone unchecks a checkbox make all uncheck
var thisParent=jQuery(this).parents('.uwpqsf_class').attr('id');
var AllTicked =jQuery("#"+thisParent+" .chkcmfall").prop('checked');
if(thisParent && AllTicked){
jQuery("#"+thisParent+" .chkcmfall").prop('checked',false)
//jQuery(this).trigger('click');
}
})
});
</script>
Here is the HTML structure
<div id="mycategory" class="filter_acc_class uwpqsf_class togglecheck">
<h2 class="LabelPlaceHolder">Category</h2>
<!-- Add controlall and data-boxid -->
<label class="searchLabel control controlAll checkbox" data-boxid="wrap_id_cats"><input type="checkbox" class="chkcmfall" value="" name="mycatname[]" data-boxid="wrap_id_cats"><span class="control-indicator"></span>All</label>
<div id="wrap_id_cats" class="wrap_acf togglecheck">
<label class="searchLabel control checkbox"><input type="checkbox" value="16" name="mycatname[]"><span class="control-indicator"></span>Bakery<span class="fltr_num">(12)</span></label><br>
<label class="searchLabel control checkbox"><input type="checkbox" value="18" name="mycatname[]"><span class="control-indicator"></span>Indulgences<span class="fltr_num">(12)</span></label><br>
<label class="searchLabel control checkbox"><input type="checkbox" value="17" name="mycatname[]"><span class="control-indicator"></span>Dairy<span class="fltr_num">(7)</span></label><br>
<label class="searchLabel control checkbox"><input type="checkbox" value="19" name="mycatname[]"><span class="control-indicator"></span>Meat<span class="fltr_num">(7)</span></label><br>
<label class="searchLabel control checkbox"><input type="checkbox" value="27" name="mycatname[]"><span class="control-indicator"></span>test4<span class="fltr_num">(7)</span></label><br>
<label class="searchLabel control checkbox"><input type="checkbox" value="24" name="mycatname[]"><span class="control-indicator"></span>test1<span class="fltr_num">(5)</span></label><br>
<label class="searchLabel control checkbox"><input type="checkbox" value="26" name="mycatname[]"><span class="control-indicator"></span>test3<span class="fltr_num">(5)</span></label><br>
<label class="searchLabel control checkbox"><input type="checkbox" value="25" name="mycatname[]"><span class="control-indicator"></span>test2<span class="fltr_num">(1)</span></label><br>
<label class="searchLabel control checkbox"><input type="checkbox" value="29" name="mycatname[]"><span class="control-indicator"></span>test6<span class="fltr_num">(1)</span></label><br>
<label class="searchLabel control checkbox"><input type="checkbox" value="30" name="mycatname[]"><span class="control-indicator"></span>test7<span class="fltr_num">(1)</span></label>
</div>
</div>
Not sure I completely understand what you're asking, but with this script you can check/uncheck with one checkbox which reacts to changes of other checkboxes as well.
JavaScript:
$("input[type=checkbox]:not(.chkcmfall)").on("change", function () {
if ($(".chkcmfall").is(":checked")) {
$("input[type=checkbox]:not(this)").prop("checked", false);
$(this).prop("checked", true);
}
$(".chkcmfall").prop("checked", $("input[type=checkbox]:not(.chkcmfall):checked").length == $("input[type=checkbox]:not(.chkcmfall)").length);
});
$(".chkcmfall").on("change", function () {
$("input[type=checkbox]").prop("checked", $(this).is(":checked"));
});
What does it do?
It applies an eventhandler to all checkboxes except the one with class chkcmfall. Whenever one of these checkboxes change from checked to unchecked or vice versa, it counts all checked checkboxes (except the one with class chkcmfall) and if it matches the total amount of checkboxes, it checks the chkcmfall-checkbox as well. Otherwise it unchecks it.
When the chkcmfall-checkbox is checked, all other checkboxes are also checked.
EDIT: When the chkcmfall-checkbox is checked and then another checkbox is checked, only this latter one will be checked and the rest will be unchecked.
EDIT 2: Check all box now acts as a check/uncheck all box.
FIDDLE
EDIT 3: Added a new solution not to be using the prop attribute, but by using the click event of checkboxes as per request of the OP. I've made a difference between a click from a user and a click triggered by code by passing in an extra parameter in the trigger-function. This will prevent the infinite loops the OP was talking about, since we can now prevent the execution of triggering click events based on the source of the click.
JavaScript:
jQuery(window).ready(function () {
//check ALl checkbox onClick
jQuery('body').on('click', '.chktaxoall,.chkcmfall', function (e, source) {
var all = $(this).is(":checked");
if (source != "code") {
$("input[type=checkbox]:not(this)").each(function () {
if ($(this).is(":checked") != all)
$(this).trigger("click", "code");
});
}
});
jQuery('body').on('click', '.wrap_acf input:checkbox', function (e, source) {
var allChecked = $(".chkcmfall").is(":checked");
if (source != "code" && allChecked) {
$(".wrap_acf input:checkbox:not(this)").trigger("click", "code");
$(".chkcmfall").trigger("click", "code");
} else if (source != "code") {
if ($(".wrap_acf input:checkbox:checked").length == $(".wrap_acf input:checkbox").length)
$(".chkcmfall").trigger("click", "code");
}
})
});
NEW FIDDLE
Edit 4: Updated the answer to reflect the wishes of OP to be able to have multiple sets of checkboxes.
For this approach to work you have to be able to set data--attributes to both the checkboxes and the (un)select-all-checkbox. In the following example, the script only applies the checking/unchecking of checkboxes based on a data-attribute called set.
$(document).ready(function () {
//check ALl checkbox onClick
$("body").on("click", ".chktaxoall,.chkcmfall", function (e, source) {
var all = $(this).is(":checked");
var set = $(this).data("set");
if (source != "code") {
$("input[type=checkbox][data-set='" + set + "']:not(this)").each(function () {
if ($(this).is(":checked") != all)
$(this).trigger("click", "code");
});
}
});
$("body").on("click", ".wrap_acf input:checkbox", function (e, source) {
var set = $(this).data("set");
var allChecked = $(".chkcmfall[data-set='" + set + "']").is(":checked");
if (source != "code" && allChecked) {
$(".wrap_acf input[type=checkbox][data-set='" + set + "']:not(this)").trigger("click", "code");
$(".chkcmfall[data-set='" + set + "']").trigger("click", "code");
}
else if (source != "code")
{
if ($(".wrap_acf input[type=checkbox][data-set='" + set + "']:checked").length == $(".wrap_acf input[type=checkbox][data-set='" + set + "']").length)
$(".chkcmfall[data-set='" + set + "']").trigger("click", "code");
}
})
});
FIDDLE 3
supposing you have a table with un checkbox (A) (with class: checkall) as part of a header. then all elements in this column are CHECKBOXES (B) (with class: checkitem ) then you want to change the state of all checkboxes (B) (the checked will be unchecked and vice-versa):
$(".checkall").click(function() {
var value = $(this).is(':checked');
$('.checkitem:checkbox').each(function(){this.checked = !this.checked;})
});
I'm not sure I follow, but here's a simple script to uncheck all checkboxes after a checkbox has been checked:
EDIT: realized you're looking to check/uncheck with one specific checkbox.
$('.chkcmfall').click(function(){
var chall = this;
$('input:checkbox').attr('checked',$(chall).attr('checked');
});
EDIT 2: accounting for your comment:
$('input:checkbox').click(function(){
var clicked_box = this
// see if all checkboxes are checked
if($('input:checked').length == $('input:checkbox').length){
$('input:checkbox').attr('checked','false');
$(clicked_box).attr('checked'),'true');
}
});
Say this is my HTML:
<input type="radio" name="rad" id="Radio0" checked="checked" />
<input type="radio" name="rad" id="Radio1" />
<input type="radio" name="rad" id="Radio2" />
<input type="radio" name="rad" id="Radio4" />
<input type="radio" name="rad" id="Radio3" />
As you can see the 1st radio button is checked. I need the radio button to function like toggle. For eg. If I again click on radio0, all radio buttons should be unchecked.
How can I achieve that?
Update: I don't want any extra buttons. For eg. I could add a button and set the checked property for all radio buttons to be false. However, I don't want that. I only want my form to consist of these 4 radio buttons.
Update: Since most of the people don't understand what I want, let me try to rephrase- I want the radio button to function in toggle mode. I've given the same name to all radio buttons hence it's a group. Now I want the radiobuttons to toggle itself. Eg. if I click on radio0, it should get unchecked if it's checked and checked if it's unchecked.
The problem you'll find is that as soon a radio button is clicked its state is changed before you can check it. What I suggest is to add a custom attribute to keep track of each radio's previous state like so:
$(function(){
$('input[name="rad"]').click(function(){
var $radio = $(this);
// if this was previously checked
if ($radio.data('waschecked') == true)
{
$radio.prop('checked', false);
$radio.data('waschecked', false);
}
else
$radio.data('waschecked', true);
// remove was checked from other radios
$radio.siblings('input[name="rad"]').data('waschecked', false);
});
});
You will also need to add this attribute to the initially checked radio markup
<input type="radio" name="rad" id="Radio0" checked="checked" data-waschecked="true" />
See demo here : http://jsfiddle.net/GoranMottram/VGPhD/2/
Once you give the name of 2 or more radio buttons as the same, they automatically become a group. In that group only one radio button can be checked. You have already achieved this.
This code solved my issue
$("[type='radio']").on('click', function (e) {
var previousValue = $(this).attr('previousValue');
if (previousValue == 'true') {
this.checked = false;
$(this).attr('previousValue', this.checked);
}
else {
this.checked = true;
$(this).attr('previousValue', this.checked);
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<label >Toogle radio button example</label>
<br />
<input type="radio" name="toogle_me" value="mango"> Blue </input>
<input type="radio" name="toogle_me" value="kiwi"> Green </input>
<input type="radio" name="toogle_me" value="banana"> Yellow </input>
<input type="radio" name="toogle_me" value="orange"> Orange </input>
I use an onClick() like the following for my custom radios:
$(function(){
// if selected already, deselect
if ($(this).hasClass('selected') {
$(this).prop('checked', false);
$(this).removeClass('selected');
}
// else select
else {
$(this).prop('checked', true);
$(this).addClass('selected');
}
// deselect sibling inputs
$(this).siblings('input').prop('checked', false);
$(this).siblings('input').removeClass('selected');
}
Using #Goran Mottram answer just tweaking it a bit to suit the case where radio buttons are not siblings.
$(".accordian-radio-button").click(function(){
var wasChecked = true;
if($(this).data('waschecked') == true){
$(this).prop('checked', false);
wasChecked = false;
}
$('input[name="ac"]').data('waschecked', false);
$(this).data('waschecked', wasChecked);
})
<input class="accordian-radio-button" data-waschecked="false" type="radio" name="ac" id="a1" />
I ran into this as well, after thinking about it and playing around with the various fiddles offered, I had a few dissatisfactions with the offered solutions.
My main problem was the last line of the accepted answer, requiring a reset:
// remove was checked from other radios
$radio.siblings('input[name="rad"]').data('waschecked', false);
And since I'm not using jQuery, I'd have to loop over and evaluate the siblings myself, which isn't a huge deal, but seemed inelegant to me. But, there's no way around it with that method, because you're using the dataset as a storage of information.
After playing around, I realized is that the problem is that when a radio is clicked, it triggers the clicked event, and whatever function is attached to that click event completes itself before the function for the "onchange" event is ever evaluated, let alone called. So, if the click event "unchecks" the toggle, then no change event is ever fired.
I've left my failed attempt here:
https://codepen.io/RiverRockMedical/pen/daMGVJ
But, if you could answer the question "will a change event happen after this click event?" then you could get a toggle working.
The solution I came up with can be seen at this pen:
https://codepen.io/RiverRockMedical/pen/VgvdrY
But basically is as follows:
function onClick(e) {
e.dataset.toDo = 'uncheck';
setTimeout(uncheck, 1, {
event:'click',
id:e.id,
dataset:e.dataset
});
}
So, on the click event, set a marker that the click has happened, and the use setTimeout() to create a pause that allows the onchange event to be evaluated and fire.
function onChange(e) {
e.dataset.toDo = 'leave';
}
If the onchange event fires, it undoes what was done by the onclick event.
function uncheck(radio) {
log('|');
if (radio.event !== 'click') return;
log('uncheck');
if (radio.dataset.toDo === 'uncheck') {
document.getElementById(radio.id).checked = false;
radio.checked = false;
}
}
Then, when the uncheck function starts, it has the information of whether a change event followed the click event or not. If not, then the radio is unchecked, and functions as a toggle.
And, it's basically self-resetting, so I don't have to loop over all the radios and reset their datasets to the initial values at the end of the function.
Now, I'm sure there's a cooler async/await way to do this that doesn't use setTimeout and would be even more elegant, but I'm still learning and I couldn't come up with it. Anyone else?
<input type="radio" name="gender" id="male"onclick="getChecked(1)"><label for="male">Male</label>
<input type="radio" name="gender" id="female"onclick="getChecked(2)"><label for="female">female</label>
<script>
var btnChecked = "";
function getChecked(i) {
if(btnChecked == i) {
btnChecked = "";
document.getElementsByTagName("input")[i-1].checked = false;
}
else btnChecked = i;
}
</script>
A simple approach in jQuery (even though I don't use jQuery nowdays):
function makeRadioInputsToggleable(radioInputs){
let radioGroup = {
lastValue: radioInputs.filter(':checked').prop('value'),
get value(){
return this.lastValue;
},
set value(v){
let inputToCheck = radioInputs.filter((i, el) => el.value === v);
radioInputs.filter(':checked').prop('checked', false);
if(inputToCheck.length > 0){
inputToCheck.prop('checked', true);
this.lastValue = v;
}else{
this.lastValue = undefined;
}
},
};
radioInputs.on('click', (e) => {
let input = e.target;
if(input.value === radioGroup.lastValue){
input.checked = false;
radioGroup.lastValue = undefined;
}else{
radioGroup.lastValue = input.value;
}
}).on('keydown', (e) => {
if(e.code === 'Space'){
let input = e.target;
if(input.checked){
input.checked = false;
input.blur();
radioGroup.lastValue = undefined;
}
}
});
return radioGroup;
}
let radioInputs = $('input[type="radio"][name="rad"]');
let radioGroup = makeRadioInputsToggleable(radioInputs);
$('.check-radio').on('click', (e)=>{
let value = e.target.value;
radioGroup.value = value;
});
// Note:
// 1. pass a single group of radio inputs to `makeRadioInputsToggleable`
// 2. set distinct values for each radio input in a group.
// 3. to change checked radio programmatically, use `radioGroup.value = 'XXX'` rather than radioInputs.prop('checked', false).filter('[value="XXX"]').prop('checked', true);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<h3>makeRadioInputsToggleable</h3>
<label><input type="radio" name="rad" value="1" id="Radio0" checked="checked" />1</label>
<label><input type="radio" name="rad" value="2" id="Radio1" />2</label>
<label><input type="radio" name="rad" value="3" id="Radio2" />3</label>
<label><input type="radio" name="rad" value="4" id="Radio4" />4</label>
<label><input type="radio" name="rad" value="5" id="Radio3" />5</label>
<p>1. click on an already-checked radio button, the radio will be toggled to unchecked.</p>
<p>2. focus on an already-checked radio button and press 'Space', the radio will be toggled to unchecked. <i>(This may not work in Code Snippet result area)</i></p>
<p>
3. programmatically
<button class="check-radio" value="2">check radio with value 2</button>
<button class="check-radio" value="10">check radio with value 10</button>
</p>
<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