简体   繁体   中英

When checkbox is checked show hidden button and hide the visible button

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> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM