4

I'm have some problems to add attributes to these input fields using jQuery:

<input id='timetable_start'>
<input id='timetable_finish'>

<script>
attributes = {
    "class": "reloj",
    "maxlength": "5",
    "pattern": "^([0-9]|0[0-9]|1[0-9]|2[0-3]):[0-5][0-9]$",
    "size": "6",
    "type": "text"
};

$('#timetable_finish').attr(attributes);
$('#timetable_start').attr(attributes);
</script>

Why only one is changed? What I'm missing? Thanks in advance for you time
Link: http://jsbin.com/iqipan/4/edit

chespinoza
  • 2,552
  • 20
  • 43

3 Answers3

6

Because the code throws an error when you are trying to set the attributes for the first input field:

Uncaught Error: type property can't be changed.

Remove type from the object and everything will be fine.


Some browsers (I guess IE) don't allow to change the type of an input element after it was created, so jQuery throws an exception if you are trying to do that. See change type of input field with jQuery.

Community
  • 1
  • 1
Felix Kling
  • 705,106
  • 160
  • 1,004
  • 1,072
3

Use

$("#timetable_finish, #timetable_start").attr(attributes);

However, you can't change the type property of inputs. You would have to create a new input instead:

$("#timetable_finish").replaceWith($("<input>", attributes));
Explosion Pills
  • 176,581
  • 46
  • 285
  • 363
3

This is because the attribute type is read-only - whereas the DOM property type is not.

You can use:

$('#timetable_finish').prop(attributes);
$('#timetable_start').prop(attributes);

to successfully change both.

techfoobar
  • 61,046
  • 13
  • 104
  • 127