Mizy
Mizy

Reputation: 69

Adding a score to every input field the user fills in the form and displaying it

Currently i have developed a program that gets the count of all the inputs field and adding up a percentage for the numbers of fields that are filled individually.

what i need now here, i need to assign a number to each input field and when the user fills an input field i need to show it to the user as a " SCORE ".

below is the program i have built.

<html>
<body>
<label> Name </label>
<input class="track"/>

<label> Name </label>
<input class="track"/>

<h5>Profile Strength  <span class='perc'>0</span>%</h5>

</body>
</html>

and the JavaScript is

<script>
   $('.track').change(function(e) {
update_progress();
});

// supports any number of inputs and calculates done as %

function update_progress() {
var count = $('.track').length;
var length = $('.track').filter(function() {
    return this.value;
}).length;
var done = Math.floor(length * (100 / count));
$('.perc').text(done);
$('.meter').width(done + "%");
} 

so when you fill the first input field the 'Profile strength' will show 50% as there are only 2 input fields, and when you fill the second input it will show 100%.

i want to show a number instead of a percentage here like

input 1 = 10

input 2 = 20

so when the user fills input 1 his "SCORE" will be 10, and when the user fills the next input the total must add on and show 30 in real time.

sorry if have confused a few developers but this the only way i understood the assignment i got.

Upvotes: 0

Views: 895

Answers (1)

sam
sam

Reputation: 1807

Try the following: Html:

<html>
 <body>
  <label> Name </label>
  <input class="track" data-score=10 />

  <label> Name </label>
  <input class="track" data-score=20 />

  <h5>Profile Strength  <span class='perc'>0</span>%</h5>
  <h5>Score <span id="score">0</span></h5>
 </body>
</html>

JS:

$('.track').change(function(e) {
    update_progress();
});

// supports any number of inputs and calculates done as %

function update_progress() {
    var score = 0
    $('input.track').each(function(){
      var _score = $(this).data("score")
        if ($(this).val().length > 0) {
          score += _score
        }
      })
   $('#score').text(score)
   var count = $('.track').length;
   var length = $('.track').filter(function() {
      return this.value;
   }).length;
   var done = Math.floor(length * (100 / count));
   $('.perc').text(done);
   $('.meter').width(done + "%");
} 

Or, a live version https://jsfiddle.net/wmt6cznh/2/

Is this what you want to achieve?

Upvotes: 2

Related Questions