Home > Web Front-end > JS Tutorial > Getting form id. It is not what you think

Getting form id. It is not what you think

Susan Sarandon
Release: 2024-10-02 18:18:29
Original
554 people have browsed it

Getting form id. It is not what you think

I had a case in which I had this form:

<form id="hello">
   <input type="hidden" name="id" />
</form>
Copy after login

And i tried to retrieve its Id using javascript:

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

But this resulted returning the:

   <input type="hidden" name="id" />
Copy after login

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'))
Copy after login

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
}
Copy after login

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
}
Copy after login

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

The above is the detailed content of Getting form id. It is not what you think. For more information, please follow other related articles on the PHP Chinese website!

source:dev.to
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template