Search code examples
javascriptjquerytriggersclickdocument-ready

how to fire click event on document ready...?


Radio Button

<input name="radio-choice-t-6" class="qololbl" id="radio-choice-t-6a" value="qolo" checked="checked" type="radio">
<label for="radio-choice-t-6a" style="border: 1px solid #2d5f7c;width:90px;border-bottom-left-radius:4px;border-top-left-radius:4px;font-family:Noto Sans;">Toast</label>

$(document).ready(function (e) {

    $('.qololbl').trigger('click'); 

    $(".qololbl").click(function(){
        alert("Hi");
     });
});

how to fire qololbl click event on document ready. this code is not working why..? thanks in advance. help me


Solution

  • Use .click() instead of .trigger(). And put it after event hanlder declaration.

    $(document).ready(function (e) {
    
        $(".qololbl").click(function(){
            alert("Hi");
         });
         
         $('.qololbl').click();
    });
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <input name="radio-choice-t-6" class="qololbl" id="radio-choice-t-6a" value="qolo" checked="checked" type="radio">
    <label for="radio-choice-t-6a" style="border: 1px solid #2d5f7c;width:90px;border-bottom-left-radius:4px;border-top-left-radius:4px;font-family:Noto Sans;">Toast</label>

    Alternative (Suggested by pratik-gaikwad)

    $(document).ready(function (e) {
    
        $(".qololbl").on('click', function(){
            alert("Hi");
         });
         
         $('.qololbl').trigger('click');
    });
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <input name="radio-choice-t-6" class="qololbl" id="radio-choice-t-6a" value="qolo" checked="checked" type="radio">
    <label for="radio-choice-t-6a" style="border: 1px solid #2d5f7c;width:90px;border-bottom-left-radius:4px;border-top-left-radius:4px;font-family:Noto Sans;">Toast</label>