Well, I'm stuck and have been banging my head for a little while now to try to figure what I'm doing wrong.
Scenario:
I have a question with a Yes/No answer (ie 2 radio buttons). When a user selects the either Yes or No, I call a function to .toggle() a hidden div to show a link. That works great. And if they go back and check that Yes/No again it disappears again due to the .toggle()
My issue is that if a user clicks the No (and the link is shown) but then clicks the Yes I want the link that is showing due to the No result to disappear and vice-versa.
So basically only show 1 link at a time.
I figured that maybe an If statement would work but I can't seem to get it right.
My code:
<div id="Question1">
<div>Do you kazoo?</div>
<input type="radio" ID="Q1RB1" runat="server" value="Yes" text="Yes" name="RadioGroup1"/>Yes<br />
<input type="radio" ID="Q1RB2" runat="server" value="No" text="No" name="RadioGroup1"/> No
<span id="Q1RB1Results" style="display:none"> <a href=#>Click here</a></span>
<span id="Q1RB2Results" style="display:none"> <a href=#>Click here</a></span>
</div>
My jQuery code that works for each individual radio button:
$("input[id$=Q1RB1]:radio").change(function () {
$("[id$=Q1RB1Results]").toggle();
});
$("input[id$=Q1RB2]:radio").change(function () {
$("[id$=Q1RB2Results]").toggle();
});
This is the If statement I'm trying to get to work. Amy I going about this the wrong way?
if ($("input[id$=Q1RB2]").is(":checked")) {
$("input[id$=Q1RB2]:radio").change(function () {
$("[id$=Q1RB2Results]").toggle();
});
});
Thanks for any thoughts/advice. I've tried a multitude of answers here in Stackoverflow and the 'net but can't seem to figure out what I'm doing wrong. :(
~V
Update: I put a sample form and the dialogue up on JSFiddle. http://jsfiddle.net/Valien/7uN6z/4/ I tried some of the solutions mentioned here and couldn't get them working so not sure what I'm doing wrong.
When you register an event listener in JQuery (.change, .click, .blur, etc.), the Javascript engine matches the selector and applies them at that point. With that in mind, you can rearrange your code (which is close to being right) to this, which should do the trick:
/* The function you're about to define applies to all radio button
inputs whose ID ends with Q1RB2 */
$("input[id$=Q1RB2]:radio").change(function()
{
/* Inside the change function, $(this) refers to the instance that
was changed. So, this checks to see if the instance that was just
changed is currently checked, after being changed. */
if ($(this).is(":checked"))
{
// If that was the case, then toggle the item
$("[id$=Q1RB2Results]").toggle();
}
});
Try this:
$('input:radio[name=RadioGroup1]').change(function(){
var show = "#" + $(this).attr('id') + 'Results';
$('#Question1 span').hide();
$(show).show();
});
I believe this is what you need:
// declare common variables so it's easier to target
var question = $("#Question1"),
group = question.find("input[name='RadioGroup1']"),
span = question.find("span");
// change listener for each radio button group
group.click(function(){
var id = $(this).attr("id"); // get the radio button id for reference
span.each(function(){ // loop through each span and check which one to hide/show
var item = $(this);
if (item.attr("id")===id+"Results") { item.show(); } else { item.hide(); }
});
});
Related
I am facing problem because I have a checkbox inside a div and I want to call a function in both the cases: if we change the checkbox value or click the div.
Now the problem is that, When I click the checkbox, The event is fired twice and I am not getting expected result.
<div ng-click="checkEntry(config.id)"><input type="checkbox" ng-model="modelCheckbox" ng-change="checkEntry(config.id)" ng-checked="someArray.indexOf(config.id) !== -1"></div>
$scope.checkEntry = function(id){
var idx = $scope.someArray.indexOf(id);
if(idx === -1){
$scope.someArray.push(id);
}else{
$scope.someArray.splice(idx, 1);
}
}
Now If i click div, it works fine and the checkbox gets selected. But if i click the checkBox, the function is called twice, and it doesn't work as expected.
Please help me with a solution
You don't need two event handler for two identical events.When you click on the input, the div will be clicked as well. so you just need to remove ng-change from your code.
<div ng-click="checkEntry(config.id)">test
<input type="checkbox" ng-model="modelCheckbox" ng-checked="checked">
and in your controller:
$scope.checked = true;
$scope.checkEntry = function(id){
$scope.checked = !$scope.checked;
}
Look at this plunker
Checkbox is situated inside of that div, so when you click checkbox you are actually clicking also on div.
Actually, in your case you can remove ng-change attribute from checkbox and it will still work, because function will be called via click on div anyway. But that is not correct way to work with checkboxes!
First question here is if you really need that div?
I would rather use label instead:
<label for="my-checkbox"><input id="my-checkbox" type="checkbox" ng-model="modelCheckbox" ng-change="checkEntry(config.id)" ng-checked="someArray.indexOf(config.id) !== -1"></label>
In such case it will work fine, you just need to write proper CSS to style that label correctly. This is the best and the most correct solution.
I need to hide a button until a check box is clicked, however I am stepping into someone elses code who used tag libraries that did not define ID in the button tag. Here is what I have:
The button code:
<html:button name="Next" value="BTN.NEXT" styleClass="button" localeCd="<%= localeCd %>" onClick='Submit("Next")'/>
The checkbox code:
<input type="checkbox" name="fedCheck" onclick="checkFed(this, 'myNext')" value="y" />
The Javascript Code
function checkFed(ele, id) {
x = document.getElementById(id);
if (ele.checked == true) x.disabled = false;
else x.disabled = true;
}
I can get this to work in a seperate page but the page that it is on does not allow for the button to have an ID so it crashes every time. Any suggestions?
There would be better ways of doing this, listening for the click event, etc... but, to simply modify your code see this jsFiddle (note: this assumes this is the only element named "Next"):
function checkFed(ele, name) {
x = document.getElementsByName(name)[0];
x.disabled = !x.disabled
}
And change the onclick="checkFed(this, 'myNext')" to:
onclick="checkFed(this, 'Next')"
And add disabled="true" to the button so that it's initial state is disabled
...also note that this doesn't actually hide it like the title asks, it disables it, like the content of the question seems to ask.
Instead of finding the button using document.getElementById, use document.querySelector.
For example, if you have a single button on the page with "Next" as the value of its name attribute:
document.querySelector('button[name="Next"]')
How can i disable the one radio input from the radio group ?
<input type="radio" name="radiogrp" value="op1" checked="checked">Option1
<input type="radio" name="radiogrp" value="op2"> Option2
<input type="radio" name="radiogrp" value="op3" > Option3
<input type="radio" name="radiogrp" value="op4"> Option4
My question is i want to disable option1 after clicking on any other button
For example:
when i select option2, than option1 should be disabled
Check this Fiddle I have just added
Let me know if this is not what you intended
As requested - posted fiddle answer
$('.rd').click(function(){
$('.rd[value="op1"]').attr('disabled', 'disabled');
});
Try
$('input[value="op2"]').click(function(e)
{
$('input[value="op1"]').attr('disabled', 'disabled');
});
http://jsfiddle.net/3CdZU/
$(":radio").change(function(){
$(":radio[name='radiogrp']").slice(0,1).attr("disabled","disabled");
});
DEMO
var radios = $('input[type="radio"][name="radiogrp"]');
radios.change(function() {
if (this.value != "op1") {
radios.filter('[value="op1"]').prop('disabled', true);
}
});
I cached the radio buttons, so I don't need to Query the DOM twice.
DEMO
Since, after the change, there is no way back, this is more fun way:
var radios = $('input[type="radio"][name="radiogrp"]');
var first = $('input[type="radio"][name="radiogrp"][value="op1"]');
radios.not(first).change(function() {
alert('changed'); // getting called only once.
first.prop('disabled', true);
radios.unbind('change');
});
LIVE DEMO
I am using jquery mobile with fancy dynamic styling, and I found that after performing the disable, I needed to explicitly issue an refresh using the checkboxradio("refresh") method call so that the styling would reflect the change. You can chain the method call, though, so it might look like this:
$('.rd').click(function(){
$('.rd[value="op1"]').attr('disabled', 'disabled').checkboxradio("refresh");
});
http://view.jquerymobile.com/1.3.2/dist/demos/faq/updating-the-value-of-enhanced-form-elements-does-not-work.html
While I appreciate gdoron's deeper, more technical, more efficient, more comprehensive approach, I believe that sometimes (just sometimes) the easier reading and shorter coding of Jibi Abraham's approach is warranted, especially in an otherwise lightweight situation.
I realize this isn't a distinct answer, but I don't have enough reputation to do a comment yet.
Its very easy, use jQuery's attribute selector. Here is an example of disabling the radio button with value op3
$('input[value="op3"]').attr('disabled', 'disabled');
Demo
Here is your solution
var radios = $('input[name=radiogrp]'); //Cache all the radio button
radios.click(function() {
//Attach a function to the click event of all radio button
if(this.value!='op1') { //Check if currently click button has value of op1
radios.filter('[value="op1"]').prop('disabled', true); //if not disable the first
}
});
Demo
$(function () {
$("#MyInputBox").keyup(function () {
var nextChk = $(this).next(":radio:checked").attr('id'));
alert(nextChk);
});
});
What is the correct way to say "Get the ID of the next checkbox which is checked" Am I even close?
Assuming your radio inputs are all siblings, you'd need to use .nextAll(), and then narrow down to the first match.
$(this).nextAll(":radio:checked:first").attr('id');
or
$(this).nextAll(":radio:checked").first().attr('id');
Or you could technically use .nextUntil() with .next().
$(this).nextUntil(":radio:checked").next().attr('id');
Also, I see that you're asking about checkboxes, but your code uses :radio, so I guess I don't know which one you actually want.
this is a small, but very annoying, glitch in my form.
I have a checkbox, that if clicked displays others checkboxes and input fields for the user to add more information. If this trigger checkbox is unclicked, the extra options dissapear.
However (the plot thickens), if another checkbox is checked in the form, the trigger checkbox can be checked and the extra options appear, but if unchecked the extra option won't dissapear!
(Sorry that was long winded, but i wanted to be clear!)
Here is my simple Jquery code:
$(function() {
var boxes = $('.obstruct-opt');
boxes.hide();
var ob = $('li.obstructionOptions').children().eq(0);
ob.change(function() {
if ($('$(this):checked').val()) {
boxes.show();
}
else {
boxes.hide();
}
});
});
I have tried different ways of checking if the trigger is checked or not, but any suggestions are welcome.
Edit
HTML as requested: (although simplified as my ASP.Net repeater control generated it)
<ul>
<li class="obstructionOptions">
<span>
<input id="Obstruction" type="checkbox" name="Obstruction" />
<label for="Obstruction">Obstruction</label>
</span>
<span class="obstruct-opt">
<input id="WeatherProof" type="checkbox" name="WeatherProof"/>
<label for="WeatherProof">WeatherProof</label>
</span>
<span class="obstruct-opt">
<input id="WeatherProofFlap" type="checkbox" name="WeatherProofFlap"/>
</span>
</li>
<li class="obstruct-opt">
<span>Obstruction Notes</span>
<textarea name="ObstructionNotes" rows="7" cols="50" id="ObstructionNotes"/>
</li>
</ul>
Hope it helps!
Update:
substituting the if condition to
if ($(this).is(":checked")) {
doesn't trigger anything, no appearing or disappearing acts in sight.
Thanks for the suggestion tho, maybe with my html you can discern why?
Update
Ok after posting my HTML i realised ASP.Net has been stitching me up!
As you can see i select the 'ob' object as the first child, but the first child is a generated span! ASP has been wrapping my checkboxes in spans all this time and i never suspected! shrewd!
I have used this code in the end:
$('ul li.obstructionOptions span').children().eq(0).click(function() {
if ($(this).is(":checked")) {
boxes.show();
}
else {
boxes.hide();
}
});
Thank you to adamantium as this solved the prod perfectly!
Problem Solved!
Do not to trust ASP.Net with my markup!!!
What about replacing
if ($('$(this):checked').val())
with
if ($(this).is(':checked'))
is
Checks the current selection against
an expression and returns true, if at
least one element of the selection
fits the given expression.
Edit:
Replace
var ob = $('li.obstructionOptions').children().eq(0);
with
var ob = $('ul li.obstructionOptions span').children().eq(0);
and
<textarea name="ObstructionNotes" rows="7" cols="50" id="ObstructionNotes"/>
with
<textarea name="ObstructionNotes" rows="7" cols="50" id="ObstructionNotes"></textarea>
and your code works fine.
Working Demo
It might have something to do with this line:
if ($('$(this):checked').val()) {
AFAIK, that won't do anything useful. You probably want this:
if ($(this).is(":checked")) {
ob.change(
A checkbox's onchange doesn't fire in IE until it's unfocused. For this reason it's usual to use onclick instead.
$('$(this):checked').val()
Doesn't work for two reasons. Firstly, you've included $(this) as part of the string. A dollar and brackets don't mean anything to selectors so jQuery won't match anything. You've already got the this object you want; you don't need to select anything more. Secondly, val() on a checkbox gets the value of that checkbox, not whether it is checked or not. This is the value attribute, or on if you haven't specified one.
Whilst you could test for checkedness using if ($(this).is(':checked')), it's more readable and much quicker to just use the standard DOM checked property. You don't have to shoehorn everything you do into jQuery.
ob.click(function() {
if (this.checked)
boxes.show();
else
boxes.hide();
});