Radio Button "Select" Toggle issue - javascript

I am trying to make a very very simple script that checks to see if a certain radio button option is clicked, and if so, shows another set of fields (this works fine), but if you unselect that radio button option, it hides the extra set of fields (seemingly simple, but does not work for me!)
Also I am newish to JS/JQuery so debugging this has been a struggle! Thanks for any help :)
My HTML radio button that triggers the fields display - imagine there are 6 other radio button options with this (each classed with [class="otherFund"]).
<input type="radio" name="ItemName1" id="Relief1" value="Daughters of Penelope Charitable Relief Fund" onclick="set_item('DOP-Relief-Fund', 8)" onchange="relief_fund_handler()" />
Here is the text and field and I want to toggle with the above button's selection
<p id="Earmark1" style="display: none;">
<strong>Please designate below what relief fund you would like your <em>DOP Charitable Relief</em> donation to go towards (see bulleted examples above).</strong><br />
<strong>Earmarked for <span class="required">*</span>:</strong><input type="text" name="Earmark1" id="Earmark1" size="50" />
</p>
And here are my JS attempts...
Attempt 1:
function relief_fund_handler() {
var relief_elem = document.getElementById("Relief1"),
earmark_elem = document.getElementById("Earmark1"),
donate_elem = document.getElementById("ItemName1");
if (relief_elem.checked) {
earmark_elem.setAttribute("style", "display: inline;");
} else if (".otherFund".checked) {
earmark_elem.setAttribute("style", "display: none;");
}
}
attempt 2:
function relief_fund_handler() {
var relief_elem = document.getElementById("Relief1"),
earmark_elem = document.getElementById("Earmark1"),
donate_elem = document.getElementById("ItemName1");
if (relief_elem.checked) {
earmark_elem.setAttribute("style", "display: inline;");
} else {
earmark_elem.setAttribute("style", "display: none;");
}
}
attempt 3:
$("#Relief1:checked")(
function() {
$('#Earmark1').toggle();
}
);
On attempt #3, I have also replaced the :checked with .click, .select, .change and none have worked... Thanks for any help! :)

Try this:
$("input.otherFund").change(function() {
$('#Earmark1').toggle($(this).attr('id') == 'Relief1');
});​

Try removing all of the events off of the radio button like this:
<input type="radio" name="ItemName1" id="Relief1" value="Daughters of Penelope Charitable Relief Fund" />
And using the following jquery script:
​$(function(){
$("#Relief1").change(function(){
$(this).is(":checked") ? $("#Earmark1").show() : $("#Earmark1").hide();
});
});​

You could iterate through each radio button and assign an event handler to each radio button, so when selected it shows the other fields and when deselected it hides the other fields. The code below may help you arrive at the correct answer.
// Iterate the radio buttons and assign an event listener
$('input[name="ItemName1"]').each( function() {
// Click Handler
$(this).live('click', function() {
// Check for selected
if ( $(this).is(':checked') )
{
$('#EarMark1').show();
}
else
{
$('#EarMark1').hide();
}
});
});
It's not perfect, nor is it the most elegant solution. With some tweaking it should point you in the right direction.

thank you to everyone!!! I ended up using kennypu's example - the ":checked" seemed to work fine even though it is a radio button. I had to make some tweaks to it, and ended up with 2 separate functions instead of the "else". For some reason the other examples were not working for me - although I highly doubt it has to do with your code, and likely has to do with other things going on in the page. Since we're using an external form/database handler, we need to keep the events and other code there.
Here's what ended up working..
$(function(){
$("#Relief1").change(function(){
if($(this).is(":checked")) {
$("#Earmark1").show();
}
});
});
$(function(){
$("#Radio1, #Radio2, #Radio3, #Radio4, #Radio5, #Radio6, #Radio7").change(function(){
if($(this).is(":checked")) {
$("#Earmark1").hide();
}
});
});
Pretty clunky, but I got it to work how I needed. Thank you to everyone who contributed, it helped quite a bit.

Try:
<script>
var r=$('input[name="ItemName1"]).is(:checked);
if(r)
{
alert("Item is checked");//replace with any code
}
</script>

if you're already using jQuery, this is simple as using .show() and .hide():
$('#Relief1').on('change',function() {
if($(this).is(':checked')) {
$('#Earmark1').show();
} else {
$('#Earmark1').hide();
}
});
example fiddle: http://jsfiddle.net/x4meB/
also note, don't use duplicate ID's, they are meant to be unique (in this case, you have a dulpicate #Earmark1 for the p tag and span). Also, in the example fiddle, I changed it to a checkbox instead of a radio since You can't uncheck a radio if there is only one option.

Related

Targeting a clicked element

Fiddle
I am trying to make a button that toggles between making an img grayscale and normal. I need to find a way to properly target the button if it was clicked. I tried adding a class on click and then targeting that class. I also tried this.
$('.switch').on("click", function() {
if($(this).attr('data-click-state') == 1) {
$(this).attr('data-click-state', 0)
$(this).siblings('img').css("-webkit-filter", "grayscale(100%)");
} else {
$(this).attr('data-click-state', 1)
$(this).siblings('img').css("-webkit-filter", "none");
}
});
Why the button doesn't toggle between color and grayscale versions?
apparently the problem isn't in my jQuery but in my html, so is it not possible to use this jquery on a checkbox label?
When you press the button once, it detect two clicks. I set an alert outside the if statement and I would get it twice per click, so your problem lies with that.
I'm still inspecting it, but that the issue right now, need to figure out why it is occurring, will update.
Update:
Yes sir, that was the cause that I stated in the comments... Here is a fixed, and you can mess with it however you like.
$('#cmn-toggle-1').on("click", function() {
if($(this).attr('data-click-state') == '1') {
$(this).attr('data-click-state', '0')
$(this).parents().siblings('img').css("-webkit-filter", "grayscale(100%)");
}
else {
$(this).attr('data-click-state', '1')
$(this).parents().siblings('img').css("-webkit-filter","");
}
});
New HTML SNIP:
<div class="switch">
<input id="cmn-toggle-1" class="cmn-toggle cmn-toggle-yes-no" type="checkbox" data-click-state="1">
<label for="cmn-toggle-1" data-on="Color" data-off="B&W" data-click-state="1"></label>
</div>
As you can see if you look at the input, I added in the data-click-state="1"

What causes jQuery click event not always to fire?

I have the following script. The HTML is not dynamically added. 99% of the time, the confirm popup will open and the data will be posted if confirmed, but every now and then, the checkbox visually changes state, but the confirm popup does not open. I've witnessed this on Firefox 34.0.5 running on Windows 7, and haven't yet tested enough on other browsers.
What might cause this to happen, and how can it be prevented?
EDIT. It happens all the time when I go to the page and quickly click the checkbox.
<input type="checkbox" checked="" id="makePublic">
$(function() {
$("#makePublic").click(function(e){
if($(this).is(":checked")){
var status=1;
var message='Are you sure you wish to make this project public?';
}
else {
var status=0;
var message='Are you sure you wish to make this project private?';
}
if(window.confirm(message)) {
$.post('update.php',{id:$('#id').val(),status:status});
}
else {e.preventDefault();
return;
}
});
});
EDIT. It happens all the time when I go to the page and quickly click the checkbox.
Then you should disable the element until your javascript has finished. The issue is that the checkbox is visible without the event being attached. The best option in my opinion is to disallow the click (by setting it disabled or hiding etc) until after the event has been attached.
<input type="checkbox" checked="" id="makePublic" disabled="disabled">
$(function() {
$("#makePublic").click(function(e){
if($(this).is(":checked")){
var status=1;
var message='Are you sure you wish to make this project public?';
}
else {
var status=0;
var message='Are you sure you wish to make this project private?';
}
if(window.confirm(message)) {
$.post('update.php',{id:$('#id').val(),status:status});
}
else {e.preventDefault();
return;
}
});
$("#makePublic").prop('disabled','');
});

Hide / Show Multiple Divs

I am trying to create a form that has various hide/reveals in it and one of the last parts I need to do to this form is SHOW the payment information fields when only Credit Card is selected.
I have a test page setup here: http://www.faa.net.au/test/femmes-member-form.html
Process so far is:
Enter your details
Select Event Date
Selecting Member + 1 or more Guests ask for payment details
At the moment, I have displayed the 3 DIVs that I want to appear depending on the radio selection made but when I hide these, the code I have in place at present doesn't work.
Can anyone help me here at all please?
If you need the code, please let me know, with a number of different elements involved I didnt want to paste the whole thing on here, hopefully you can see the Source Code?
Here is the Javascript I have at present but not sure if its this that is wrong or if its clashing with something else?
<script type="text/javascript">
$(function() {
$('.cat_dropdown').change(function() {
$('#payMethod').toggle($(this).val() >= 2);
});
});
</script>
<script type="text/javascript">
$(document).ready(function () {
$(".payOptions").click(function () {
$(".paymentinfo").hide();
switch ($(this).val()) {
case "Credit Card Authorisation":
$("#pay0").show("slow");
break;
case "Direct Deposit":
$("#pay1").show("slow");
break;
case "Cash Payment (FAA Office)":
$("#pay2").show("slow");
break;
}
});
});
</script>
As per viewing code from View Souce and guessing that you have not added correct class in event handler. thus click event for radio is not getting invoked.
Change
$(".payOptions").click(function () {
to
$(".paymentmethod").click(function () {
You have not posted any source, but if you are using jQuery, you can simply do:
$(".commonclass").hide();
Provided that all 3 divs have the "commonclass" class.
Process goes something like this:
Start clean: hide all payment methods
Your radio inputs have paymentmethod class, so attach a change event listener to those elements
When one of the radios is selected, hide all of the payment methods, determine the one you want to show using index, and show that div
$('#pay0, #pay1, #pay2').hide();
$('input.paymentmethod').on('change', function(){
$('#pay0, #pay1, #pay2').hide();
var selected = $('input.paymentmethod').index($('input.paymentmethod:checked'));
$('#pay'+selected).show();
});
Used to jquery as like this
Css
#pay0, #pay1, #pay2{display:none;}
Jquery
$(document).ready(function(){
$('#payment').change(function(){
if($('#CAT_Custom_255277_0').attr('checked')){
$('#pay0').show();
$('#pay1').hide();
$('#pay2').hide();
}
else if($('#CAT_Custom_255277_1').attr('checked')){
$('#pay1').show();
$('#pay0').hide();
$('#pay2').hide();
}
else if($('#CAT_Custom_255277_2').attr('checked')){
$('#pay2').show();
$('#pay0').hide();
$('#pay1').hide();
}
});
});
Demo
As per my understanding, you're trying like below,
select value from dropdown, if the value !== "1" then show payment radio buttons
Based on the radio button selection, you want to show the respective div
From viewing your source code, it seems you're using jQuery lib and there use this
$(document).ready(function() {
$('input[type=dropdown]').on('change', function(){
if($(this).val() !== 1)
{
$('input[type=radio]').show();
}
}
$('input[type=radio]').on('change', function(){
if($(this).val() === "Credit Card Authorisation") {
$('#pay1').hide();
$('#pay2').hide();
$('#pay0').show();
}
else if($(this).val() === "Direct Deposit"){
$('#pay0').hide();
$('#pay2').hide();
$('#pay1').show();
}
else if($(this).val() === "Cash Payment (FAA Office)"){
$('#pay0').hide();
$('#pay1').hide();
$('#pay2').show();
}
});
});
Hope you understand.

How do you do a mandatory checkbox in a form?

I need a checkbox, where you move from one page to another after clicking the box. The checkbox should be required, given that you've read the terms and conditions link next to it.
I'm only half sure how to do this, something like this:
<input type="checkbox" value="confirm_prepay_terms" name="confirm_prepay_terms" align="middle" />
with Jquery:
<script type="text/javascript" language="javascript">
$(document).ready(function() {
if ($('form#prepay input:checkbox', 'confirm_prepay_terms').is(':checked') {
return true;
} else {
$('#confirm_terms_hint').text('Please try again - you need to check the box to move on');
$('#confirm_terms_hint').css('font-weight', 'strong');
return false;
}
}
</script>
At the moment though, I can't view the checkbox at all on the page, so perhaps my HTML is incorrect?
Hope you can help.
Your HTML is fine - is will show a checkbox - but without any text. You could add some using this markup :
<input type="checkbox" value="confirm_prepay_terms" name="confirm_prepay_terms" align="middle" >​Text here</input>​​​​​​​​​​​​​​​​​​​​​​​
In your JavaScript you are missing a closing ) :
if ($('form#prepay input:checkbox', 'confirm_prepay_terms').is(':checked') {
should be
if ($('form#prepay input:checkbox', 'confirm_prepay_terms').is(':checked')) {
and a ) on the last line :
}
</script>
should be
})
</script>
and your selector is incorrect
$('form#prepay input:checkbox', 'confirm_prepay_terms')
should be
$('form#prepay input:checkbox[name=confirm_prepay_terms]')
This uses the multiple attribute selector
and
$('#confirm_terms_hint').css('font-weight', 'strong');
should be
$('#confirm_terms_hint').css('font-weight', 'bold');
font-weight has no strong value (see here) ... use bold instead
in your script you are returning true or false but the code is not being called by anything - its executing as soon as the page has completed loading. Have a look at the .submit() method in jQuery if you want to perform form validation. An example would be this :
$(document).ready(function() {
$('#prepay').submit(function() {
if ($('form#prepay input:checkbox[name=confirm_prepay_terms]')) {
return true;
} else {
$('#confirm_terms_hint').text('Please try again - you need to check the box to move on');
$('#confirm_terms_hint').css('font-weight', 'bold');
return false;
}
});
});
This would prevent the form from being submitted now - as you return false to the submit event.
Fully working example here
I don't think it is necessary for you to provide a CheckBox as long as they must accept this terms and conditions before using the service.
You can just do the following and stress-less yourself .
- Provide a link to the terms and conditions for reading
- Notify them that they have automatically accept this terms while proceeding.

jquery / javascript for a user to select 1 of n images

I want to display a few images (probably 5 max) and have a user click to select one. First thing I tried was radio buttons and putting the images inside labels.
<input type="radio" name="BackgroundId" id="BackgroundId" value="1" />
<label for="BackgroundId"><img src="../../Content/images/thumb_1.jpg" /></label>
Firefox will select the radio button when the user clicks the image, but IE doesn't.
Is there a jquery plugin that will make the images clickable? Fancy-form looks like something I could use, but it isn't jquery and I've already got jquery in my project.
Or can someone point me to a better way of selecting a single image?
Something like
$(function(){
$("label img").click(function(){
var parent = $(this).parent();
$("#" + parent.attr("for")).attr("checked", "checked");
});
});
Just drop this javascript into your page. I have tested it.
<script language="javascript" type="text/javascript">
$(document).ready(
function ()
{
var selImg = $("#BackgroundId").next("label").find("img");
selImg.click(
function ()
{
$("#BackgroundId")[0].click();
});
});
</script>
The code reads:
Get all the next element after those elements that have an id='BackgroundId'
Now find an img element inside each one.
Set the click events if each found img to call a function that will simulate a click on all those elements that have an id='BackgroundId'.
Please note that even though I am writing "all those" and "each tag", since there is only one tag with the id of 'BackgroundId', all these things are happening singularly.

Categories