简体   繁体   中英

Checkbox Javascript disable button

I have an array of users in php that i send to the view (in laravel) and do a foreach to list all users in table. For now it is ok. I have a "send" button that appear disable but i want to put visible when i click on the checkbox.

在此处输入图片说明

I put this javascript code:

<script type="text/javascript">
Enable = function(val)
{
    var sbmt = document.getElementById("send"); //id of button

    if (val.checked == true)
    {
        sbmt.disabled = false;
    }
    else
    {
        sbmt.disabled = true;
    }
}    
</script>

and call the function onClick method of checkbox:

onclick="Enable(this)"

But the problem is when i click on the check box only the first button send works and appear visible. If i click for example in check box of user in position 2,3,4...etc the buttons send of these users stay disabled, only the first appear visible. This code only work to the first position of send button.

I appreciate your help :)

Regards

  1. You pass element to function Enable , but treat it as value. You should extract value from element before other actions.
  2. You hardcoded button id in the function. It shout be passed outside and should differs for each button.

 Enable = function(checkbox, btnId) { document.getElementById(btnId).disabled = !checkbox.checked; // ← ! }
 <button id="send1" disabled>SEND</button> <input type="checkbox" onclick="Enable(this, 'send1')"><br> <button id="send2" disabled>SEND</button> <input type="checkbox" onclick="Enable(this, 'send2')"><br> <button id="send3" disabled>SEND</button> <input type="checkbox" onclick="Enable(this, 'send3')">

The reason is that you are using id element to activate button. What you can do is set id for each of your send button while you loop and pass it from your click your function and use it enable it.

<script type="text/javascript">
Enable = function(val, id)
{
    var sbmt = document.getElementById("send-"+ id ); //id of button

    if (val.checked == true)
    {
        sbmt.disabled = false;
    }
    else
    {
        sbmt.disabled = true;
    }
}    
</script>

and your click button looks like this

onclick="Enable(this,id)"

Hope you understood.

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