Home > other >  Returning "ReferenceError: variable is undefined"
Returning "ReferenceError: variable is undefined"

Time:02-01

I'm working through some practice work. I'm trying to create a modal pop-up window when the table row is clicked and bringing up the relevant information for the clicked on state.

the JSON is returning this:

"data": [
    {
        "ID State": "04000US01",
        "State": "Alabama",
        "ID Year": 2019,
        "Year": "2019",
        "Population": 4903185,
        "Slug State": "alabama"
    }
]

and I'm trying to pull the Slug State line to use for another API using it in the call.

function BuildStatesByPopulation(data) {
    if (stateTable != null) {
        for (var i = 0; i < data.length; i  ) {
            let addRow = `<tr id="stateData" class='clickable-row' onClick=SelectStateOpenModal(${data[i]["Slug State"]})>
                          <td>${data[i].State}</td>
                          <td>${data[i].Population}</td>
                          </tr>`
            stateTable.innerHTML  = addRow;
            //console.log(data[i]["Slug State"]);
        }
    }
}
function SelectStateOpenModal(stateName) {
    let setState = String(stateName);
    let stateDisplay;
    let stateJson
    console.log(stateName);
    $.ajax({
        type: 'GET',
        url: stateInformation setState,
        success: function (response) {
            stateJson = response.data;
            stateDisplay = document.getElementById('modalView');
            console.log(stateJson);
        }
    });
}

When the table's row is clicked on the console is returning:

index2.html:71 Uncaught ReferenceError: nebraska is not defined at HTMLTableRowElement.onclick (index2.html:71:87)

CodePudding user response:

Here is a suggestion which uses dataset to pass the Slug State to an event handler.

function BuildStatesByPopulation(data) {
  if (stateTable != null) {
  
    data.forEach(d => {
    
      // Create a row element
      let tr = document.createElement("tr");
      tr.classList.add("clickable-row");
      tr.dataset.slug = d["Slug State"];
      
      // Set an event listener
      tr.addEventListener("click", SelectStateOpenModal);
      
      // Create the two tds
      let td1 = document.createElement("td");
      td1.innerText = d.State;
      
      let td2 = document.createElement("td");
      td1.innerText = d.Population;
      
      // Appends everything
      tr.append(td1);
      tr.append(td2);
      stateTable.append(tr);
    })
  }
}

// In the event handler, get the Slug State from this.dataset
function SelectStateOpenModal() {
  let setState = this.dataset.slug;
  // ...
}
  •  Tags:  
  • Related