Howdy, Stranger!

It looks like you're new here. If you want to get involved, click one of these buttons!

Categories

How can I access a dynamically generated element ID after document ready?

Adébáyò ÒjóAdébáyò Òjó Member Posts: 1

I echoed the table below in my PHP script where I can edit and save the firstname and lastname fields for each user. When I click on edit, I could modify the field and save the change successfully. The issue I have now is that I want to disable the save button if the input text field is empty. I don't want user to save an empty field. Right now, once the page is fully loaded(document.ready), the ID I'm referencing(txtnameid) in my Jquery is not created yet, since they are created dynamically when a user click on the edit button. So my jquery is not working. How can I make this work please?

PHP

echo "<table>"; echo "<tr>"; echo "<td>"; ?>Firstname: <?php echo "</td>"; echo "<td>"; ?><div id="name<?php echo $firstname; ?>"><?php echo $firstname; ?> </div> <?php echo "</td>"; echo "<td>"; ?><input type="button" id="<?php echo $firstname; ?>" name="<?php echo $firstname; ?>" value="Edit" onclick="edit(this.id)"><?php echo "</td>"; echo "<td>"; ?> <input type="button" id="save<?php echo $firstname; ?>" name="<?php echo $firstname; ?>" value="Save" style="visibility:hidden" onclick="save(this.name)"><?php echo "</td>"; echo "</tr>"; echo "<tr>"; echo "<td>"; ?>Lastname: <?php echo "</td>"; echo "<td>"; ?><div id="name<?php echo $lastname; ?>"><?php echo $lastname; ?> </div> <?php echo "</td>"; echo "<td>"; ?><input type="button" id="<?php echo $lastname; ?>" name="<?php echo $lastname; ?>" value="Edit" onclick="edit(this.id)"><?php echo "</td>"; echo "<td>"; ?> <input type="button" id="save<?php echo $lastname; ?>" name="<?php echo $lastname; ?>" value="Save" style="visibility:hidden" onclick="save(this.name)"><?php echo "</td>"; echo "</tr>"; echo "</table>";

JavaScript

`function edit(id) {
nameid = "name" + id;
txtnameid = "txtname" + id;
var name = document.getElementById(nameid).innerHTML;
document.getElementById(nameid).innerHTML = "";

updateid = "save" + id;
document.getElementById(id).style.visibility = "hidden";
document.getElementById(updateid).style.visibility = "visible";
}`

Jquery

$(document).ready(function() { $("#nameid").on("blur", "txtnameid", function() { if( $('#txtnameid').val().length === 0 ) { $("#saveid").prop('disabled', true); } }); });

Sign In or Register to comment.