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.

3

3 Answers 3

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();
Sign up to request clarification or add additional context in comments.

Comments

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(); 
    } 
});

Comments

0

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

$("#um-submit-btn[value='Login']").trigger( "click" );

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.