简体   繁体   中英

Disable button if only one div

I have two buttons. One where i clone a div (button-add) and one where I remove a div (button-remove).

I want to disable the remove-button when I only have one div.

So for multiple divs, it looks like this:

<button type="button" class="btn btn-default btn-lg button-add">+1</button>
<button type="button" class="btn btn-default btn-lg button-remove">-1</button>
<div class="copybox"></div>
<div class="copybox"></div>
<div class="copybox"></div>

...and when there's only one div, I want it to look like this:

<button type="button" class="btn btn-default btn-lg button-remove" disabled>-1</button>
<div class="copybox"></div>

I use jQuery 1.11.3

Here you go. Hope this is what you need.

 $('.btn').on('click',function(){ if($(this).text()=="+1") { $('.button-remove').prop('disabled',false); $('div.copybox:first').clone().appendTo('body'); } else { $('div.copybox:last').remove(); } $('div.copybox').length==1?$(this).prop('disabled',true):$(this).prop('disabled',false) }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <button type="button" class="btn btn-default btn-lg button-add">+1</button> <button type="button" class="btn btn-default btn-lg button-remove">-1</button> <div class="copybox">Copy</div> <div class="copybox">Copy</div> <div class="copybox">Copy</div> 

Try using the $("div.copybox").length that DontVoteMeDown commented and then set an ID for the button remove. Once you do that, you can add a function to hide the button with this code.

document.getElementById(buttonID).style.display = 'none'

If later you decide to enable it again, then you can also add another if statement and then the code for that would be block instead of none

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