0

I have a problem with my JavaScript code.

I want to check if a variable with dynamic name exist, but I don't know how to do it. I tried to do something, but it doesn't work

If someone could help me, I would be very grateful. Thx, Alessio

function addElement(id_sub, id_v){
    var n_id_sub = document.getElementById('sub'+id_sub).value;
    var name = "tot" + id_sub;
    checkName(name);
    var n_prod = document.getElementById('number'+id_v).value;
    if(n_prod>=2){
        alert(n_prod)
    }else{
        var inputField=document.getElementById('number'+id_v);
        inputField.value=parseInt(n_prod)+1;
        
    }
}

function checkName(n){
    if(typeof window['name'] === 'undefined'){
        var window['name'] = 0;
    } 
}

EDIT: Sorry, I didn't make myself clear, I'm currently studying to improve my English. I want to create a js file that retrieve a value from an HTML form. I need to check if there is a variable that has the retrieved value as its name.

Spanu18
  • 1
  • 2
  • 1
    noedjs doesn't have `window` - also using `window['name']` is the same as `window.name` which isn't dynamic, you perhaps meant `window[n]` ... note, no `'` ... and you can't declare a var like that, it'd be `window[n]=0` – Jaromanda X Sep 19 '22 at 09:36
  • @JaromandaX nor `document.getElementById()`. Is this really code that runs in Node.JS? – VLAZ Sep 19 '22 at 09:37
  • @VLAZ - didn't even look at that!!! `node.js` must be one of those spam tags :p – Jaromanda X Sep 19 '22 at 09:38
  • 1
    to be perfectly honest, I think if you fixed your code to pollute the global object like that, it would be very poor design - globals are virtually unnecessary with correct code – Jaromanda X Sep 19 '22 at 09:40
  • Also, what is meant by "variable" here? How and why do you create variable with dynamic names? Do you mean *elements*? Or something else? If it's actual variables, then I see no reason for actual variables to be used. See ["Variable" variables in JavaScript](https://stackoverflow.com/q/5187530) - it's easier to use an object where you check the property names.Although, even that is probably not needed, depending on what you're trying to do . If you mean something else, then clarify. – VLAZ Sep 19 '22 at 09:41
  • Also when run in the client `window['name'] = 0;` should be declared without the var keyword since the window object is an excisting object. You also have to pick a different name to your variable since `name` is part of the window object already. – Mark Baijens Sep 19 '22 at 09:42
  • I edited the question. I hope it is clearer now! Thx for your help – Spanu18 Sep 19 '22 at 11:03

0 Answers0