avarus
avarus

Reputation: 37

How to use dynamically created JavaScript object in a conditional statement?

I'm having this little bump in a function, normally if the variable "receivedRDB" is undefined in the DOM, it is dynamically created in a form and if it is defined it takes the value of another variable "receivedR". But "receivedRDB" keeps being created, even when it is already defined in the DOM.

var receivedRDB = document.getElementsByName('receivedR')[0];
    if (typeof receivedRDB !== "undefined") {

        receivedR = JSON.parse(receivedRDB.value.split(",").slice(0));

    } else {

        receivedR = [];


    }
    if (typeof receivedRDB !== "undefined") { //never detected
        receivedR.push(toRemoveR);
        receivedRDB.value = JSON.stringify(receivedR).replace(/"\[\\|\\"]|\\"/g, "");
    } else { //problematic part
        event.preventDefault();
        receivedR.push(toRemoveR);
        var input = document.createElement("input");
        input.type = "hidden";
        input.name = "receivedR";
        input.value = JSON.stringify(receivedR);
        rForm.appendChild(input);
    }

Upvotes: 0

Views: 68

Answers (2)

InQβ
InQβ

Reputation: 521

I guess <script> tag which uses receivedRDB appears earlier than the DOM (in <head> for example). If so, there is more than one way to solve.

  1. <script defer>

    add an attribute defer to the <script> tag will make the JavaScript code be run after DOM is loaded

  2. window.onload = function(){ /* ... */ }

    window.onload will be called after DOM is loaded.

  3. window.addEventListener('load', function(){ /* ... */ })

    More compatible one (more than one function can be called individually)


If not the problem please include the minimal code to reproduce the problem.

Upvotes: 0

Jaromanda X
Jaromanda X

Reputation: 1

Here's a solution based on the fact that getElementsByName is a "live" list

Anywhere in your code you can put

var receivedRDB = document.getElementsByName('receivedR');

then change your code to

if (receivedRDB.length !== 0) {
    receivedR.push(toRemoveR);
    receivedRDB[0].value = JSON.stringify(receivedR).replace(/"\[\\|\\"]|\\"/g, "");
} else {
    event.preventDefault();
    receivedR.push(toRemoveR);
    var input = document.createElement("input");
    input.type = "hidden";
    input.name = "receivedR";
    input.value = JSON.stringify(receivedR);
    rForm.appendChild(input);
}

Upvotes: 2

Related Questions