Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get form name via JavaScript

Tags:

javascript

I have simple question but I can't fined good solution on the web.

I have this HTML code:

 <form name="Register" action="Register.aspx" method="post" runat="server" style="margin-top: 15px;" onsubmit="return validateProfile(this);" >

And this JavaScript code

function validateProfile(F) {
var G = F.name; 
}

I want somehow to get the form name, but this code just does not working.

wish for help, thanks!

like image 981
Nave Tseva Avatar asked Oct 19 '25 13:10

Nave Tseva


2 Answers

There you go

function validateProfile(F) {
    alert(F.name); 
    return false;
}

F is already the form, no need to use .Form .

Since a form is an element, you can access its name using .name.

This is defined in the DOM specification here :

name of type DOMString

Names the form.

Demo

Notice how my JSFiddle contains window.validateProfile = validateProfile because I run it after the DOM is ready, if your function is not directly in a script block, chances are you need to do this too.

like image 134
Benjamin Gruenbaum Avatar answered Oct 22 '25 01:10

Benjamin Gruenbaum


You likely have a control in the form with a name of name. Form controls are made available as properties of the form, using their name or ID as the property name. So in:

<form name="foo" ...>
  <input name="name" ...>

then:

document.forms['foo'].name

returns a reference to the input element, not the value of the form's name property (which reflects the value of the HTML name attribute).

The solution is to not use attribute values for form controls that are the same as standard form element attribute or DOM property names (e.g. do not name form controls "submit" or "reset" as they will overwrite the form's submit and reset methods).

like image 41
RobG Avatar answered Oct 22 '25 01:10

RobG



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!