Petru Lebada Petru Lebada - 6 months ago 17
jQuery Question

Run function on multiple events

I need to run a function on two cases.One when the page was loaded , and one each time the element was clicked.The click event works,but the onload one doesn't.

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

var captcha;

$('#captcha').on('ready click',function(){
function alphanumeric_unique() {
return Math.random().toString(36).split('').filter( function(value, index, self) {
return self.indexOf(value) === index;
}).join('').substr(2,8);
}

captcha = alphanumeric_unique();

$(this).val(captcha);
});
});


<input type="text" readonly value="" id="captcha">


Any help please?

Answer

You need to trigger click event on page load:

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

  $('#captcha').on('click',function(){
        function alphanumeric_unique() {
            return Math.random().toString(36).split('').filter( function(value, index, self) { 
                return self.indexOf(value) === index;
            }).join('').substr(2,8);
        }

        captcha = alphanumeric_unique();

        $(this).val(captcha);
    });

    $('#captcha').trigger("click"); // it will automatically call click event


});
Comments