Search code examples
javascriptjquerytriggerscorrelationprefix

Trigger by suffix from same element class


I want make every button which have suffix class -dummy (let's call it "dummy") to trigger another button who have same class but without that suffix (call it "real button").

<button class="btn-submit hidden"> triggered by <button class="btn-submit-dummy">

<button class="btn-edit hidden"> triggered by <button class="btn-edit-dummy">

<button class="btn-delete"> triggered by nothing since there is no element with class btn-delete-dummy

Each real button need to be triggered by click on the dummy.

My script so far :

/** If I define manually on each button **/
$(".btn-submit-dummy").click(function() {
    $(".btn-submit").trigger("click");
});
$(".btn-edit-dummy").click(function() {
    $(".btn-edit").trigger("click");
});
...
...
...
/** end of defining button **/

My idea if written in jQuery and human language (sorry for this ugly way) as the following :

$("button[class$='-dummy']").click(function() {
    var realButton = button_which_have_same_class_as_clicked_object_but_trimmed_with_"-dummy";
    if(find realButton) {
        $(realButton).trigger("click");
    }
});

Please help. Thanks a lot.


Solution

  • Try This:

    $("[class$='-dummy']").on('click', function () {
        var btnClass = $(this).attr('class').match(/([\w-]+-dummy)+/)[0].replace('-dummy', '');
    
        alert(btnClass);
        $("." + btnClass).trigger("click");
    });
    

    Demo: https://jsfiddle.net/tusharj/gc3d5yy5/

    Hope this helps