2

How to disable an input and enable through button click if the ID is something like this id="qty_<?php echo $x; ?>" not a normal id="qty"

<input type="number" name="qty[]" min="0" id="qty_<?php echo $x; ?>" class="form-control" required onclick="getTotal(<?php echo $x; ?>)" onkeyup="getTotal(<?php echo $x; ?>)" value="<?php echo $val['qty'] ?>" autocomplete="off">

javascript - how to use this kind of id? id="qty_<?php echo $x; ?>

function enablebutton(){    
  $('*#my_field').prop( "disabled", false );

}

the normal id like id="qty" is working but i need the solution on how to use this kind of id id="qty_<?php echo $x; ?>" when enable/disable an input

wloleo
  • 1,294
  • 2
  • 6
  • 15

1 Answers1

1

Assuming that you have the following button:

<input type=button value="Disable" onclick='javascript:disablebutton(<?php echo $x; ?>)'>

Then the JS function to disable the element with id ="qty_<?php echo $x; ?> will be

function disablebutton(var1){    
  $('#qty_' + var1).prop( "disabled", true );

}

Note: for enablebutton, it will be

function enablebutton(var1){    
  $('#qty_' + var1).prop( "disabled", false );
}

So, put them all together, will be like

<script
  src="https://code.jquery.com/jquery-3.6.1.js"
  integrity="sha256-3zlB5s2uwoUzrXK3BT7AX3FyvojsraNFxCc2vC/7pNI="
  crossorigin="anonymous"></script>

<?php $x=1; ?>

<input id="qty_<?php echo $x; ?>" value=10>
<input type=button value="Disable" onclick='javascript:disablebutton(<?php echo $x; ?>)'>
<input type=button value="Enable" onclick='javascript:enablebutton(<?php echo $x; ?>)'>

<script>
function disablebutton(var1){    
  $('#qty_' + var1).prop( "disabled", true );
}

function enablebutton(var1){    
  $('#qty_' + var1).prop( "disabled", false );
}
</script>

You may click this sandbox to see the effect:

http://www.createchhk.com/SOanswers/testSO26Nov2022.php

Of course in practice, you may have multiple input boxes with multiple buttons, so changing the $x value dynamically (e.g use the database key) will be the usual way to do it.

Ken Lee
  • 6,985
  • 3
  • 10
  • 29