Marin
Marin

Reputation: 45

Get dynamic Id from dynamic elements and click

I have one problem that I cannot solve, I was searching for a solution but nothing I have found fits my needs.

I have this code:

<a class="button-main" id="saveButton7" href="#" onclick="window.location.reload()">Save</a>

Where saveButton is static part and only number changes dynamically .

I need to get that id and click on it:

document.getElementById("saveButton7").click();

I have tried things like this: Get dynamic Id from dynamic elements But it does not work because I need to get whole id and click on it.

Thanks

Upvotes: 0

Views: 2861

Answers (3)

arnabkaycee
arnabkaycee

Reputation: 1644

Why dont you try jQuery selectors:

    $("[id^='saveButton']").click();

The ^ represents any attribute whose id starts with saveButton

EDIT 1

Then you could have something like this:

    var anchors = document.getElementsByTagName("a"), item;
    for (var i = 0, len = anchors.length; i < len; i++) {
      item = anchors[i];
      if (item.id && item.id.indexOf("saveButton") == 0) {
         // item.id starts with saveButton
      }
     }

EDIT 2 Have a look @ this

    <a class="button-main" id="saveButton7" href="#" onclick="onClickFunction(event);">Save</a>


    function onClickFunction(event){
           var saveButtonObject = event.target;
           //do reloading stuff here...
    }

The event object is implicitly passed by the browser here...

Upvotes: 2

Saeed M.Aghdam
Saeed M.Aghdam

Reputation: 46

Use the code below:

$('a[id^="saveButton"]').click();

It'll find "A" tag in your html page that starts with "saveButton", then call it's onClick event.

Upvotes: 1

nyumerics
nyumerics

Reputation: 6547

Considering you would like to have each such <a> element to be triggered with a keyboard event. You could do something like this in HTML5,

<a data-keybind='KEY_HERE' ..>Save</a>

Now, using jQuery:

$('#DOMelement').on('keypress',function(e){
    $("a[data-keybind='"+e.which+"']").trigger('click');
});

Such kind of event handler could be used. Essentially I am using jQuery attribute equals selector.

Upvotes: 0

Related Questions