-1

Anyone may help me to find the problem in this javaScript code , actually i want to take input from user and the taken should be sorted in Descending order .

Code is -

<html>

<body>
    <h2><u>Sorting the array in Descending order</u></h2>
    <script>  
         var number=document.getElementById("D").value;  
         document.write(number);
         function Sort_Number(x, y) 
        {
            return y - x;
        }
       documentgetElementbyId(number.sort(Sort_Number)) = Af;
       </script>  
       <form>
       <label for="fname">Enter the values - </label><br>
       <input type="text" name="nm"  id="D" ><br><br>
       <input type="button" value="Sort" onclick="Sort_Number()"><br><br>
       <label for="fname">Descending values are - </label><br>
       <input type="text" name="nm" id="Af"><br><br>
   </form>
</body>
</html>
  • should be document.getElementById no `documentgetElementbyId ` you are missing "." – lissettdm Mar 15 '22 at 15:54
  • i have put . now but still not working – prabhas lal Mar 15 '22 at 15:57
  • 1
    @prabhaslal Learn about [how to debug small programs](//ericlippert.com/2014/03/05/how-to-debug-small-programs). Try using your browser’s [debug capabilities](//ali-dev.medium.com/how-to-easily-debug-in-javascript-5bac70f94f1a). See [What is a debugger and how can it help me diagnose problems?](/q/25385173/4642212). Use the [browser console (dev tools)](//webmasters.stackexchange.com/q/8525) (hit `F12`), read any errors. – Sebastian Simon Mar 15 '22 at 15:58
  • ok i will try it – prabhas lal Mar 15 '22 at 16:03
  • [JS docs](//developer.mozilla.org/docs/Web/JavaScript/Reference) and [JS tutorials](//developer.mozilla.org/docs/Web/JavaScript/Guide) are all available. Why do you pass an array into `getElementById`? Why do you expect `onclick="Sort_Number()"` to do anything? Inline event handlers like `onclick` are [bad practice](/q/11737873/4642212). They’re an [obsolete, cumbersome, and unintuitive](/a/43459991/4642212) way to listen for events. Always [use `addEventListener`](//developer.mozilla.org/docs/Learn/JavaScript/Building_blocks/Events#inline_event_handlers_%E2%80%94_dont_use_these) instead. – Sebastian Simon Mar 15 '22 at 16:05
  • Why do two of your text inputs have the same `name`? Why do your labels have `for="fname"` but no element with the ID `fname` exists? `= Af` makes no sense because you can’t assign to a function call; you could assign something to a _property_, but not `Af`, because assigning an element doesn’t make sense in this context. And relying on the global property `Af` to exist is [bad practice](/q/3434278/4642212). [`sort`](//developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Array/sort) is an array method. Where are you creating an array? Go over JS and HTML basics again. – Sebastian Simon Mar 15 '22 at 16:12

2 Answers2

0

Your script is executed immediately, so the only thing called by the button is Sort_Number(), and that function requires the paramters x and y which you don't provide in onclick="Sort_Number()". You want to use Sort_Number(x, y) as the compare function when you call number.sort, and you will need to call another function on the button press to actually carry it out; it won't just execute the contents of the <script> tag again. Your script tag here should only be functions.
So for my solution I'm making another function Sort() that turns document.getElementById("D").value into an array of integers, sorts it in descending order, and outputs it to Af:

function Sort() {
  var number = document.getElementById("D").value.split(" "); //splits string into array
  for(let i = -1; ++i < number.length; number[i] = parseInt(number[i])); //turns strings into integers
  number = number.sort(Sort_Number); //sorts the array
  document.getElementById("Af").value = number.toString().replace(/,/gi, " "); //outputs array with spaces instead of commas
  return;
}

Then in your button you'd use onclick="Sort()".

So the whole thing would look like this:

<html>

<body>
    <h2><u>Sorting the array in Descending order</u></h2>
    <script>
         function Sort_Number(x, y) 
        {
            return y - x;
        }
         function Sort() {
            var number = document.getElementById("D").value.split(" ");
            for(let i = -1; ++i < number.length; number[i] = parseInt(number[i]));
            number = number.sort(Sort_Number);
            document.getElementById("Af").value = number.toString().replace(/,/gi, " ");
            return;
        }
       </script>  
       <form>
       <label for="fname">Enter the values - </label><br>
       <input type="text" name="nm"  id="D" ><br><br>
       <input type="button" value="Sort" onclick="Sort()"><br><br>
       <label for="fname">Descending values are - </label><br>
       <input type="text" name="nm" id="Af"><br><br>
   </form>
</body>
</html>

Note that the user must separate each number with one space, if you want a different separator you can change the parameter used in split(" ")

Matt Pasta
  • 183
  • 7
0

If you are not submitting the form, I don't know if it's necessary to wrap in form tag.

considering that you have only 1 text field for input numbers, You need to consider to add some char to use split method in javascript, in this case, I will consider a simple '-'.

First, let's start to separate your elements to be more clearly

   <h2><u>Sorting the array in Descending order</u></h2>

   <div>
       <label for="numbers">Enter the values - </label><br>
       <input type="text" name="numbers"  id="numbers" ><br><br>
       <input type="button" value="Sort" onclick="handleSortNumber()"><br><br>
   </div>

   <div>
      <label for="result">Descending values are - </label><br>
      <input type="text" name="result" id="result"><br><br>
   </div>

Second, you can keep the inputs elements in a variable

<script>
...
  const inputValues = document.getElementById("numbers");
  const output = document.getElementById("result");
...
</script>

Now, you can create a handleSortNumber but don't forget that you have a string with values separated with '-' in your input, and now you need to split them, in javascript you can use the method 'split'

function handleSortNumber() {

   const splitedValues = inputValues.value.toString().split('-');
   ...
}

Now, splitedValues will have a array of String and we can to convert each one to a number, and we can use a map to pass for each element.

function handleSortNumber() {
    ...

    const numbers = splitedValues.map(value => Number(value));
    ...
}

Finally, you can sort a number and insert the result into a output

function handleSortNumber() {
...

    const sortedNumbers = numbers.sort(function compare(a, b) {
          return b - a;
        })
        output.value = sortedNumbers.join('-')
    }
}

Full code:

<html>

<body>
    <h2><u>Sorting the array in Descending order</u></h2>

   <div>
       <label for="numbers">Enter the values - </label><br>
       <input type="text" name="numbers"  id="numbers" ><br><br>
       <input type="button" value="Sort" onclick="handleSortNumber()"><br><br>
   </div>

    <div>
      <label for="result">Descending values are - </label><br>
      <input type="text" name="response" id="result"><br><br>
    </div>
   
    <script>
      const inputValues = document.getElementById("numbers");
      const output = document.getElementById("result");
      

      
      function handleSortNumber() {
        const splitedValues = inputValues.value.toString().split('-');
        const numbers = splitedValues.map(value => Number(value));

        const sortedNumbers = numbers.sort(function compare(a, b) {
          return b - a;
        })
        output.value = sortedNumbers.join('-')
      }

    </script>
</body>
</html>
Massaaki
  • 1
  • 2