jQuery - Selector for duplicate ID's

前端 未结 7 1173
名媛妹妹
名媛妹妹 2020-12-02 00:40

I have a page with duplicate ID\'s for a form element. The catch is I the elements show up separately based on a toggle. So both ID\'s never show up simultaneously.

相关标签:
7条回答
  • 2020-12-02 00:45

    as Rwwl said, duplicate IDs are invalid. Assign classes instead of ids to them.

    Then you can do

    alert($('.my_element:visible').val());
    
    0 讨论(0)
  • 2020-12-02 00:45

    try :hidden

       $("#my_element").find(":hidden").val();
    

    Elements can be considered hidden for several reasons:

    They have a CSS display value of none.
    They are form elements with type="hidden".
    Their width and height are explicitly set to 0.
    An ancestor element is hidden, so the element is not shown on the page.
    

    NOTE: Elements with visibility: hidden or opacity: 0 are considered to be visible,

    0 讨论(0)
  • 2020-12-02 00:53

    Do not use same id for multiple elements, classes are better!

    0 讨论(0)
  • 2020-12-02 00:58

    The reason this is occurring is because of Duplicate IDs. IDs must be unique for the HTML to be considered valid. Whenever you aren't working against valid HTML, your results are often erratic.

    In this case, even though you are only showing one of the forms at a time, they're both still present in the mark up which is why the last one in the code is always the one that's getting run.

    Since you're using jQuery, I'd highly recommend using classes for this instead.

    0 讨论(0)
  • 2020-12-02 01:04

    Avoid duplicates ids on the page. It is not a valid HTML.

    0 讨论(0)
  • 2020-12-02 01:06

    As the myriad of other questions about this premise will tell you, you cannot use the ID selector # in this case; you have to use something like $('div[id=foo]') to find it.

    0 讨论(0)
提交回复
热议问题