working with radio buttons passing the status along with value? - javascript

I am writing code for radio buttons where there are 3 radio buttons like YES, NO and ALL. I am using same class name for all the 3 and also binding a value for them. If user clicks on one of the three Am able to pass the corresponding value on onclick event but my problem is how to know whether user clicks on which radion button among the three buttons like if user clicks on 'All' radio button I want to perform some type of action else if user clicks on 'Yes' option then some different action, etc. how to know user clicks on which radio button? mycode is below:
<input type="radio" name="select_option" class="select_option" value="<?=$row_id;?>">All
<input type="radio" name="select_option" class="select_option" value="<?=$row_id;?>">Yes
<input type="radio" name="select_option" class="select_option" value="<?=$row_id;?>">No
I need radio button value along with user clicked on which radio button. how to achieve this? Can anyone please guide me.

I have added my class names(all, yes, no) in those html elements
<input type="radio" name="select_option" class="select_option all" value="<?=$row_id;?>">All
<input type="radio" name="select_option" class="select_option yes" value="<?=$row_id;?>">Yes
<input type="radio" name="select_option" class="select_option no" value="<?=$row_id;?>">No
Using jQuery
$(document).ready(function(){
$("input:radio").click(function(e){
if($(this).hasClass("all"))
{
console.log("which button -> all");
console.log("value="+$(this).val());
}
else if($(this).hasClass("yes"))
{
console.log("which button -> yes");
console.log("value="+$(this).val());
}
else if($(this).hasClass("no"))
{
console.log("which button -> no");
console.log("value="+$(this).val());
}
});
});
FIDDLE

Please add an extra parameter for storing the 'id' inside the input box, just like this:
<input type="radio" name="select_option" class="select_option" value="all" data-id="<?=$row_id;?>">All
<input type="radio" name="select_option" class="select_option" value="yes" data-id="<?=$row_id;?>">Yes
<input type="radio" name="select_option" class="select_option" value="no" data-id="<?=$row_id;?>">No
Now, here is the script which will run after checking the radio button:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script>
$(document).ready(function() {
$('.select_option').click(function() {
if ($(this).prop('checked')) {
var id = $(this).data('id');
var value = $(this).val();
}
alert(value);
});
});
</script>
I hope, this may be useful to you.

try this
$(".select_option").change(function(){
var radioValue = $("input[name='select_option']:checked").val();
if(radioValue){
alert("Your are clicked - " + radioValue);
}
});

$(".select_option").change(function () {
if ($(this).is(":checked")) {
var value = $(this).val();
console.log(value);
}
});
fiddle

Related

How find empty input value in jquery

I have two checkboxes the one checkbox value is 1 and the second one is 0.
One checkbox is for enabling and other for disabling. Now I want to identify when a user clicks on Disable checkbox How I will get Disable checkbox value and if a user clicks on Enable box then how I will get Enable Checkbox value
<input type="radio" name="forgot_pass" class="forgot_pass_enable" value="1" checked>
<input type="radio" name="forgot_pass" class="forgot_pass_disable" value="0">
I have tried This code but it's not working for me any help
$("body").on('change', '.forgot_pass_enable', function(event)
{
event.preventDefault();
/* Act on the event */
if($('.forgot_pass_enable').val().length > 0)
{
var status = 1;
console.log(status);
}
if($('.forgot_pass_disable').val().length > 0)
{
var status = 0;
console.log(statusasdad);
}
});
Neither of the elements you've shown are checkboxes - they are radio inputs.
To get the selected value apply the same class to both elements, then hook the change event to that class. Then you can simply read the value from it, like this:
$("body").on('change', '.forgot_pass', function(e) {
e.preventDefault();
var status = this.value;
console.log(this.value === '1' ? 'enabled' : 'disabled', status);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<input type="radio" name="forgot_pass" class="forgot_pass" value="1" checked="checked">
<input type="radio" name="forgot_pass" class="forgot_pass" value="0">
If you did want to use a checkbox for this, which would be more applicable for an enable/disable switch, then the method is the same except you look for the checked property instead:
$("body").on('change', '.forgot_pass', function(e) {
e.preventDefault();
var status = this.checked ? '1' : '0'
console.log(status);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<input type="checkbox" name="forgot_pass" class="forgot_pass" value="1" checked="checked">

Javascript - If no radio buttons are selected, check the first one

I'm a beginner in JavaScript. I have several radio buttons on my dynamic page and I want to create a script to make the following:
HTML:
<input type="radio" id="elemainfoto">
<input type="radio" id="elemainfoto">
<input type="radio" id="elemainfoto">
JavaScript:
var radio = '#elemainfoto',
if(radd.value == 0) {
radd.checked the first radio element,
} else {
keep the way it is,
}
If none of the radio elements are marked, mark the first compulsory.
I your expectation is that the first item get selected by default, then you should use HTML and not javascript for that and please note that you should not use two HTML elements with the same id in your case you should either replace by a class and/or add unique Ids for elements.
<input type="radio" class="elemainfoto" id="item1" checked>
<input type="radio" class="elemainfoto" id="item2">
<input type="radio" class="elemainfoto" id="item3>
Updated the answer based on RobG comment.
Something like this in pure JS (I changed ids to classes id should be unique):
var radio = document.querySelectorAll('.elemainfoto'),
checked = false;
for (var i = 0; i < radio.length; i++) {
if (radio[i].checked) {
checked = true;
break;
}
}
if (!checked) {
radio[0].checked = true;
}
else {
alert('something is checked')
}
A little shorter with jQuery:
var $radio = $('.elemainfoto');
if (!$radio.filter(':checked').length) {
$radio[0].checked = true;
}
else {
alert('something is checked')
}
using 'id' attribute in html with the same value more than once is invalid, you should use "name" for an input.
HTML:
<input type="radio" name="elementinfoto" value="1" />
<input type="radio" name="elementinfoto" value="2" />
<input type="radio" name="elementinfoto" value="3" />
JavaScript:
var radio = document.getElementsByName('elementinfoto'); // get all radio buttons
var isChecked = 0; // default is 0
for(var i=0; i<radio.length;i++) { // go over all the radio buttons with name 'elementinfoto'
if(radio[i].checked) isChecked = 1; // if one of them is checked - tell me
}
if(isChecked == 0) // if the default value stayed the same, check the first radio button
radio[0].checked = "checked";
example: http://jsfiddle.net/yxm4N/2/
A radio button group is formed by giving radio buttons the same name. An ID is optional and usually not necessary. If an ID is provided, each should have a different value. And the buttons should have a value so that there's a point to their existence.
To have one button selected by default, simply set the chosen button's checked attribute:
<form id="foo">
<input type="radio" name="elemainfoto" valu="0" checked>0<br>
<input type="radio" name="elemainfoto" valu="1">1<br>
<input type="radio" name="elemainfoto" valu="2">2<br>
<input type="reset">
</form>
Now if no other button is selected, or the form is reset, one button will be selected. Note that if you do not set a button as the default selected, then once a user checks a button, the only way to deselect it is to select a different radio button in the same group, or use a reset button (if provided).
If you want to set the default checked button in script, there are a couple of options. One is:
var buttons = document.getElementsByName('elemainfoto');
buttons[0].defaultChecked = true;
If you really want to check if one is selected, add a button like the following to the form:
<input type="button" value="Check buttons" onclick="checkButtons(this);">
Then the checkButtons function can be:
function checkButtons(el) {
var buttons;
var form = el && el.form;
if (form) {
buttons = form.elemainfoto;
for (var i=0, iLen=buttons.length; i<iLen; i++) {
// If a button is checked, return its value
if (buttons[i].checked) {
return buttons[i].value;
}
}
}
// Otherwise, try to check the first one and return undefined
buttons && buttons[0].checked;
}
you need to know how to use radio element. Id is unique in html page. you should assign same name for each radio element.
<input type="radio" name="elemainfoto" id="first" value="1" />
element 1
<input type="radio" name="elemainfoto" id="second" value="2" />
element 2
<input type="radio" name="elemainfotor" id="thrid" value="3" />
element 3
if you want to check the first radio button as default, set it in input tag attribute.
<input type="radio" name="elemainfoto" id="first" value="1" checked="true"/>
element 1
or you can do it with javascript also,
$("input:radio[name=elemainfoto]:first").attr('checked', true);
you can perform action for each radio button click, to know which item is checked
$(function(){
$('input[type="radio"]').click(function(){
if ($(this).is(':checked'))
{
alert($(this).val());
}
});
});
if you want to perform a separate action for each radio button, try this below code
$(function () {
$('input[type="radio"]').click(function () {
if ($(this).is(':checked')) {
if ($(this).val() == '1') alert('first radio element is checked');
if ($(this).val() == '2') alert('second radio element is checked');
if ($(this).val() == '3') alert('third radio element is checked');
}
});
});
SEE THIS FIDDLE DEMO
Instead of selecting the first one, I prefered to use null
const radio = document.querySelectorAll('.timescale');
let timescale;
if (radio.checked) {
timescale = $('input[name=timescale_radio_buttons]:checked').val()
} else timescale = null;
You can write it like this with less code
HTML
<input type="radio" name="elementinfoto" value="1" />
<input type="radio" name="elementinfoto" value="2" />
<input type="radio" name="elementinfoto" value="3" />
JavaScript
const fields = document.getElementsByName('elementinfoto');
const value = fields.filter(el => el.checked).shift()?.value || null;
if(!value) {
fields.shift().checked = true;
}
You can replace the function shift() by [0] to get the first element if you prefer

Jquery when submit button need to validate radio button and get the id of radio button

I want to validate my button when summit if not check the radio button it will show error but if we check, it will get the id of the button that we check. I try code as below:
Html:
<div class="radio">
<label>
<input type="radio" name="chk" id="chk1" class="chk"/>abcd
</label>
</div>
<div class="radio">
<label>
<input type="radio" name="chk" id="chk2" class="chk" />
efg
</label>
</div>
<input type="button" value="Visualiser le résultat..." id="btnresult" class="btn"/>
Jquery:
$('#btnresult').on('click',function(){
if ( ! $('input.chk').is(':checked') ){
alert('not check.');
}
else if($('input.chk').is(':checked')) {
var getid = $(this).parent().find(".chk").attr('checked', true).attr('id');
alert(getid);
}
});
My problem is that: I can get only the first id of radio buttonchk1 when I check on other radio button.
To get the id of the checked radio button
var getid = $('input.chk:checked').attr('id');
$(this).parent().find(".chk").attr('checked', true).attr('id') will return the id of the first element with class .chk inside the parent element which will always be the first radio element - not the checked one
If you want to be more specific in your search then use
var getid = $(this).parent().find(".chk:checked").attr('id');
$("#btnresult").click(function() {
if(!$("input.chk:checked").length) alert("Not checked");
else alert($("input.chk:checked").attr("id"));
});

using multiple sets of radio buttons, how can I unhide and hide images

Images //hide and show images with buttons
images are shown based on radio button/checkbox selected
<img id="storage_drawer" src="images/placeholder/get_hardware/storage_drawer.png" />
<img id="cash_drawer" src="images/placeholder/get_hardware/cash_drawer.png" />
Form two sets of radio buttons// changed into checkboxes by javascript function
<input type="checkbox" id="cashdrawer" name="type" value="cashDrawer" class="unique" >
<input type="checkbox" id="cashStorage" name="type" value="storageDrawer" class="unique">
//second set of radio buttons
<input type="checkbox" id="single" name="type2" value="singleLine" class="unique" >
<input type="checkbox" id="multi" name="type2" value="multiLine" class="unique" >
</form>
Start of script
$(document).ready(function(){
to make make checkboxes have the functionality of radio buttons
var $inputs = $(".unique");
$inputs.change(function(){
$inputs.not(this).prop('checked');
});
return false;
radio buttons -- first set of radio buttons
$("input[name$=type]").click(function(){
var value = $(this).val();
//Cash Drawers
if(value == 'cashDrawer') {
$("#cash_drawer").show();
$("#storage_drawer").hide();
}
else if( value == 'storageDrawer') {
$("#storage_drawer").show();
$("#cash_drawer").hide();
}
})
$("#cash_drawer").hide();
$("#storage_drawer").hide();
second set of radio buttons
$("input[name$=type2]").click(function(){
var value = $(this).val();
//Barcode Scanners
if(value = 'singleLine') {
$("#sinlgeBarcode").show();
$("#multiBarcode").hide();
}
else if(value == 'multiLine') {
$("#multiBarcode").show();
$("#sinlgeBarcode").hide();
}
})
$("#sinlgeBarcode").hide();
$("#multiBarcode").hide();
});
});
end of script
If your radio boxes have the same name attribute they will behave as radio buttons i.e only one selection can be active in the group, but if each button have their own name they can all be selected.
So if u have a collection of radios like this:
<form>
<input type="radio" name="1">
<input type="radio" name="2">
<input type="radio" name="3">
</form>
U can get them to behave like check boxes with a lil javascript:
// This will allow the radio boxes to toggle on of.
$("input[type=radio]").click(function(){
$(this).attr("checked", !$(this).attr("checked"));
});
Edit:
I did a js fiddler with a working example, maybe it will give some answers.
http://jsfiddle.net/uPp82/1/

Get previously checked Radio Button

Given a set of radio buttons, like:
<input id="B_1" type="radio" name="radioName" value="1">
<input id="B_2" type="radio" name="radioName" value="2">
<input id="B_3" type="radio" name="radioName" value="3">
<input id="B_4" type="radio" name="radioName" value="4">
​When one of them gets checked is it possible to know which was previously active (if there is one)?
I tried to attach the following function to the onclick event, but it doesn't work because it returns the the presently selected radio button instead of the one that was selected before:
my_func = function() {
var checkedValue = $('input[type=radio]:checked').val();
return alert("The previously selected was: " + checkedValue);
};
I don't know if could be of any help, anyway here's the complete attempt: http://jsfiddle.net/H6h4R/
Try this - http://jsfiddle.net/H6h4R/1/
$(":radio").on("mousedown", function() {
$("p").text( $('input[type=radio]:checked').val() );
}).on("mouseup", function() {
$('input[type=radio]').prop('checked', false);
$(this).prop('checked', true);
});
The click event is only triggered after this exact series of events:
The mouse button is depressed while the pointer is inside the element.
The mouse button is released while the pointer is inside the element.
if he uses keyboard key this can help with that
http://jsfiddle.net/DYrW3/73/
$('input[name=radios]').keydown(function(){
alert("Before change "+$('input[name=radios]:checked').val());
})

Categories

Resources