0

Following this answered question, I am attempting to have a checkbox at the end of each row of my table, which contains 2 text field inputs per row.

I would like the inputs to become "disabled" if the checkbox has been checked.

My HTML:

<table class="forecast">
    <tr>
      <th>Question</th>
      <th>Answer A</th>
      <th>Answer B</th>
      <th>Not applicable</th>
    </tr>
    <tr>
      <td>Quesiton 1</td>   
      <td>
        <input id="" name="q1a" value="" size="10" maxlength="10" />
      </td>
      <td>
        <input class="" title="" id="" name="q1b" value="" size="10" maxlength="10" />
      </td>
      <td >
        <input type="checkbox" id="" class="notused" name="" />
      </td>
    </tr>
    <tr>
      <td>Quesiton 2</td>   
      <td>
        <input id="" name="q2a" value="" size="10" maxlength="10" />
      </td>
      <td>
        <input class="" title="" id="" name="q2b" value="" size="10" maxlength="10" />
      </td>
      <td >
        <input type="checkbox" id="" class="notused" name="" />
      </td>
    </tr>
</table>

My attempted jQuery:

$('.notused').delegate(':checkbox', 'change', function() {
    $(this).closest('tr').find('input:text').attr('disabled', this.checked);
});
$(':checkbox').change(); 

Nothing happens when I check the box, there are no errors in my console. Any help would be appreciated thank you.

2 Answers 2

4

You need to use .prop() to set the checked property, Also prefer .on() to register event handlers

$('.forecast').on('change', ':checkbox', function () {
    var $inpts = $(this).closest('tr').find('input:text').prop('disabled', this.checked);
    if(this.checked){
        $inpts.val(0)
    }
}).find(':checkbox').change();

(Assuming you are using jQuery >= 1.7)

Demo: Fiddle

Sign up to request clarification or add additional context in comments.

8 Comments

Thank you, this works perfectly (yes, I'm on jQuery 1.9.1) I will accept this answer when the time runs out
And may I ask, how could I also set the input values to 0 if it was checked?
that doesn't seem to work (The edit) should the var have a $ for sure?
@Gideon checkout the fiddle... is it working for you? it is working for me
yes the fiddle is - in chrome however I was getting an uncaught exception and the code was not showing var $inpts = but instead var = I removed the $ sign such that it was var inpts= and this is now working. Something strange?
|
0

Try this, Using Jquery 1.9.1

$(function(){
$('.forecast').delegate(':checkbox', 'change', function() {
    $(this).closest('tr').find('input:text').attr('disabled', this.checked);
});
});

Demo

Updated Demo with 0 value

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.