简体   繁体   中英

HTTP input to javascript variable remains undefined

Okay, so I'm fairly new to javascript and I'm working on the front-end of a webapplication for my internship, and this just utterly baffles me.

I have a select and an input element, both of which feed into a message model for a database Procedure Call through .POST(). I've done this in other scripts in the project, but here it won't work no matter how I try to assign the values.

Here's the code:

var cctOldSelect = document.getElementById("ConceptToCopy");
var cctOld = cctOldSelect.options[cctOldSelect.selectedIndex].value;
var cctNew = document.getElementById('NewConceptName').value;
console.log("cctOld: " + cctOld + "; cctNew: " + cctNew);
if (cctOld !== "" && cctNew !== "") {
    console.log("model creation started.");
    var model = {
        p_cct_code_old: cctOldSelect.options[cctOldSelect.selectedIndex].value,
        p_cct_code_new: document.getElementById('NewConceptName').value,
        p_specialty_layout: null
    };
    console.log("model creation ended.");
}
console.log("cctOld model: " + model.cctOld + "; cctNew model: " + model.cctNew);

output:

cctOld: 1020H; cctNew: 1021H
model creation started.
model creation ended.
cctOld model: undefined; cctNew model: undefined

I've tried multiple ways:

p_cct_code_Old: $scope.<ElementID>  //both with and without .value
p_cct_code_Old: document.getElementById(<ElementID>)    
var cctOld = document.getElementById(<ElementID>); p_cctOld: cctOld

None of which work. Why won't it assign a value?

The problem in this case is that you create a new object called "model" and with two attributes called "p_cct_code_old" and "p_cct_code_new", then you are trying to access two attributes called "cctOld" and "cctNew" out of scope .

The JS interpreter when you are trying to access a non existing attributes do not throw an error, instead he return an undefined value.

The thing that I suggest to make the things work is:

var model = {};
var cctOldSelect = document.getElementById("ConceptToCopy");
var cctOld = cctOldSelect.options[cctOldSelect.selectedIndex].value;
var cctNew = document.getElementById('NewConceptName').value;
console.log("cctOld: " + cctOld + "; cctNew: " + cctNew);
if (cctOld !== "" && cctNew !== "") {
    console.log("model creation started.");
    model.p_cct_code_old = cctOldSelect.options[cctOldSelect.selectedIndex].value;
    model.p_cct_code_new = document.getElementById('NewConceptName').value;
    model.p_specialty_layout: null;
    console.log("model creation ended.");
}
console.log("cctOld model: " + model.p_cct_code_old + "; cctNew model: " + model.p_cct_code_new);

Tell me if this solution helped you !

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM