Home > Net >  Assign dynamic value to an Input Field in HTML
Assign dynamic value to an Input Field in HTML

Time:10-05

I have an input field and I want to assign it a value dynamically fetched from DB. I will use that value later in a script. Here is my code below

<div data-ng-model="DashboardCounterItems">
<div data-ng-repeat="cItem in DashboardCounterItems">
<input type ="hidden" id ="myInput" value = {{cItem.dbMeetings.length}} />
</div>
</div>

Here {{cItem.dbMeetings.length}} is fetched from DB and assigned to myInput. Further when I check the value of this input in alert in script below, I get {{cItem.dbMeetings.length}} message instead of the value within it.

<script>
var iLenthv = document.getElementById("myInput").value;
alert(iLenthv);
</script>

Any help how can I do it. Or any other better way. I will really appreciate it.

CodePudding user response:

Use .getAttribute() to get the value from a html attribute

function myFunction() {
var iLenthv = document.getElementById("myInput").getAttribute("value"); 
alert(iLenthv);
}

Hope it's helpfull

CodePudding user response:

I think your JS code will execute before DB data retrieval, can you check JS code within the setTimeout() Method?

<script>
    setTimeout(function() {
        var iLenthv = document.getElementById("myInput").getAttribute("value");
        alert(iLenthv);
    }, 3000); 
</script>

CodePudding user response:

So we have to track the client side actual value, after the document is loaded. Would you adapt this piece of code and take a look at the console ?

<div data-ng-model="DashboardCounterItems">
  <div data-ng-repeat="cItem in DashboardCounterItems">
    <input type="hidden" id="myInput" value={{cItem.dbMeetings.length}} />
  </div>
</div>

<script>
  const test = () => {
    var iLenthv = document.getElementById("myInput").value;
    console.log("value:",iLenthv);
  };

  window.onload = test;
</script>

  • Related