Noble Polygon
Noble Polygon

Reputation: 806

jquery disable button until first button is clicked

I have a project in JQuery that requires a user to click a button to download a PDF before proceeding to the next screen. I've tried writing a conditional statement that would perform this action:

downloadPDF.js

function getPdf () {
  $('.button-rounded').click(function () {
    (pdf.fromHTML($('.message-container').html(), 30, 30, {
      'width': 400,
      'elementHandlers': specialElementHandlers
    }));
    pdf.save('example.pdf');
  });
}

// continue new plan

function getPlan () {
  $('.button-rounded-negative').click(function () {
    var url = "http://www.example.com";
    window.open(url);
  })
}

if ($(getPdf).onClick(false)) {
  $(getPlan).attr('disabled', true)
}else{
  if ($(getPdf).onClick(true)) {
    $(getPlan).attr('disabled', false)
  }
}

The goal is to disable the getPlan button until the getPDF button is clicked which starts an automatic download of the file.

Unfortunately, I haven't got it to work yet. If I use ($(getPdf).click(false)) & the displayed code, both button are still enabled. If I use .onClick both buttons are then disabled.

How do I handle this event? Up until this point, I've mostly written apps/conditional statements in React so I'm not quite understanding where I am going wrong in my conditional statement logic.

Upvotes: 1

Views: 125

Answers (1)

Rory McCrossan
Rory McCrossan

Reputation: 337610

This isn't how Javascript works. You cannot put event handlers in if statements. You should also not nest your event handlers (as I assume getPdf() and getPlan() are called from onclick attributes).

Instead you need to enable the second button in the DOM within the click handler for the first button. Try this:

jQuery(function($) {
  $('.button-rounded').click(function () {
    pdf.fromHTML($('.message-container').html(), 30, 30, {
      'width': 400,
      'elementHandlers': specialElementHandlers
    });
    pdf.save('example.pdf');
  });

  $('.button-rounded-negative').click(function () {
    var url = "http://www.example.com";
    window.open(url);
    $('button-rounded').prop('enabled', true); // enable the button here, 
                                               // assuming it starts in a disabled state
  });
});

Note that you should remove the implied onclick attributes from your HTML and only use the above JS.

Upvotes: 2

Related Questions