$(“#myForm”).attr(“action”) returns a form element instead of undefined for forms with no actions

StackOverflow https://stackoverflow.com/questions/4166843

  •  09-10-2019
  •  | 
  •  

Pergunta

I have this basic example:

<!doctype HTML>
<html>
<head>
    <script src="jquery-1.4.2.min.js" type="text/javascript"></script>
    <script>
        $(document).ready(function(){
            $("#showAction").click(function(){
                alert($("#myForm").attr("action"));
            });
        });
    </script>
</head>
<body>
<form id="myForm">
    <input type="text" name="action" value="myAction" />
</form>
<input type="button" value="click me" id="showAction" />
</body>
</html>

When you click 'click me' you can see the tag

$("#myForm").attr("action"); 

Doesn't actually return an attribute of the element. It returns the child of the form with the name "action".

Is this expected behavior? Is this a bug in jQuery?

Foi útil?

Solução

It's a "bug" introduced by Netscape a long time ago (a boneheaded move, IMO), where form.action is a property because an element with that name is a child of the <form>. So no, it's not really a jQuery bug, but a JavaScript one, depending on your point of view...jQuery just doesn't have any additional checks for these cases.

To be safe, don't name your elements "action" or "submit", since it can mess with form.submit() as well.

Outras dicas

Very odd indeed. I am going to quietly say - bug...

Form with an action attribute: http://jsfiddle.net/vMTYY/

Form without an action attribute: http://jsfiddle.net/ZWWTm/

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top