0

Imagine that I had a form where I wanted to have a "rent date" and a "return date".

I want to use the calendar to make a pick.

However, my code is not working. I think it has something to do with both of them having same id but i do not want to rewrite a whole load of new CSS for each one that I need to use (around 4 currently).

<script type=”text/javascript”>
    jQuery(document).ready(function(){
        $( "#datepicker" ).datepicker();
                $( "#datepicker" ).datepicker2();
    });
</script> 

<div class="demo">
  <p>Date: <input id="datepicker" class="datepicker" type="text"></p>
</div>         <!-- End demo -->

<div class="demo">
  <p>Date: <input id="datepicker" class="datepicker" type="text"></p>
</div>         <!-- End demo -->
Arjan
  • 22,808
  • 11
  • 61
  • 71
matthew moore
  • 215
  • 4
  • 19
  • Can someone show me the completed code. i changed the ids and applied the code but still not working. – matthew moore Mar 11 '11 at 18:56
  • You still have multiple elements with `id="datepicker"`. – Matt Ball Mar 11 '11 at 18:58
  • Okay i updated code wwith what i put in. – matthew moore Mar 11 '11 at 19:13
  • You're still using the **wrong selector.** Use `$('.datepicker')` (the class selector) rather than `$('#datepicker')` (the ID selector). You're also calling `$('#datepicker').datepicker()` **four times**. You only need to call it **once.** Wake up, dude! – Matt Ball Mar 11 '11 at 19:33
  • odd are you pulling cache cause i updated that all and still do not work – matthew moore Mar 11 '11 at 19:53
  • I did a hard refresh but the page still has the wrong code. It did just change, however, but it's ***still*** running the initializer code multiple times (don't do that), and using the ID selector rather than the class selector. – Matt Ball Mar 11 '11 at 19:57

4 Answers4

6

HTML element IDs must be unique.

Use the class instead.

$( ".datepicker" ).datepicker();

If a document contains multiple elements with the same ID, you will be eaten by velociraptors the Great Cthulhu will be summoned and consume the world bad things will happen (as you've seen! :).

Community
  • 1
  • 1
Matt Ball
  • 354,903
  • 100
  • 647
  • 710
2

If you have several elements with the same id then the selector will return only the first one.

What you should do is use the class selector to assign the datepicker.

I think this could work:

$(".datapicker").datepicker();
willvv
  • 8,439
  • 16
  • 66
  • 101
2

You will have more problems with any javascript if you assign the same ID to multiple items on the page. You need to fixt that first.

An ID should be unique, otherwise you're going to have all kinds of things go wrong with the DOM which javascript/jquery use.

polyhedron
  • 1,560
  • 4
  • 19
  • 26
2

No matter the way you see it, the ID's have to be unique

Carlos Valenzuela
  • 816
  • 1
  • 7
  • 19