I am trying to show a <div> when a certain radio button is selected by the user.
I found some nice code form http://www.tutorialrepublic.com/faq/show-hide-divs-based-on-radio-button-selection-in-jquery.php and I adapted it for myself like this:
With the CSS & script:
<style type="text/css">
.box{padding: 2px;display: none;margin-top: 2px;border: 0px solid #000;}
.red{ }
.green{ }
.blue{ }
</style>
<script type="text/javascript" src="http://code.jquery.com/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$('input[type="radio"]').click(function(){
if($(this).attr("value")=="Tax representation"){
$(".box").not(".red").hide();
$(".red").show();
}
if($(this).attr("value")=="VAT recovery"){
$(".box").not(".green").hide();
$(".green").show();
}
if($(this).attr("value")=="Other"){
$(".box").not(".blue").hide();
$(".blue").show();
}
});
});
</script>
Then I got this to remember the selection:
if (!empty($_REQUEST['object'])) { $object = $_REQUEST['object']; }
Add the radio selection in the form that remembers the selection if the form needs to be reloaded:
<input tabindex="1" type="radio" name="object" <?php if (isset($object) && $object=="Tax representation") echo "checked";?> value="Tax representation">Tax representation
<input tabindex="2" type="radio" name="object" <?php if (isset($object) && $object=="VAT recovery") echo "checked";?> value="VAT recovery">VAT recovery
<input tabindex="3" type="radio" name="object" <?php if (isset($object) && $object=="Other") echo "checked";?> value="Other">Other
Followed with the <div> to be shown or hidden:
<div class="red box">text 1</div>
<div class="green box">text 2</div>
<div class="blue box">text 3</div>
Now my problem is that when the form is reloaded, the radio selection is memorized, but the corresponding <div> does not show.
I believe there may be a way to change the script from "click" to "selected" or something like that. Would you help?
This is similar to previous answers, extracting the behavior into a function so that you can run it on page load and in an event:
function showBoxes(value) {
if(value=="Tax representation"){
$(".box").not(".red").hide();
$(".red").show();
}
if(value=="VAT recovery"){
$(".box").not(".green").hide();
$(".green").show();
}
if(value=="Other"){
$(".box").not(".blue").hide();
$(".blue").show();
}
}
$(document).ready(function(){
showBoxes($("input[type='radio']:checked").attr("value"));
$('input[type="radio"]').click(function(){
showBoxes($(this).attr("value"));
});
});
jsFiddle
Use change instead of click
$('input[type="radio"]').change(function(){
Then, move your function to a variable and call it when the page loads.
The final code should look something like this.
$(document).ready(function(){
var updateDivs = function(){
if($(this).attr("value")=="Tax representation"){
$(".box").not(".red").hide();
$(".red").show();
}
if($(this).attr("value")=="VAT recovery"){
$(".box").not(".green").hide();
$(".green").show();
}
if($(this).attr("value")=="Other"){
$(".box").not(".blue").hide();
$(".blue").show();
}
}
$('input[type="radio"]').click(updateCheckbox);
$.proxy(updateDivs, $('input[type="radio"]'))
});
Add this line after your $('input[type="radio"]').click(function(){ code and inside the document.ready block
$('input[type="radio"]:checked').trigger('click');
Your current logic will work only when the radio buttons are clicked. So let's trigger the click event of the checked radio button when the page reloads. Which inturn will run your logic and toggle the divs accordingly.
Related
EDIT
I don't have access to the original HTML. I can only add jQuery to the page.
I was trying to figure out how to show/hide an element (div) on a page dynamically based on if another element (div) exists.
I have a checkbox on the page that gets a class appended when clicked.
The code here is what I was thinking I would like. But it just hides the element when .is-checked exists. It doesn't toggle it back again.
$( document ).ready(function() {
if($('.is-checked').length){
$('.fn_container_start').hide();
}
});
I already have a checkbox with a class called .selectit and when you click it a class get's appended called .is-checked
I would like that when .is-checked get's appended on the page that it hides the class .fn_container_start
But also when .is-checked is not on the page, the .fn_container_start class should be hidden again.
Here's the html for the checkbox before and after it's clicked
Before the checkbox is clicked
<label class="selectit"><input value="157" type="checkbox" name="download_category[]" id="in-download_category-157"> Brushes</label>
After
<label class="selectit is-checked"><input value="157" type="checkbox" name="download_category[]" id="in-download_category-157"> Brushes</label>
Is this possible?
Thanks,
Morten
function valueChanged(){
if($('.toggle_check').is(":checked")) {
$('.fn_container_start').hide();
$('.toggle_check').addClass('is-checked');
}
else{
$('.fn_container_start').show();
$('.toggle_check').removeClass('is-checked');
}
}
<label class="selectit"><input value="157" type="checkbox" class="toggle_check" name="download_category" id="in-download_category-157" onchange="valueChanged();"> Brushes</label>
<div class="fn_container_start">
<p class="hide">div hides if the checkbox checked</p>
</div>
<script src="https://code.jquery.com/jquery-3.2.1.slim.min.js" integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN" crossorigin="anonymous"></script>
I think you can use .hasClass method
$( document ).ready(function() {
$("#in-download_category-157").click(function() {
$(".selectit").toggleClass("is-checked");
if($('.selectit').hasClass('is-checked')){
$('.fn_container_start').hide();
}else{
$('.fn_container_start').show();
}
});
});
Use this code
<script type="text/javascript">
$(document).ready(function() {
$('input[type="checkbox"]').click(function() {
$(".selectit").addClass("is-checked");
});
});
</script>
$( document ).ready(function() {
$('.selectit').on('click', function(){
$('.fn_container_start').toggleClass("hidden");
});
});
.hidden{display:none !important;}
.fn_container_start{border:1px dashed red;}
<label class="selectit"><input value="157" type="checkbox" name="download_category[]" id="in-download_category-157"> Brushes</label>
<div class="fn_container_start">This div have .fn_container_start class</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
$('.selectit input.toggle_check').on('change',function(){
if($(this).is(":checked")) {
$('.fn_container_start').hide();
$(this).addClass('is-checked');
}
else{
$('.fn_container_start').show();
$(this).removeClass('is-checked');
}
})
<label class="selectit"><input value="157" type="checkbox" class="toggle_check" name="download_category" id="in-download_category-157"> Brushes</label>
<div class="fn_container_start">
<p class="hide">div hides if the checkbox checked</p>
</div>
<script src="https://code.jquery.com/jquery-3.2.1.slim.min.js" integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN" crossorigin="anonymous"></script>
I have a specific problem where I need to render a html string from the server and show it to the user. The user then clicks the checkboxes and I transform it back into a html string and save it on the server.
Problem is after the user clicks the checkboxes, the transformed HTML string does not contain the checked attribute.
Here is a snippet
$("button").on("click", function(){
console.log($("#container").html());
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="container">
<input type="checkbox" id="checkbox"/>
<button> Test </button>
</div>
But when I manually click the checkbox and click the button and examine the console log, the checked attribute inside the HTML string is not seen.
How can I solve this problem?
Set checked attribute manually by .attr('checked', 'checked') on change:
$("button").on("click", function() {
console.log($("#container").html());
});
$('#checkbox').change(function() {
if ($(this).is(':checked')) {
$(this).attr('checked', 'checked');
} else {
$(this).removeAttr('checked');
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="container">
<input type="checkbox" id="checkbox" />
<button> Test </button>
</div>
When you check a checkbox manually, the checked HTML attribute doesn't change.
You can change it yourself by selecting every checked checkbox and manually updating them with the jQuery :checked selector:
$('#container input[type="checkbox"]:checked').attr('checked','true');
$("button").on("click", function() {
$('#container input[type="checkbox"]:checked').attr('checked','true');
console.log($("#container").html());
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="container">
<input type="checkbox" id="checkbox" />
<button> Test </button>
</div>
I am a beginner in javascript, hopefully you can help me with this problem..
I have 2 buttons in html form and 1 checkbox, 1 button should be hidden and the other is visible. My problem is how to show the hidden button and hide the visible button at the same time when the checkbox is checked..
I know how to hide/show the button flip-ch1 but I can't do it to other button.
I have a script here:
$(document).ready(function() {
$('#flip-ch1').hide();
$('#radio').mouseup(function() {
$('#flip-ch1').toggle();
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
<input type="checkbox" name="radio" id="radio">
<button class="btn_style" id="ch1">Add</button>
<button class="btn_style" id="flip-ch1">Add</button>
</div>
Toggle them both:
<script type="text/javascript">
$(document).ready(function(){
$('#flip-ch1').hide();
$('#radio').mouseup(function () {
$('#ch1').toggle();
$('#flip-ch1').toggle();
});
});
</script>
Just add this line:
$('#ch1').toggle();
So, the complete js code would be:
$(document).ready(function () {
$('#flip-ch1').hide();
$('#radio').mouseup(function () {
$('#flip-ch1').toggle();
$('#ch1').toggle();
});
});
Do not get confused by the .hide(). It is used to hide one of the buttons only in the beginning. No need to use afterwards. The reason that you do not see any changes after toggling the checkbox, is that when first button is hidden the second one gets its place, the place does not remain empty. You can spot all this that I mentioned on inspect element of any major browser.
Try $('#radio').is(':checked') as below
$(document).ready(function() {
$('#flip-ch1').hide();
$('#radio').on('change', function() {
if ($('#radio').is(':checked')) {
$('#flip-ch1').show();
$('#ch1').hide();
} else {
$('#flip-ch1').hide();
$('#ch1').show();
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
<input type="checkbox" name="radio" id="radio">
<button class="btn_style" id="ch1">Add 1</button>
<button class="btn_style" id="flip-ch1">Add 2</button>
</div>
I'm working on a project where a button needs to be disabled until a hyperlink is clicked and a checkbox is checked. I currently have the checkbox part down using jQuery:
$('#tc-checkbox').change(function(){
if($(this).is(":checked")) {
$('#tc-btn').removeClass('tc-disable');
} else {
$('#tc-btn').addClass('tc-disable');
}
});
But I also need to set it up so the class of tc-disable is still on the button until an anchor tag is clicked as well. I've never really done this before where a link needs to be clicked before removing a class and couldn't find what I was looking for as I was Googling for an answer.
Hope the code below helps. I also added console out put so you can track the value. Another option is use custom attribute on link element instead of javascript variable to track if the link is clicked.
var enableLinkClicked = false;
$('#tc-link').click(function() {
enableLinkClicked = true;
console.log("link clicked\ncheckbox value: " + $($('#tc-checkbox')).is(":checked"));
console.log("link clicked: " + enableLinkClicked);
if ($('#tc-checkbox').is(":checked")) {
$('#tc-btn').removeClass('tc-disable');
}
});
$('#tc-checkbox').change(function() {
console.log("checkbox clicked\ncheckbox value: " + $(this).is(":checked"));
console.log("link clicked: " + enableLinkClicked);
if ($(this).is(":checked") && enableLinkClicked) {
$('#tc-btn').removeClass('tc-disable');
} else {
$('#tc-btn').addClass('tc-disable');
}
});
#tc-btn.tc-disable {
background: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<button id="tc-btn">My Button</button>
<br/>
<a id="tc-link" href="javascript:void(0);">Link to enable button</a>
<br/>
<input type="checkbox" id="tc-checkbox" />
If the page is refreshing or taking you to a different page when you click the hyperlink, you will want to look into sessionStorage. When the hyperlink is clicked you will want to set a sessionStorage variable and when the page loads you want to check that variable to see if it is populated. If the variable is populated, enable the button.
Set the variable.
sessionStorage.setItem('key', 'value');
Get the variable
var data = sessionStorage.getItem('key');
If you need to re-disable the button you can clear the session storage and reapply the disabled class.
sessionStorage.clear();
You can learn more about session storage here.
If the page does not refresh you could just set an attr on the link when it is clicked like so.
$('#tc-link').on('click', function() {
$(this).attr('clicked', 'true');
});
Then when the checkbox is checked you can check this in your function.
$('#tc-checkbox').change(function(){
if($(this).is(":checked") && $('#tc-link').hasAttr('clicked')) {
$('#tc-btn').removeClass('tc-disable');
} else {
$('#tc-btn').addClass('tc-disable');
}
});
These are just some solutions I could think of off the top of my head. Hope this helps.
Maybe this is better for you. First you make an .on('click' event listener on the anchor element, then, if the checkbox is checked enable the button. I added the else statement to disable the button if a user clicks the link and the checkbox is not set for an example. In this example you don't need the classes.
But if you needed to keep the the classes then you would replace the $('#tc-btn').prop('disabled', false); with $('#tc-btn').addClass() or .removeClass()
$( '#theLink' ).on( 'click', function(e)
{
e.preventDefault();
if($('#tc-checkbox').is(':checked'))
{
$('#tc-btn').prop('disabled', false);
$('#tc-btn').val('Currently enabled');
}
else
{
$('#tc-btn').val('Currently disabled');
$('#tc-btn').prop('disabled', true);
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="checkbox" id="tc-checkbox" />
This link will enable the button
<input type="button" id="tc-btn" value="Currently disabled" disabled="disabled"/>
Here a much more simple solution and it handles the state of the button if they uncheck the "I Accept" checkbox. It is pretty easy to implement. I just used Bootstrap to pretty up the example.
//Handles the anchor click
$("#anchor").click(() => {
$("#anchor").addClass("visited");
$("#acceptBtn").prop("disabled", buttonState());
});
//Handles the checkbox check
$("#checkBx").on("change", () => {
$("#acceptBtn").prop("disabled", buttonState());
});
//Function that checks the state and decides if the button should be enabled.
buttonState = () => {
let anchorClicked = $("#anchor").hasClass("visited");
let checkboxChecked = $("#checkBx").prop("checked") === true;
return !(anchorClicked && checkboxChecked);
}
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.2/css/bootstrap.min.css" rel="stylesheet"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container">
<div class="row">
<div class="col-md-12">
View Terms
</div>
</div>
<div class="row">
<div class="col-md-12">
<label class="form-check-label">
<input class="form-check-input" id="checkBx" type="checkbox" value="">
I accept the terms
</label>
</div>
</div>
<div class="row">
<div class="col-md-12">
<button id="acceptBtn" class="btn btn-success" disabled="disabled">
Ok
</button>
</div>
</div>
</div>
A one-liner solution using Javascript could be:
<input type="submit" id="test" name="test" required disabled="disabled">
<label for="test">I clicked the <a target="_blank" href="https://stackoverflow.com" onclick="document.getElementById('test').disabled=false">link</a>.</label>
Change the type "submit" to "button" or "checkbox" accordingly to your needs.
I have select menu option in right side of my website "I wish to sponsor". Default drop down menu set to "select" option I want when someone press go button page will not go anywhere. Currently when user press go button without selection option it goes to "404" page. How can I stop page to go somewhere without selection two given option in drop down?
Screenshot also attached and link is : http://ilmoamal.org/newsite2017/sponsor-now-testing/
enter image description here
Using CSS you can remove!
<style>
#link:focus option:first-of-type {
display: none;
}
</style>
You can use this in your footer.php file of WordPress theme. This will disable the "Go" button if no option is selected.
<script>
jQuery( document ).ready(function() {
jQuery(".wpcf7-form .submit input").prop('disabled', true);
jQuery(".wpcf7-form select option:first").prop('disabled', true);
jQuery("#link").change(function(){
var conceptName = jQuery('#link').find(":selected").text();
if(conceptName == "select"){
} else {
jQuery(".wpcf7-form .submit input").prop('disabled', false);
}
});
});
</script>
jQuery( document ).ready(function() {
jQuery(".wpcf7-form .submit input").prop('disabled', true);
jQuery(".wpcf7-form select option:first").prop('disabled', true);
jQuery(".wpcf7-form select option:first").prop('selected', true);
jQuery("#link").change(function(){
var conceptName = jQuery('#link').find(":selected").text();
if(conceptName == "select"){
} else {
jQuery(".wpcf7-form .submit input").prop('disabled', false);
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<form class="wpcf7-form">
<h4>I wish to sponsor</h4>
<p><select id="link"><option>Select</option><option value="http://ilmoamal.org/bms/apps_available.php?start=1&link=72f061b63526b44879240efb612646ed&project_id=1&submit=+Go+">A Child’s Education</option><option value="http://ilmoamal.org/bms/apps_available.php?start=1&link=72f061b63526b44879240efb612646ed&project_id=3&submit=+Go+">A Family Help</option></select></p>
<div class="submit"> <input onclick="go()" name="submit" value="Go" type="button" id="submit"> </div>
</div>
</form>
You can click on "Show Code Snippet" link above to RUN and test this code.
add below code in function.php file for remove select option
<?php
function myscript() {
?>
<script type="text/javascript">
$(document).ready(function()
{
$("#link").children().first().remove();
});
</script>
<?php
}
add_action( 'wp_footer', 'myscript' );
?>
I have seen that you use contact form 7 select box.
And also seen that you have set value for 2nd and 3rd option in select box but in first option there are no value for that option.
The best way is set the value # to first option which you want to disable.
Then let me know the result.
I mean
<option value="#">Select</option>
just add this in your script-
jQuery(document).ready(function(){
jQuery('#sidebar #link > option:first-child').attr('disabled', 'disabled');
});