Getting form id, obvious solution not working. Here's an alternate approach.

pcmagas

Dimitrios Desyllas

Posted on October 2, 2024

Getting form id, obvious solution not working. Here's an alternate approach.

I had a case in which I had this form:

<form id="hello">
   <input type="hidden" name="id" />
</form>
Enter fullscreen mode Exit fullscreen mode

And i tried to retrieve its Id using javascript:

const form  = document.getElementById("#hello")
console.log(form.id)
Enter fullscreen mode Exit fullscreen mode

But this resulted returning the:

   <input type="hidden" name="id" />
Enter fullscreen mode Exit fullscreen mode

HTMLElement instead. Thus in order to mitigate this issue I used the getAttribute function instead:

const form  = document.getElementById("#hello")
console.log(form.getAttribute('id'))
Enter fullscreen mode Exit fullscreen mode

Where I used it

At first thought the example seems the issue kinda irrelevant. But in my case I was developing a utility library that a HTMLElement was received as an argument:

function formEnable(form,enable,resetFeedback=true){

    // checks whether for is an actual form are ommited for simplicity
    const formId = form.id
    const submitBtn = form.querySelector(`button[type="submit"]`)?? document.querySelector(`button[form="${formId}"][type="submit"]`) ?? document.querySelector(`button[form="${formId}"]`);

   if(!submitBtn){
        throw Error("Unable to enable or disable form")
   }
  // Form Enabling Logic
}
Enter fullscreen mode Exit fullscreen mode

In my case I used this function to place a logic for form enabling and because a hidden input with name id was as input field in my form Button failed to be retrieved.

Therefore, instead I did:

function formEnable(form,enable,resetFeedback=true){

    // checks whether for is an actual form are ommited for simplicity
    const formId = form.getAttribute('id');
    const submitBtn = form.querySelector(`button[type="submit"]`)?? document.querySelector(`button[form="${formId}"][type="submit"]`) ?? document.querySelector(`button[form="${formId}"]`);

   if(!submitBtn){
        throw Error("Unable to enable or disable form")
   }
  // Form Enabling Logic
}
Enter fullscreen mode Exit fullscreen mode

Ensuring that I received the id attribute regarding the Input and their names that exist inside my form.

πŸ’– πŸ’ͺ πŸ™… 🚩
pcmagas
Dimitrios Desyllas

Posted on October 2, 2024

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related