seventeen
seventeen

Reputation: 443

JavaScript: Simulate a click with a value

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.

Upvotes: 0

Views: 326

Answers (3)

Udochukwu Enwerem
Udochukwu Enwerem

Reputation: 2823

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

Upvotes: 1

dhamo dharan
dhamo dharan

Reputation: 762

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

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

Upvotes: 0

Djaouad
Djaouad

Reputation: 22766

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

Upvotes: 2

Related Questions