Radio Button Onclick Event Requires Two Clicks to Fire/Execute on Firefox - javascript

Hoping someone has a solution to this weirdness on Firefox 3.
I basically have 3 radio buttons and 3 text input fields (see following code):
<input type="radio" name="group1" id="preloaded" value="preloaded_img" checked="checked" onclick="SetVals();" />
<input type="text" name="text1" id="text1" />
<input type="radio" name="group1" id="custom" value="custom_img" onclick="SetVals();" />
<input type="text" name="text2" id="text2" />
<input type="radio" name="group1" id="vector" value="vector_img" onclick="SetVals();" />
<input type="text" name="text3" id="text3" />
Now, every time I click on a specific Radio Button, the text input elements for the other two buttons should get cleared and also become disabled (see following code).
function SetVals() { // using JQuery + straight JS for this...
$(document).ready(function() {
$(":radio").click(function(event) {
// use event.target to determine which radio button was clicked
if (event.target.id=="preloaded") {
document.getElementByID("text1").disabled=false;
$("#text2").val("");
$("#text3").val("");
document.getElementById("text2").disabled=true;
document.getElementById("text3").disabled=true;
} else if (event.target.id=="custom") {
document.getElementByID("text2").disabled=false;
$("#text1").val("");
$("#text3").val("");
document.getElementById("text1").disabled=true;
document.getElementById("text3").disabled=true;
} else if (event.target.id=="vector") {
document.getElementByID("text3").disabled=false;
$("#text1").val("");
$("#text2").val("");
document.getElementById("text1").disabled=true;
document.getElementById("text2").disabled=true;
}
});
});
}
Also, when the page is initially loaded, the text2 and text3 input fields are disabled via javascript as the text1 field is checked by default:
document.getElementById("text2").disabled=true;
document.getElementById("text3").disabled=true;
The problem I'm having is that it requires 2 (two) clicks to get this to work on Firefox. On Internet Explorer, it works as expected.
So, when clicking on a radio button the first time - nothing happens. When clicking on it a second time, that's when the Onclick Event is triggered.
NOTE: I'm using JQuery for this, but have also used straight Javascript to no avail.
You can simply copy and paste my code on an editor and open the page with Firefox to see issue firsthand.
Has anybody else encountered this? Is it some sort of Firefox bug? If so, is there a work-around?
Any and all help, comments, suggestions, and input are welcome.
Thanks in advance!

Since you are using jQuery to assign the event handler for the radio button click, you can remove the onClick attribute.
This should work for you:
$(function() {
$(":radio").click(function(event) {
if (this.id == "preloaded") {
$("#text1").removeAttr("disabled");
$("#text2, #text3").val("").attr("disabled", true);
} else if (this.id == "custom") {
$("#text2").removeAttr("disabled");
$("#text1, #text3").val("").attr("disabled", true);
} else if (this.id == "vector") {
$("#text3").removeAttr("disabled");
$("#text1, #text2").val("").attr("disabled", true);
}
});
$("#text2, #text3").val("").attr("disabled", true);
});
Code example on jsfiddle.
Side note: since you are using jQuery you might as well use jQuery for almost all dom interactions since mixing the two will eventually lead to some pain. Let jQuery hide the inconsistencies in browsers.

You started using jQuery, and then returned to vanilla JavaScript... but you mis-typed the getElementById() function.
I would stick with jQuery if you have it, it will avoid IE bugs with this particular method too.
Cleaner HTML
<input type="radio" name="group1" id="preloaded" value="preloaded_img" checked="checked"/>
<input type="text" name="text1" id="text1"/>
<input type="radio" name="group1" id="custom" value="custom_img"/>
<input type="text" name="text2" id="text2"/>
<input type="radio" name="group1" id="vector" value="vector_img"/>
<input type="text" name="text3" id="text3"/>
and the jQuery...
$(document).ready(function(){
//bind the click event to the radio buttons
$(':radio').click(function(){
var radioID = $(this).attr('id');
if(radioID == 'preloaded'){
$('#text1').removeAttr('disabled');
$('#text2, #text3').val('').attr('disabled','disabled');
} else if(radioID == 'custom'){
$('#text2').removeAttr('disabled');
$('#text1, #text3').val('').attr('disabled','disabled');
} else if(radioID == 'vector'){
$('#text3').removeAttr('disabled');
$('#text1, #text2').val('').attr('disabled','disabled');
}
});
});

You could try the .change() event handler. I think that could work better.
EDIT: There are issues with the .change() event and IE.

Related

Weird a+label+input interaction

$(document).ready(function () {
$('a').click(function(e) {
console.log('a clicked');
if ($('.is_force:checked').length) {
$(this).closest('div').find('input').click();
}
e.preventDefault();
});
$('label[for]').click(function(e) {
console.log('label clicked');
});
$('input[id]').click(function(e) {
var $input = $(this);
//if ($input.is('[type=radio]')) $input.prop('checked', 'checked');
console.log('input clicked', $input.is(':checked'));
setTimeout(
function() {
console.log($input.is(':checked'));
},
0
);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<label><input class="is_force" type="checkbox"> Force checkbox/radio click when clicking on link</label>
<br>
<br>
<div>
<input id="c" type="checkbox" name="checkbox" value="1">
<label for="c">
Text
Link
</label>
</div>
<br>
<div>
<input id="r1" type="radio" name="radio" value="1">
<label for="r1">
Text
Link
</label>
</div>
<div>
<input id="r2" type="radio" name="radio" value="2">
<label for="r2">
Text
Link
</label>
</div>
Open you console to see the output.
When you click on checkbox/radio, everything works as intended.
It works as intended when you click on labels also.
But, when you click on a link inside a label: link clicks, label clicks, but input associated with the label does not get clicked.
You can "fix" this by programmatically clicking associated input from inside link click handler. To see this in action, check the top checkbox.
The fix works OK for checkboxes. But does not for radios: inside input click handler, the first console.log() shows that clicked radio is not checked. But the second console.log() from inside setTimeout() shows that it actually is checked.
This again can be "fixed" by checking the radio programmatically - see the commented line inside input click handler. But that gets way too hacky.
I have a few questions about this:
Why corresponding input doesn't get clicked when a link inside a label is clicked?
Can this be fixed "the right way" without hacky programmatic clicks?
Why radio input "checks" with a delay, while a checkbox works OK?
How to fix this without even more hacky "checked" property setting?

jQuery Mobile click event.preventDefault does not seem to prevent change

I am trying to prevent a radio button from changing when a use clicks, it works when using standard jQuery but when you include jQuery Mobile it does not seem to work, is there something else I have to do in jQuery Mobile?
<fieldset data-role="controlgroup" data-type="horizontal">
<input type="radio" name="trade-direction" id="buy" value="B" checked="checked" />
<label for="buy">Buy</label>
<input type="radio" name="trade-direction" id="hold" value="H" />
<label for="hold">Hold</label>
<input type="radio" name="trade-direction" id="sell" value="S" />
<label for="sell">Sell</label>
</fieldset>
$('[name="trade-direction"]:radio').click(function(event) {
if(!confirm("Do You Want To Change?")) {
event.preventDefault();
}
});
below is a link to the code in jsFiddle.
http://jsfiddle.net/mikeu/xJaaa/
The problem is that with jQuery.Mobile, the element that is effected by the UI change is not the input element. In fact, the radio element isn't actually clicked at all. The Element that is clicked is <div class="ui-radio">. If you want to bind to the radio input itself, you need to use the change event, but in this case it won't work for you, because the function gets called after the change has already taken place.
What you need is something like this:
// Probably a good idea to give your fieldset an ID or class
$('fieldset').delegate('.ui-radio','click',function(event){
if(!confirm("Do You Want To Change?")) {
event.stopImmediatePropagation();
event.preventDefault();
}
})
The event.stopImmediatePropagation() prevents the the .ui-radio from triggering the click event to the input, and the event.preventDefault prevents the default action. The stopImmediatePropagation may not be necessary, but it gives an added guarantee that may be helpful across different browsers.

validate field in javascript and jquery

I have four radio buttons. If I select the last radio button then one textbox is appearing. I handled this scenario by jquery. Now I want to validate in such a way that if user gets this textbox means if user checked the last radio button, then he should provide some text.But in my case, if I check any one of the radio button, its telling to provide some text. The code is like:
<input type="radio" name="bus_plan" id="smallBtn" value="1" />1
<input type="radio" name="bus_plan" id="smallBtn" value="2" />2
<input type="radio" name="bus_plan" id="smallBtn" value="3" />3
<input type="radio" name="bus_plan" id="smallBtn" value="Promotional" />
<span class="plantxt"><a style="cursor:pointer;" onclick="popup('popUpDiv')">Promotional Plan</a> (Please enter a promotional code)</span>
<div class="reg-line" id="pr_code_id" style="display:none">
<div class="reg-linea" align="left">Promotional Code: <sup>*</sup></div>
<input type="text" name="bus_prcode" id="bus_prcode" class="reg-line-input" value="Promotional Code" onblur="if(this.value=='') this.value='Promotional Code'" onClick="if(this.value==this.defaultValue) this.value='';" />
<br />
<div>
<div id="promotionalbox" style="display:none;font-size:13px;clear:both"></div>
</div>
</div>
<script type="text/javascript" src="js/jquery-1.7.2.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("input:radio[name=bus_plan]").click(function(){
var values = $(this).val();
if(values == 'Promotional'){
$('#pr_code_id').show();
}else{
$('#pr_code_id').hide();
}
});
});
</script>
and in js if I alert the value of document.getElementById('bus_prcode').value then always it is showing Promotional code, which is only for last radio button value.
Your code is a bit of a mess which is the root of this problem. Remember, one element per ID.
You may also find it helpful to look at jQuery .is(), for example:
$('input[value="Promotional"]').is(':checked')
n.b. I do not suggest the above, you should use identifiers in the appropriate way first.
Also worth noting that your code works fine for me using Chrome. See an example (which I have expanded for you) here: http://jsbin.com/ofujal/3/
You should not have an element with the same ID (your radio buttons). Also, you're getting the textbox by running document.getElementById('bus_prcode') and not the radio button. You should give a unique ID to your last radio button, e.g. btnPromotional, then bind click to it:
$("#btnPromotional").click(...)

Observing change in radio button selection using Prototype JS

I'm relatively new to Prototype JS (v1.7), and I'm stuck on something. I'm trying to detect when a change in the radio button selection occurs. Here's the code:
Radio buttons:
<input class="amounts" type="radio" name="amount" id="amount-1" value="1" />
<input class="amounts" type="radio" name="amount" id="amount-2" value="2" />
<input class="amounts" type="radio" name="amount" id="amount-3" value="3" />
Javascript:
Here's a stab I took at it, which doesn't work:
Event.observe($$('amounts'), 'change', function(event) {
alert('change detected');
});
When the form loads, no radio buttons are checked. I'd like the Javascript to detect these events:
A radio button is selected when none was previously selected
The radio button selection changes
Any help would be greatly appreciated.
It doesn't work because $$ returns an array of elements and Event needs a single element. Also $$('amounts') doesn't match any elements, there are no <amounts> tags.
A better way is to use a single ancestor element which is easy to identify.
<form id="amounts-form">
<input class="amounts" type="radio" name="amount" id="amount-1" value="1" />
<input class="amounts" type="radio" name="amount" id="amount-2" value="2" />
<input class="amounts" type="radio" name="amount" id="amount-3" value="3" />
</form>
Now there is a unique ID to work with we can use Event.on
$('amounts-form').on('change', '.amounts', function(event) {
alert('change detected');
});
Notice the events are being filtered by '.amounts', the period says to use the class name.
If you're using FireBug for FireFox or Chrome's developer tools then you can test parts of your script directly in the console. It really helps to find if a selector is matching the elements you think it is by typing $$('.amounts')
Alternegro's answer attempts to use an iterator to attach the event handler directly to the "amount" radio elements but doesn't work for a few reasons:
The "$" function doesn't take css selectors as parameters, only ids. Use "$$" instead.
The css "id" attribute selector should include square braces "[]". It's also spelled wrong. "amounts-" should be "amount-" to match the ids in the example. Or just use a class selector instead: ".amounts".
There is no "change" method that can be called on enumerables. Use invoke or some other enumerable method instead.
This one should work:
$$("[id^=amount-]").invoke(
'on',
'change',
function(){alert("hello " + this.id)}
)
(YMMV using "this" in the event handler. I only checked the code in Firefox)
Its more efficient to just give those checkboxes the same class but u can also try
$("id^=amounts-").change(function(){alert("blah blah")})

javascript jquery radio button click

I have 2 radio buttons and jquery running.
<input type="radio" name="lom" value="1" checked> first
<input type="radio" name="lom" value="2"> second
Now, with a button I can set onClick to run a function. What is the way to make radio buttons run a function when I click on one of them?
You can use .change for what you want
$("input[#name='lom']").change(function(){
// Do something interesting here
});
as of jQuery 1.3
you no longer need the '#'. Correct way to select is:
$("input[name='lom']")
If you have your radios in a container with id = radioButtonContainerId you can still use onClick and then check which one is selected and accordingly run some functions:
$('#radioButtonContainerId input:radio').click(function() {
if ($(this).val() === '1') {
myFunction();
} else if ($(this).val() === '2') {
myOtherFunction();
}
});
<input type="radio" name="radio" value="creditcard" />
<input type="radio" name="radio" value="cash"/>
<input type="radio" name="radio" value="cheque"/>
<input type="radio" name="radio" value="instore"/>
$("input[name='radio']:checked").val()
this should be good
$(document).ready(function() {
$('input:radio').change(function() {
alert('ole');
});
});
There are several ways to do this. Having a container around the radio buttons is highly recommended regardless, but you can also put a class directly on the buttons. With this HTML:
<ul id="shapeList" class="radioList">
<li><label>Shape:</label></li>
<li><input id="shapeList_0" class="shapeButton" type="radio" value="Circular" name="shapeList" /><label for="shapeList_0">Circular</label></li>
<li><input id="shapeList_1" class="shapeButton" type="radio" value="Rectangular" name="shapeList" /><label for="shapeList_1">Rectangular</label></li>
</ul>
you can select by class:
$(".shapeButton").click(SetShape);
or select by container ID:
$("#shapeList").click(SetShape);
In either case, the event will trigger on clicking either the radio button or the label for it, though oddly in the latter case (Selecting by "#shapeList"), clicking on the label will trigger the click function twice for some reason, at least in FireFox; selecting by class won't do that.
SetShape is a function, and looks like this:
function SetShape() {
var Shape = $('.shapeButton:checked').val();
//dostuff
}
This way, you can have labels on your buttons, and can have multiple radio button lists on the same page that do different things. You can even have each individual button in the same list do different things by setting up different behavior in SetShape() based on the button's value.
it is always good to restrict the DOM search. so better to use a parent also, so that the entire DOM won't be traversed.
IT IS VERY FAST
<div id="radioBtnDiv">
<input name="myButton" type="radio" class="radioClass" value="manual" checked="checked"/>
<input name="myButton" type="radio" class="radioClass" value="auto" checked="checked"/>
</div>
$("input[name='myButton']",$('#radioBtnDiv')).change(
function(e)
{
// your stuffs go here
});

Categories

Resources