How to Enable/Disable a Textbox in table rows using PHP and jQuery

A readonly textbox is also used for preventing accidental inputs by users. Some projects required input fields in the rows of a table. Only after click a checkbox in the row will disable the readonly of a textbox. This post will help you to do such kind of task. Here I am retrieving database information in foreach loop and display data in rows using PHP.

<?php
foreach($getSrvPrice as $info){
?>
<tr>
<td><input type=”checkbox” name=”srvids[]” value=”<?php echo $info[‘srv_id’];?>” id=”chk_<?php echo $info[‘srv_id’];?>” onclick=”writePrice(this.value)”/></td>
<td><?php echo $info[‘tkt_name’];?></td>
<td><?php echo $info[‘tkt_description’];?></td>
<td>
<input type=”text” name=”srvprice[<?php echo $info[‘tkt_id’];?>][]” readonly=”true” id=”prz_<?php echo $info[‘srv_id’];?>” value=”<?php
echo $getPriceForPhysrv;?>” />
</td>
</tr>
<?php } ?>

Below screen shows the example table with rows containing checkbox and readonly textbox.

checkbox-1

First set all the required textbox field to readonly, in the textbox add readonly=”true” attribute. You can notice in the source code mentioned above.

Set value and id of checkbox using the database tables row id(unique). Include the onclick event function writePrice(this.value).

<input type=”checkbox” value=”<?php echo $info[‘srv_id’];?>” id=”chk_<?php echo $info[‘srv_id’];?>” onclick=”writePrice(this.value)”/>

Then set for text field which is readonly mode.

<input class=”form-control” type=”text” name=”srvprice” readonly=”true” id=”prz_<?php echo $info[‘srv_id’];?>” value=”<?php echo $info[‘price’];?>” />

Finally, implement the below jquery script in your javascript file used in that webpage.

<script type=”text/javascript”>

function writePrice(rowid)
{
var rowchk=’#chk_’+rowid;
var enablerow=’#prz_’+rowid;
if($(rowchk).is(“:checked”))
{
$(enablerow).removeAttr(‘readonly’);
}
else
{
$(enablerow).attr(‘readonly’,’true’);
}
}

</script>

Now it’s time to see the output which should work as below screen.

reaonly-dis

Have A Great Day… !

Leave a comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.