to set a var for a form object. However I would like the form id to be dynamic based on a PHP variable so I can use the same form for multiple purposes. I.e.
PHP:
Is your JS in an external file?
What does the code look like when you View Source (or inspect it in the browser’s dev tools)? That will show you what the browser received after PHP was done with it.
I tried what you wanted to do “modify id of the form to use it for different purposes.”
Click run and then click on Change id button. Later change at code side setAttr…(‘id’, ‘…blablabla…’); Then click RUN then Change id button again that will not show any message.
<!DOCTYPE html>
<html>
<head>
<script>
function changeName() {
document.getElementById("myForm").setAttribute("id", "myForm");
alert(document.forms["myForm"].getAttribute('id'));
}
</script>
</head>
<body>
<form id="myForm" action="/action_page.php" method="get">
First name: <input type="text" id="fname"><br>
Last name: <input type="text" id="lname"><br><br>
<input type="button" onclick="changeName()" value="Send form data!">
</form>
<p>default name is myForm it becomes unusable if you change it to differentForm</p>
</body>
</html>
If I change in this code form id to something else it becomes unusable. I think name should be what it is at page load, modification is not allowed. Still, you can set all id data with php at page load once.