Cross Vander
Cross Vander

Reputation: 2177

Javascript Checkbox add value Textarea

I have a code like these:

var fails = 'fail';
var sucs = 'success';

function showResult(state){
	if(state){
      document.getElementById("hasil").value=sucs;
    }else{
      document.getElementById("hasil").value=fails;
    }									
}
<form>
  <table border='1'>
    <tr>
      <th>TARGET</th>
      <th>RESULT</th>
      <th>NOTES</th>
    </tr>
    <tr>
      <td><input type='checkbox' name='target' onclick='showResult(this.checked);' /></td>
      <td><textarea name='result[]' id='hasil'>fail</textarea></td>       <td><textarea name='notes[]' class='form-control'></textarea></td>
    </tr>
    <tr>
      <td><input type='checkbox' name='target' onclick='showResult(this.checked);' /></td>
      <td><textarea name='result[]' id='hasil'>fail</textarea></td>       <td><textarea name='notes[]' class='form-control'></textarea></td>
    </tr>
    <tr>
      <td><input type='checkbox' name='target' onclick='showResult(this.checked);' /></td>
      <td><textarea name='result[]' id='hasil'>fail</textarea></td>       <td><textarea name='notes[]' class='form-control'></textarea></td>
    </tr>
</form>

I want to create that checkbox, if it's clicked, it will change textarea on that row to success. If I uncheck, it will change back to fail. Can anyone help me?

Upvotes: 1

Views: 588

Answers (1)

Divyang Desai
Divyang Desai

Reputation: 7864

it only works for the first row.

As @epascarello said, because ids are singular. so you need to select the parent tr, find the text area and set the value.

You can do in this way.

$('[type=checkbox]').change(function() {

  if ($(this).is(":checked")) {
    var $row = $(this).parents('tr');
    $row.find('textarea[name="result[]"]').text("sucess");
  } else {
    var $row = $(this).parents('tr');
    $row.find('textarea[name="result[]"]').text("fail");
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
  <table border='1'>
    <tr>
      <th>TARGET</th>
      <th>RESULT</th>
      <th>NOTES</th>
    </tr>
    <tr>
      <td>
        <input type='checkbox' name='target' />
      </td>
      <td>
        <textarea name='result[]' id='hasil'>fail</textarea>
      </td>
      <td>
        <textarea name='notes[]' class='form-control'></textarea>
      </td>
    </tr>
    <tr>
      <td>
        <input type='checkbox' name='target' />
      </td>
      <td>
        <textarea name='result[]' id='hasil'>fail</textarea>
      </td>
      <td>
        <textarea name='notes[]' class='form-control'></textarea>
      </td>
    </tr>
    <tr>
      <td>
        <input type='checkbox' name='target' />
      </td>
      <td>
        <textarea name='result[]' id='hasil'>fail</textarea>
      </td>
      <td>
        <textarea name='notes[]' class='form-control'></textarea>
      </td>
    </tr>
</form>

Upvotes: 1

Related Questions