0

I need to simulate a click, and send the value of an element. This is because the item I need to click exists several times on the page with the same ID, but I only want trigger the behavior of one.

The element looks like this

<input type="submit" value="Login" class="um-button" id="um-submit-btn"> 

My code so far is

$("#user_password-36").on('keyup', function (e) {
    if (e.keyCode == 13) {
        $("#um-submit-btn").click();
    }
});

But I think I need to be able to send the value, which is 'Login'. Otherwise it triggers the wrong submit button.

I appreciate this is not a good solution, but I need to make this work without modifying the existing code that runs the login system.

DjaouadNM
  • 22,013
  • 4
  • 33
  • 55
seventeen
  • 557
  • 1
  • 6
  • 21
  • 4
    IDs must be unique. Else you are violating web standards. Read this: https://stackoverflow.com/questions/5611963/can-multiple-different-html-elements-have-the-same-id-if-theyre-different-eleme – zomega Aug 03 '19 at 09:16
  • Possible duplicate of [Can multiple different HTML elements have the same ID if they're different elements?](https://stackoverflow.com/questions/5611963/can-multiple-different-html-elements-have-the-same-id-if-theyre-different-eleme) – VLAZ Aug 03 '19 at 09:19
  • you can use additional classes rather than using duplicate ids. – Udo E. Aug 03 '19 at 09:22

3 Answers3

2

Even though it's a bad idea to have multiple elements with the same id (your case is a problem that comes with such usage), you can select it by specifying the value as well as the id:

$("#um-submit-btn[value='Login']").click();
DjaouadNM
  • 22,013
  • 4
  • 33
  • 55
1

Using this method, you can add the keyup handler to multiple elements instead of just one for a button with a given value. However, You must use a class for the element you need to attach this handler to. You may also use classes for other duplicate elements as well.

If somehow the element with class user_password-36 shares the same parent as this button:

<div>
    <input class='user_password-36' />
    <input id='um-submit-btn' />
</div>

you can use this

$(".user_password-36").on('keyup', function (e) { 
    if (e.keyCode == 13) { 
        $(this).parent().find("#um-submit-btn").click(); 
    } 
});

Also, if somehow they share same parent but are nested in any way:

<div id='parentId'>
    <div>
        <input class='user_password-36' />
    </div>
    <div>
        <div>
            <input id='um-submit-btn' />
        </div>
    </div>
</div>

then supply the id (or class) of their common parent

$(".user_password-36").on('keyup', function (e) { 
    if (e.keyCode == 13) { 
        $(this).parents('#parentId').find("#um-submit-btn").click(); 
    } 
});
Udo E.
  • 2,665
  • 2
  • 21
  • 33
0

You can also trigger the click event by using trigger()

$("#um-submit-btn[value='Login']").trigger( "click" );
dhamo dharan
  • 712
  • 1
  • 10
  • 25