On Radio Button execute onChange function - javascript

ive got the (working) following code
$('#selBookable').change(function () {...
and
<div class="radio radio-search">
<label><input id="radio-new-pop" type="radio" name="radio_newest_popular" value="new" >Neueste</label>
which executes when #selBookable gets another value.
Now i want to execute this function when a Radio button somewhere else is clicked.
i tried :
$('#selBookable, #radio-new-pop').change(function () {...
but that does not work.
now i thought about giving this ".change(function NAMEHERE"
a name and execute that function but doesnt work either.
any help is appreciated.
edit: i tried using the onchange event but then again i have no function name to call.

You could define the function independently of its use, giving it a name. Then you could attach it to as many targets you wish, making a call as the one that works (using the name instead of the definition), each with a different target.
(The reason your second attempt didn't work is that the second argument to $ is not another target to attach the function to, but a constraint on where to find the first target.)

You have two buttons radio with the same name :
<div class="radio radio-search">
<label>
<input id="radio-new-pop" type="radio" name="radio_newest_popular" value="new" />
Neueste
</label>
<label>
<input id="radio-new-pop2" type="radio" name="radio_newest_popular" value="new" />
Other
</label>
</div>
Add a javascript function to handle this change :
var onRadioButtonChange = void 0;
{
onRadioButtonChange = function (e) {
theFunctionYouWantToExecute(); // pass this or e.target if needed
return false;
}
}
Attach it to your elements :
Array.prototype.forEach.call(
document.querySelectorAll('input[type="radio"]'),
function (element) {
element.addEventListener('change', onRadioButtonChange, false);
}
);

Perhaps try putting the jquery listener inside of a $(document).ready().
OR
You could add a click handler on the radio, like this:
<div class="radio radio-search">
<label>
<input id="radio-new-pop" type="radio" name="radio_newest_popular" value="new" onclick="handleClick(this)">
Neueste</label>
and in the JS:
handleClick(myRadio) {
// click function logic
}
Adapted from this answer.

Related

Conditionally required form field (Checkbox)

I already checked multiple sites and posts regarding this topic, but couldn't find an answer yet. I simply want to fire the following JS code if someone clicked a specific Checkbox in my form:
function updateRequirements() {
var escortWrapper = document.querySelector(".elementor-field-type-html .elementor-field-group .elementor-column .elementor-field-group-field_ceffa28 .elementor-col-100");
if (escortWrapper.style.display != 'none') {
document.getElementById('escort').required = true;
} else {
document.getElementById('escort').required = false;
}
}
You can check and test that for yourself on the following site:
Advelio Website
If you click on the second checkbox field, there is a field appearing where you can type in your name. And this field is currently optional, but I want to make this required if someone clicked the second checkbox.
You can do it like this:
function updateRequirements() {
const btn = document.getElementById('escort');
btn.required = !btn.required;
}
document.querySelector("#requireCheck").addEventListener('click', updateRequirements);
<form>
<input type="checkbox" id="requireCheck">
<label for="requireCheck">Should the the other input be required?</label>
<br>
<input type="text" id="escort">
<input type="submit" value="submit">
</form>
I simplified the function updateRequirements for the scope of this answer, but it can be changed to anything or any condition.
You have to have event listener for click event and if you dont have create one and wrote the function with logic what to do if is click

Checking a radio button in Protractor + AngularJS

I have a radio button on my html page and I'd like to test the value of the current selected option
<div>
<input type="radio" name="radio1" value="enabled" checked/>
<label for="radio1">Yes</label>
</div>
<div>
<input type="radio" name="radio1" value="disabled" />
<label for="radio1">No</label>
</div>
<br />
I'm using this code on the page object I use to test
var radio = $("input[type='radio'][name='radio1']:checked").val();
Unfortunately I get
val() is undefined
How can I return "enabled" or "disabled" based on the current status of the radio button?
val() is a jQuery function which you do not inherently have access to unless you setup Protractor that way. Use getAttribute('value') instead, which returns a promise - see the getAttribute() reference
So if you are using it in an assertion, you can let expect resolve the promise itself:
var radio = $("input[type='radio']:checked")
expect(radio.getAttribute('value')).toEqual('enabled');
Or if you want to access the value and use it elsewhere, resolve the promise yourself:
radio.getAttribute('value').then(function (val) {
if(val === 'enabled') {
// code
}
});
Instead of 'enabled' the value = 1
// using TS
static myElement = element
.all(by.css('input[type="radio"]:checked'))
.get(0);
expect(this.myElement.getAttribute('value')).toEqual(
'1'
);

Append radio checked to the form using jquery

im working on a small app but i cant resolve this
im trying to use jQuery to append checked radio to the form , i did try alot of solution but i did fail
i wrote the code here , hope someone can help me to resolve this issue
<div class="radio">
<label>
<input type="radio" name="optionsRadios" id="optionsRadios" value="interior">
Interior
</label>
</div>
<div class="radio">
<label>
<input type="radio" name="optionsRadios" id="optionsRadios" value="exterior">
Exterior
</label>
</div>
<div class="radio">
<label>
<input type="radio" name="optionsRadios" id="optionsRadios" value="interio+exterior">
Interior si exterior
</label>
</div>
Here data was fetchted using json and i have the right result
<script>
$.each(data, function (k, v) {
typdespal = v.typdespal;
// the problem is that always i cant get the radio checked in the right position from the database
// $('#optionsRadios').val(typdespal);
$("input:radio[name='optionsRadios']").val(typdespal).prop( "checked", true );;
</script>
You can use filter() to find the correct radio button with value then set its property to checked.
$("input:radio[name='optionsRadios']").filter(function(){
return $(this).val() === typdespal
}).prop( "checked", true);
First, you need to wrap this all in a Document.Ready call. Then you need to only apply the checked function to the checkbox which contains the appropriate value. At the minute you are setting the value of all optionsRadios. You can do this with the prop function overload:
$(function() { // DOM ready
$("input:radio[name='optionsRadios']").prop("checked", function() {
// Only set the checked value when this checkbox value === the corresponding data value
var val = $(this).val();
return val === data[val].typdespal;
});
});
Note: I think I'm reading your data object right, hard to tell without seeing it :)
Firstly, several radio buttons may have same name, but not ID. So make them unique. Secondly, try to change your selector to:
$("input:radio[value='"+typdespal+"']").prop( "checked", true );

Radio button value change onclick

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

How can I toggle radiobutton

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>

Categories