Skip to content
Advertisement

Adding And Sorting Array Of Integers from html input field Using Javascript

The Task Is To Get 10 Values Of Array Through HTML Input Field And Sort Them In Acceding Order

In Order To Append 10 Value’s from Html Input field To JS Array I Created one input field which data is passed to array in js and Two labels to keep track of array using innerHTML Method Note:- The Name Of Array Is itself declared array

whenever a button is hit the input value of html data is appended to js array using id of input field and the resulted array is shown to label list every time we insert a new digit to array and the next label similar to this updates array lenght simantaeneously to limit it upto 10 index i compare array.lenght with 10th value i.e. 9th index Note:- Here Array index is starting from 0 so 9th index is 10th digit

But even Though Code Is Not Working Well Here’s my code looks like

HTML File

 <div id='div3'>
      <input type='number' id='ip1' placeholder='Enter values'></input>
      <label id='list' >List values are:</label>
      <button id='bt3' onClick='task()'>ADD Value</button>
      <label id='len' >Length:</label>
    </div>

JS FIle

var array =[];
function task()
{
  let pr=array.length;
  document.getElementById('len').innerHTML=pr;
  
  if(array.length > 9)
  {
  let item = document.getElementById('task3val').value;
  array.push(item);
  document.getElementById('list').innerHTML=array;
  }
  if(array.length<=9)
  {
    array.sort(function(a, b){return b - a});
    document.getElementById("list").innerHTML = array;
  }
}

Please Give Insighful Answer

Advertisement

Answer

I have made few changes in your code, It should work for you now. in the above code, you were using the wrong id for the text box

HTML code

 <div id='div3'>
  <input type='number' id='ip1' placeholder='Enter values'></input>
  <br/>
  <label id='list' >List values are: </label>
  <br/>
  <button id='bt3' onClick='task()'>ADD Value</button>
  <br/>
  <label id='len' >Length:</label>
</div>

Jquery code

<script type="text/javascript">
var array =[];
function task()
{  
if(array.length < 3)
{
let item = document.getElementById('ip1').value;
array.push(item);
document.getElementById('list').innerHTML = array.toString();
}
else
{
alert('Only 10 Items allowed!')
}
let pr=array.length;
document.getElementById('len').innerHTML=pr;  
}
</script>
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement