General developer forum

Bind event to checkbox

Picture of Anthony Nguyen
Bind event to checkbox

Hi, I am facing a problem. In my form there are a checkbox and a textbox. 

$mform->addElement('checkbox', 'is_premium', get_string('is_premium', 'admin'));
$mform->setType('is_premium', PARAM_INT);
$mform->setDefault('is_premium', $pageData->isPremiumCourse);

$custom_attributes = array();
if($pageData->isPremium == 0)
$custom_attributes['disabled'] = "disabled";

//add textbox
$mform->addElement('text', 'coursePrice', get_string('course_price', 'admin'), $custom_attributes);

What I need is if the checkbox is unchecked then the textbox should disabled. If the checkbox is checked then the textbox should be enabled. 

I am thinking of 2 options:

- Bind a javascipt/jquery function to detect the status of the checkbox

- Reload the page when the checkbox is either checked or unchecked, so the status of the textbox should be updated accordingly.

But I'm not sure which one is best or if there is any other better option. Can anyone please tell me how to bind an event into a checkbox element? Thanks.

Average of ratings: -
Picture of Rahul Rai
Re: Bind event to checkbox
Hi Anthony 

I think you need to use javascipt/jquery function to detect the status. 

That is the best option. 

Average of ratings: -
Re: Bind event to checkbox
Group Core developersGroup Particularly helpful MoodlersGroup Plugin developers

Use the standard Moodle disabledIf functionality.

I don't have code in front of me, but it should look something like:

$mform->disabledIf('coursePrice', 'is_premium', 'notchecked');

(I suggest you search for examples in the code and copy what they do).

Average of ratings: -