How to Get Dynamic Id With Javascript/Jquery from PHP Loop

Catching a dynamic php loop id value for post using ajax

You are creating multiple hidden inputs with id "mtotal" in your foreach loop. You have to give unique ids to each hidden input, maybe based on the loop index/key:

foreach ($decodeMessages as $key => $messages) {

And:

<input type='hidden' id='mtotal_" . $key ."' value='".$messages['messageTotal']."' >

You should also add this key as data attribute on the corresponding button like this:

<button class='cancel-button' type='button' data-key='".$key."'><i class='fa fa-trash-o'></i></button>

Furthermore it would be better to use a class for your cancel button as I did above, then add your click handler in your javascript file. You can get the data-key attribute from the button and select your hidden input like this:

$('.cancel-button').click(function(){
var key = $(this).attr('data-key');
var datastring = $("#mtotal_" + key).val();
...
});

How to create dynamic id to a single button in foreach loop using html & js

Try this code it works...

<?php $no=1;  foreach($tables as $row){ ?>
<button type = "Submit"
onclick = "changeLabel(<?php echo $no; ?>)"
id = "btnclick<?php echo $no; ?>"
class = "btn btn-primary mt-1"
value = "<?php echo $row->table_name;?>" > <?php echo $row->table_name;?> </button>
<input type = "text"
name = "txtID"
id = "txtID<?php echo $row->table_id;?>"
value = "<?php echo $row->table_id;?>"
hidden >
<?php $no++; } ?>

<script type="text/javascript">


function changeLabel(id) {

var loanamount = document.getElementById('btnclick' + id).value;

document.getElementById('lblTableNo').innerHTML = loanamount;

};
</script>

<div class="card-header ">
<strong>Table No :</strong> <label id="lblTableNo"></label>
</div>

Ajax get dynamic id for the submit button of the form PHP MySQL

Id of elements must be unique. The abnormal behaviour of your code is due to non-unique ids of your input elements.

In the case, If you cannot assign unique ids to elements you can achieve desired output by using this keyword and siblings() method in jquery.

Instead of

var timeline_description = $("#timeline_description").val();
var pid = $("#pid").val();
var tid = $("#tid").val();

try to get values in this way.

var timeline_description = $(this).siblings('#timeline_description').val();
var pid = $(this).siblings('#pid').val();
var tid = $(this).siblings('#tid').val();

Create dynamic link id from while loop

I got it working using ajax. Just posted the id and did a lookup. Many thanks for your input.



Related Topics



Leave a reply



Submit