Search code examples
javascriptjqueryjconfirm

Uncaught TypeError: Cannot read property 'find' of undefined


Good day, I'm using jconfirm to my website project but I'm facing a weird problem that I can't solve by my own, please see my code below.

$.confirm({
    title: 'Add Patient',
   theme: 'material',
    backgroundDismissAnimation: 'glow',
    type:'blue',
    typeAnimated: true,
    content: '' +
    '<form action="" class="formName" style ="margin: 10px;">' +
    '<div class="form-group">' +
    '<label>ID NUMBER</label>' +
    '<input type="text" class="id_number form-control" value="my id" required />' +
    '</div>' +
    '</form>',
    buttons: {
        formSubmit: {
            text: 'Submit',
            btnClass: 'btn-blue',
            action: function () {
            }
        },
        cancel: function () {
            //close
        },
    },
    onContentReady: function () {
        this.$content.find('.id_number').change(function(){
            var a = this.$content.find('.id_number').val();
             alert(a);
        });
    }
});

If you try to run that code it will return an error says.

Uncaught TypeError: Cannot read property 'find' of undefined

But the weird thing is if I change the code like this.

onContentReady: function () {
                var a = this.$content.find('.id_number').val();
                 alert(a);
        }

The error is gone and the alert pop-up.

My problem is how can I get the value of input inside the change() method? please help or what is the correct way to make this code works?

onContentReady: function () {
            this.$content.find('.id_number').change(function(){
                var a = this.$content.find('.id_number').val();
                 alert(a);
            });

Solution

  • The value of this is different inside the change() function, to check that you can log the value.

    As a workaround, you can keep a reference to it and use the reference.

    You can also use bind() to bind the value of this to the event handler. Or check different other ways using call() or apply.

    onContentReady: function() {
        var myReferenceToThis = this;
        this.$content.find('.id_number').change(function() {
          var a = myReferenceToThis.$content.find('.id_number').val();
          alert(a);
    });
    

    Or in your case, as @Phil suggested, simply do...

    onContentReady: function() {
        var myReferenceToThis = this;
        this.$content.find('.id_number').change(function() {
          var a = $(this).val();
          alert(a);
     });