oTree Forum >

How to ignore "Uncaught TypeError: Cannot set properties of null" in javascript

#1 by felmola

Hi all.

Perhaps you know how to ignore "Uncaught TypeError: Cannot set properties of null" in javascript. Note that my knowledge of javascript is close to Null.

I have pairs of radio formfields where some of their options are mutually exclusive. (i.e. if I want to permanently delete a link to player2 in formfield 2, in formfield 1 I cannot attempt to link to player 2. So the code below forces the choices between the formfields to be consistent.

    document.getElementById('id_link_severed_to_p1-1').onclick = function() {
        forminputs.link_to_p1.value = 0;
    document.getElementById('id_link_to_p1-1').onclick = function() {
        forminputs.link_severed_to_p1.value = 0;
The list of formfields to apply this rule to is different across players and rounds. So an easy fix was to copy and paste the same code for all the possible pairs of formfields. Of course, the code calls formfields that are not loaded in the template. Is there an easy way to skip this error and let the script work only on those formfields that are actually there?

I've read something related to JsonIgnore() or using a conditional with null. But I don't even know where to check for nullness.

Any hint is really helpful.

#2 by felmola

The fix was really easy.
When you call an element that does not exists it returns "null". So, just get the code you want to run inside a conditional that first checks for the existence of the element. If the element exists (i.e. !== null), run the code. If not, then do nothing.

    if((document.getElementById('id_link_to_p2-1') !== null) && (document.getElementById('id_link_severed_to_p2-1') !== null)){

    document.getElementById('id_link_severed_to_p2-1').onclick = function() {
        forminputs.link_to_p2.value = 0;
    document.getElementById('id_link_to_p2-1').onclick = function() {
        forminputs.link_severed_to_p2.value = 0;

Write a reply

Set forum username