Search code examples
javascriptjquerygetelementsbytagname

Generate automatically variable and get values usign "document.getElementsByClassName"


I'm java script beginner, so do not be angry against me ;)

In order to simplify my code, I would like to generate automatically variables and affect them their current value in order to use them further.

What I have done and works (but I have a lot of changing variable on various documents) :

Html : input a,b,c,... with id a,b,c,...

a = Number($('#a').val());
b = Number($('#a').val());  
c = Number($('#c').val());
...

What I'm trying to do :

Html : add a class 'test' to all inputs I want to generate

var elements = document.getElementsByClassName('test');
elementsLength = elements.length;  
for (var i = 0 ; i < elementsLength ; i++) {
elements[i].value = Number($("#"+elements[i].id).val());
}

Something must be wrong in the part elements[i].value = Number($("#"+elements[i].id).val());

because when I call the variable a, b or c, it has not been generated. after the loop,

alert (a);

returns [object HTMLInputElement] instead of the value I would like to get ;(

I'm searching since yesterday, I'm loose. Thank you for your support guys. ++


Solution

  • Seems you want to persist the value of INPUTS in variable. I would suggest you to create an object i.e. obj and create properties based on input.

    var obj = {};
    $('button').on('click', function() {
      $('.test').each(function() {
        obj[$(this).prop('id')] = Number($(this).val());
      });
      
      //For debugging
      console.clear();
      console.log(obj);
    });
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <input type="text" id="a" class="test">
    <input type="text" id="b" class="test">
    <input type="text" id="c" class="test">
    
    <button type="button">Click me</button>