I have a form having multiple radio buttons in different groups. e.g
category vehicle has two radio buttons
2 wheeler
4 wheeler
same as other categories have 2-2 radio buttons.
What i want to do is when i check 4 wheeler from 2 wheeler i show a warning message pop up, are u sure to switch, if yes then ok, but for no i want to check again 2 wheeler radio button. I can not do this from id as well coz i have to do this on other fields as well.
<input type="radio"/>
Your questions is not very clear but from what I understand I guess you want:
$(document).ready(function(){
$('#submit_button').click(function() {
if (!$("input[#name='radioName']:checked").val()) {
alert('Nothing is checked!');
return false;
}
else {
alert('One of the radio buttons is checked!');
}
});
});
And add the same name tag for all your radio inputs:
<input type="radio" name="radioName"/>
This might be what you're trying to achieve:
var old_input = $('input[name="wheeler"]:checked');
$('input[name="wheeler"]').change(function(e) {
console.log(e);
if (
old_input.next().text() == '2 Wheeler' &&
$(this).next().text() == '4 Wheeler'
) {
if (confirm('Are you sure you want to change?')) {
old_input = $(this);
}
else {
this.checked = 0;
old_input.get()[0].checked = 1;
}
}
else {
old_input = $(this);
}
});
http://jsfiddle.net/pQpk7/
I think you are looking for this http://jsfiddle.net/7rF3d/ When a radio button is checked for the first time nothing happens. When someone checked another he is first prompted for a confirmation. If the user cancels the old checked radio will be restored.
var lastChecked;
$("input[type=radio]").click(function() {
if(typeof(lastChecked) != "undefined" && !confirm("are you sure?")) {
$("input[type=radio]:checked").attr("checked", "false");
$(lastChecked).prop("checked", true);
} else {
lastChecked = $('input[type=radio]:checked');
}
});
Since jQuery isn't tagged in the question, here's a pure JS approach. Guys, seriously, try to quit suggesting jQuery solutions when it isn't even tagged in the question.
You can achieve this by using the click event and returning false if there is at least one radio button checked, then the answer to a window.confirm is false, which will prevent it to select the new one as expected.
var oneChecked=false;
var elem=document.getElementsByName("wheeler");
for (var i=0;i<elem.length;i++) {
elem[i].onclick=function(e) {
if (oneChecked && !window.confirm("Are you sure to switch?")) {
return false;
} else {
oneChecked=true;
}
}
}
FIDDLE
Related
I have this form with questions that uses checkboxes and radiobuttons, the checkbox questions can have a max amount of checked needed to go to the next question. For the checkboxes and radio buttons i am using the bootstrap buttons.
https://getbootstrap.com/docs/4.1/components/buttons/#checkbox-and-radio-buttons
I use jquery change function to see when something happens to the checkbox, when something changes i check how many are checked and compare it with the max amount. If the amount of checked is higher than the max then i uncheck the checkbox that was just checked. Problem with this is that when a checkbox unchecks it changes the checkbox and I get an infinite loop and end up getting the error "too much recursion".
Any clue on how I can make this work? I've tried .click instead of .change but then when I get the amount of checked it gives me the wrong number.
Script:
function checkboxHandler(aThis){
if($('.pro-block.pb-active').find('.proanalysecheck:checked').length > $(aThis).data('max')) {
if($(aThis).prop('checked') == true){
$(aThis).parent('label').button('toggle');
}
}
}
$('#frmProinvite .proanalysecheck').change( function(e) {
checkboxHandler(this);
});
.pb-block.pb-active is the current question div and .proanalysecheck is the input class.
What about using a flag which indicates that a change is caused by reaching the max selections? This should do the job.
var changeByMaxReached = false;
function checkboxHandler(aThis){
if(!changeByMaxReached && $('.pro-block.pb-active').find('.proanalysecheck:checked').length > $(aThis).data('max')) {
if($(aThis).prop('checked') == true){
changeByMaxReached = true;
$(aThis).parent('label').button('toggle');
}
}
}
$('#frmProinvite .proanalysecheck').change( function(e) {
if (!changeByMaxReached) {
checkboxHandler(this);
}
changeByMaxReached = false;
});
Now making playlist using switchery checkbox,
and already make it like a radio button,
but it cant toggle back.
How can i make Switchery back to idle state / unchecked state ??
>>> my Fiddle Demo <<<
Here is my js :
$(document).ready(function() {
//switchery
var elems = Array.prototype.slice.call(document.querySelectorAll('.js-switch'));
elems.forEach(function(html) {
var switchery = new Switchery(html,{size: 'small',});
});
//detect change
$('input.pinmusic').on('change', function() { //detect change
// auto uncheck when selecting other checkbox
// but this is not working with switchery
$('.pinmusic').not(this).prop('checked', false);
});
});
PS : its already checked, but only switchery get stuck.
already browse some topic of switchery here but still error.
I'm late but, here's my solution:
var $switches = [];
var elems = Array.prototype.slice.call();
$.each(document.querySelectorAll('.js-switch'),function(i,html) {
$switches[html.name] = new Switchery(html,{size: 'small',});
});
$('input.js-switch').on('change', function () {
if (this.checked) {
$.each(document.querySelectorAll('input.js-switch:not([name="' + this.name + '"])'),
function (i, e) {
switcherySetChecked($switchers[e.name], false)
});
}
});
function switcherySetChecked(switcher, check) {
var curr = $(switcher.element).prop('checked');
var disabled = $(switcher.element).prop('disabled');
if (disabled) {
switcher.enable();
}
if (check) {
if (curr) {
$(switcher.element).prop('checked',false);
}
$(switcher.element).trigger('click');
} else {
if (!curr) {
$(switcher.element).prop('checked', true);
}
$(switcher.element).trigger('click');
}
if (disabled) {
switcher.disable();
}
}
It's pretty difficult to be sure of your problem, but if I understand well, you want to uncheck a radio button.
Well, you can't. A radio button is not made to be unchecked. The meaning of a pool of radio buttons is "choose exactly one of the following options". Unchecking a radio button would mean that the user chooses zero option, which is not allowed.
From Wikipedia's Radio button:
A radio button or option button is a graphical control element that allows the user to choose only one of a predefined set of options.
It is possible that initially none of the radio buttons in a group are selected. This unselected state cannot be restored by interacting with the radio button widget, though it may be possible through other user interface elements.
What you need to use if you want to be able to choose zero option, is a Checkbox.
I have a email address field and 3 radio buttons. You must click one radio button and it will redirect you to another page. I am testing here If I can get the value of radio button (Category.val).
Here is my code:
<aui:script>
AUI().use(
'aui-modal','liferay-portlet-url','aui-io-request','aui-base',
function(A) {
$('a.btn-resetpass').click(function() {
var validator = $(".pwdLength"),
Category = $(".1");
if (validator.val().length != 0) {
alert(Category.val());
if (Category.val() == 1) {
}
else if (Category.val() == 2) {
}
else if (Category.val() == 3) {
}
//$('.resetForm').submit();
}
else {
alert ("Please input a valid email");
}
$('.resetForm').submit();
});
});
</aui:script>
Please help.
Thank you in advance!
The problem here is the selector used for radio buttons. You are trying to get all elements with class 1, but if what you need is the selected radio so you have to use .1:checked.
Without the html it is difficult to form a proper selector, but assuming those are the only radio buttons in the page you can try
Category = $("input:radio:checked");
Update:
As per your update the class used by you is radioB so
Category = $(".radioB:checked");//no need to use `[type=radio]` if the class is only assigned to the radio elements
This is what I used:
Category = $(".radioB[type=radio]:checked");
Thanks for the help of #Arun P Johny. Thank you very much.
I have a site using input:text, select and select multiple elements that generate a text output on button click.
Having searched SO, I found examples of validation code that will alert the user when a select field returns an empty value-
// alert if a select box selection is not made
var selectEls = document.querySelectorAll('select'),
numSelects = selectEls.length;
for(var x=0;x<numSelects;x++) {
if (selectEls[x].value === '') {
alert('One or more required fields does not have a choice selected... please check your form');
return false;
$(this).addClass("highlight");
}
At the end, I tried to add a condition after the alert is dismissed, such that the offending select box will be highlighted by adding the 'highlight' class - but this doesn't do anything. My .highlight css is {border: 1px red solid;}
Any help here?
UPDATED WITH ANSWER - Thanks #Adam Rackis
This code works perfectly. I added a line to remove any added '.highlight' class for selects that did not cause an error after fixing
// alert if a select box selection is not made
var selectEls = document.querySelectorAll('select'),
numSelects = selectEls.length;
$('select').removeClass("highlight");//added this to clear formatting when fixed after alert
var anyInvalid = false;
for(var x=0;x<numSelects;x++) {
if (selectEls[x].value === '') {
$(selectEls[x]).addClass("highlight");
anyInvalid = true;
}}
if (anyInvalid) {
alert('One or more required fields does not have a choice selected... please check your form');
return false;
}
You were close. In your loop, this does not refer to each select that you're checking.
Also, you're returning false prior to the highlight class being added. You'll probably want to keep track of whether any select's are invalid, and return false at the very end after you're done with all validation.
Finally, consider moving your alert to the very bottom, so your user won't see multiple alerts.
var anyInvalid = false;
for(var x=0;x<numSelects;x++) {
if (selectEls[x].value === '') {
$(selectEls[x]).addClass("highlight");
anyInvalid = true;
}
}
if (anyInvalid) {
alert('One or more required fields does not have a choice selected... please check your form');
return false;
}
Also, since you're already using jQuery, why not take advantage of its features a bit more:
$('select').each(function(i, sel){
if (sel.value === '') {
$(el).addClass("highlight");
anyInvalid = true;
}
});
if (anyInvalid) {
alert('One or more required fields does not have a choice selected... please check your form');
return false;
}
I have been searching in a lot of topics but I haven't found anything that really correspond to my problem :
I want to make radio buttons uncheckable (i.e. uncheck a radio button by clicking on it when it's already checked).
I found some solutions using a hidden radio button as a temporary comparison object but this doesn't fits to my existing context, so I would like to do the same without another radio button.
I tried to simply test and change the status/value of the radio button on "onclick" event but it hasn't been very successfull...
Thanks in advance,
Clem.
That's not what radio buttons are. If you try to make this work, you will just confuse your users.
If you want something that can be checked and then unchecked, use a checkbox. Radio buttons are for selecting exactly one of some set of options.
better so:
onclick="
var isChecked = $(this).attr('is_che');
if (isChecked) {
$(this).removeAttr('checked');
$(this).removeAttr('is_che');
}
else {
$(this).attr('checked', 'checked');
$(this).attr('is_che', 'true');
}"
I know this sort of action is non-standard for radio buttons, but the poster requested the functionality. The following is code that I've used in the past. I've found it not to be the most optimized (assuming a large # of radio buttons), but I also haven't taken the time to do that optimization.
// Allow for radio button unchecking
$(function(){
var allRadios = $('input[type=radio]')
var radioChecked;
var setCurrent = function(e) {
var obj = e.target;
radioChecked = $(obj).attr('checked');
}
var setCheck = function(e) {
if (e.type == 'keypress' && e.charCode != 32) {
return false;
}
var obj = e.target;
if (radioChecked) {
$(obj).attr('checked', false);
} else {
$(obj).attr('checked', true);
}
}
$.each(allRadios, function(i, val) {
var label = $('label[for=' + $(this).attr("id") + ']');
$(this).bind('mousedown keydown', function(e){
setCurrent(e);
});
label.bind('mousedown keydown', function(e){
e.target = $('#' + $(this).attr("for"));
setCurrent(e);
});
$(this).bind('click', function(e){
setCheck(e);
});
});
});