0

I'm trying to disable a textbox if a checkbox is not checked , and enable it if the checkbox is checked in javascript

here is my code but it's not working :

        if($productsArray[$i])
        {
        $productName = $productsArray[$i]->getProductName() ;
        $id = $productsArray[$i]->getId(); 
        $product = $control->getNonFreshProductById($id); 
        $personAmount  = $product->getPersonAmount() ; 

        echo "<tr>";
        echo "<th  td valign='middle' > <br/> <input type='checkbox' name='nonFreshProduct".$i."' id ='nonFreshProduct".$i."' style='position:absolute; left:20%' onclick='document.getElementById('outcome".$i."').disabled=!this.checked;'/>".$productName."</th>";
        echo "<th  td valign='middle' style='text-align:-webkit-left'> <br/> <input type='text' name='outcome".$i."' id ='outcome".$i."'/></th>";
        echo "<input type='hidden' name='nfid".$i."' id='nfid".$id."' value='".$id." ' /></th>";
        echo "</tr>";
    }
dee-see
  • 23,668
  • 5
  • 58
  • 91
Haya D
  • 357
  • 2
  • 4
  • 16

2 Answers2

0

With jQuery you can do:

$( '#myInput' ).prop( 'disabled', $('#mycheckBox').is( ':checked' ) );

http://api.jquery.com/prop/

http://api.jquery.com/is/

Without jQuery you can do:

document.getElementById('myInput').disabled = document.getElementById('mycheckBox').checked;

This method is kind of dirty, I've found this question and answer to be more to my liking:

Toggle Disabled Attribute on Input Based on Checkbox in jQuery

Community
  • 1
  • 1
Matt Wagner
  • 910
  • 7
  • 14
0

All you have to do is to have a handler listening to the change event of the checkbox, and then enable/disable based on the event.

jsfiddle example: http://jsfiddle.net/w9u09ohc/

sample code:

Edit: to use javascript in PHP, all you have to do is put the script in a script tag

<script type="text/javascript">
    function enableElement(element) {
        $(element).removeAttr('disabled');
    }

    function disableElement(element) {
        $(element).attr('disabled', 'disabled');
    }

    function checkboxChangeHandler() {
        var checkbox = $('#ckb'),
            textbox = $('#txb');

        if(checkbox.is(':checked'))
        {
            enableElement(textbox);
        }
        else
        {
            disableElement(textbox);
        }
    }


    $('#ckb').on('change', checkboxChangeHandler);
</script>
George
  • 1,552
  • 1
  • 17
  • 26