3

when I've an input with name="id" within a form, the prop('id') method returns the input element instead of the id as string:

HTML

<form id="testform">
    <input name="id">
</form>

JS

var $form = $('#testform');

var wrongId = $form.prop('id');
var correctId = $form.attr('id');

alert(wrongId); // alerts the html input element
alert(correctId); // alerts the id testform

Can anyone explain this to me?

I've prepared a fiddle: https://jsfiddle.net/zosu17se/

thanks and best

ducci
  • 351
  • 1
  • 4
  • 15

1 Answers1

5

This is because you've named the input id, and a name or ID of inputs, selects and other "form elements" are attached to the parent form as properties of the form for easier access, so form.id is the input, not the elements id.

Do not name the input id or any other property you might want to access, and the problem is solved.

Example of strange code caused by this

var form = window.test; // note that element ID's are also attached to the global scope

form.id.value = 'test';
form.value.value = 'test more';
form.selectedIndex.value = '2';
<form id="test">
  <input name="id">
  <input name="value">
  
  <select id="selectedIndex">
    <option value="1">1</option>
    <option value="2">2</option>
    <option value="3">3</option>
  </select>
</form>
adeneo
  • 312,895
  • 29
  • 395
  • 388