Click here to Skip to main content
15,867,453 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
i need to get the texbox value in the function when checking the checkbox

What I have tried:

<table>
<?php foreach ($list_points as $points):
$i=1; ?>

<tr class="gradeA">
<td><?php echo $points['vehiclename'] ?></td>
<td><input type="text" name="ptime" id="ptime-text<?php echo $i; ?>" class="ptime-text"></td>
<td>
<div class="i-checks ptime-check"&gt;
<label>
<input type="checkbox" value="" target="ptime-text<?php echo $i; ?>" class="test" onclick="check_ptime();"> <i></i>
</label>
</div>
</td>
</tr>
<?php $i++;endforeach; ?>

</table>



my script function is


function check_ptime()
{
alert($(this).parent().parent().parent().parent().find('.ptime-text').val());//here i need the value of thextbox
}
Posted
Updated 23-May-20 0:59am
v4

1 solution

jQuery has a change() event that you can subscribe to when a CheckBox is checked. For example:

JavaScript
$(".test").change(function() {
  //access the Texbox using the class name
  alert($(".ptime").val());

  //access the Texbox using the ID

  alert($("#ptime-text").val());
});


To access multiple TextBox values within rows, you can do something like this:

HTML
<table>
  <tr>
    <td class="td"><input type="text" class="txt"></td>
    <td><input type="checkbox" class="chk"></td>
  </tr>
  <tr>
    <td class="td"><input type="text" class="txt"></td>
    <td><input type="checkbox" class="chk"></td>
  </tr>
  <tr>
    <td class="td"><input type="text" class="txt"></td>
    <td><input type="checkbox" class="chk"></td>
  </tr>
</table>


jQuery code:
JavaScript
$(".chk").change(function() {
  var $row = $(this).closest("tr")   // Finds the closest row <tr> 
                       .find(".td");  // Gets a descendent with class="td"
  var $txtValue = $row.find(".txt").val();   //access the Texbox using the class
  
  alert($txtValue);
                      
});


The idea is to group your elements (text and checkbox input) within a <tr> element so you can easily reference them by descendants.
 
Share this answer
 
v2
Comments
Member 13979401 10-Sep-18 23:40pm    
The above solution only get if there is one textbox value..but I have many textboxes and need to get each textbox value when checking the corresponding checkbox
Vincent Maverick Durano 11-Sep-18 10:21am    
Then you have to group your elements (text and checkbox input) within a <tr> element so you can easily reference them by descendants.

I've updated the solution for an example. Please refer to it.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900