"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > Getting form id. It is not what you think

Getting form id. It is not what you think

Published on 2024-11-08
Browse:840

Getting form id. It is not what you think

I had a case in which I had this form:

And i tried to retrieve its Id using javascript:

const form  = document.getElementById("#hello")
console.log(form.id)

But this resulted returning the:

   

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'))

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
}

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
}

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

Release Statement This article is reproduced at: https://dev.to/pcmagas/getting-form-id-it-is-not-what-you-think-4ac?1 If there is any infringement, please contact [email protected] to delete it
Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3