How to use Javascript in Chronoforms

How to add interactive JavaScript to a ChronoForms checkbox.

Overview

The issue occurs when JavaScript code added directly to custom fields fails to execute because it runs before the page elements are fully loaded.
Use a Load JavaScript action in the On Load event with jQuery code wrapped in a document.ready function to ensure it runs after the page loads, and verify the element IDs in the code match those in your form.

Answered
ChronoForms v5
ap apo24 08 May, 2017
Hi,

I was wondering how do I add this example of javascript: http://jsfiddle.net/Jb7yM/97/ to a checkbox in chronoforms.
I use a custom field in the designer for the HTML.
Added the JS code and the CSS to their individiual tabs at setup. When I try to load the page, the JS doesn't seem to work.
What am I doing wrong here?

Basically I would like to achieve the following:

How to use Javascript in Chronoforms image 1
How to use Javascript in Chronoforms image 2

When the checkbox is checked I would like to display a new price and replace the old picture.

Hopefully you can help me out! Thank you!
Gr GreyHead 08 May, 2017
Hi apo23,

Please try adding the JavaScript to a Load JavaScript action in the On Load event in the form Setup tab.

Bob
ap apo24 08 May, 2017
Hi Bob,

I tried that but it didn't work unfortunatly.

document.getElementById("MyCheckbox").onclick=function() {
    if(this.checked) {
        document.getElementById("MyImage").className = "markedImg";
    } else {
        document.getElementById("MyImage").className = "unMarkedImg";   
    }
}


added to the load javascript action in the on load.

<div id="MyImage" class="unMarkedImg">img</div><br />
<input type="checkbox" id="MyCheckbox" />


added to the custom field.

#MyImage {
    height: 50px;
    width: 50px;
    border: 1px solid black;
}
.markedImg {
    background-color: blue;
}
.unMarkedImg {
    background-color: red;
}


added to the load css on load.

Apo24
Gr GreyHead 08 May, 2017
Answer
Hi Apo24,

Maybe the problem with that is that it needs to be deferred until the page loads?

This jQuery version appears to work OK
jQuery(document).ready(function(jQ) {
  jQ('#MyCheckbox').on('click', changeClass);

  function changeClass() {
    if ( this.checked ) {
      jQ('#MyImage').removeClass('unMarkedImg').addClass('markedImg');
    } else {
      jQ('#MyImage').removeClass('markedImg').addClass('unMarkedImg');
    }
  }
});

Bob
ap apo24 08 May, 2017
Thank you so much Bob! That did the trick!
ap apo24 09 May, 2017
Final question. If I wanted to use this code not in a custom code but with a checkbox. How would I do that?

Thanks in advance!
Gr GreyHead 09 May, 2017
Hi apo24,

Same code will work - just make sure that the ID for the checkbox is matched up.

Bob
This topic is locked and no more replies can be posted.