JulianJ JulianJ - 6 months ago 22
Javascript Question

How to display the value from my form?

Please can someone tell me why my code is not working? I'm very new to jquery and am trying to get a value from an input field into jquery variable that I can use.
Can anyone tell me what is wrong with my code? Here is a fiddle. Thanks.

The html

<form id="form" method="post">
<input type="text" id="cost" placeholder ="enter a number between 0 & 100" />
<input type="submit">



<div id="gauge" class="200x160px"></div>


Jquery

$( "#form" ).submit(function() {
value = $("#cost").val();

//Display value in justgage
var g = new JustGage({
id: "gauge",
value: value,
min: 0,
max: 100,
title: "Visitors"
});

});


</form>

Answer

For this to work you need to

  • load jQuery in the JSFiddle
  • preventDefault the submission
  • have a place for gauge to put the result
  • not create a new gauge every time you submit

Here is a working code that sets the new value if a gauge already exists

FIDDLE

var g;
$("#form").submit(function(e) {
  e.preventDefault();
  value = $("#cost").val();
  
  //Display JustGage
  if (!g) {
    g = new JustGage({
      id: "gauge",
      value: value,
      min: 0,
      max: 100,
      title: "Visitors"
    });
  }
  else g.refresh(value);

});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script type="text/javascript" src="https://cdn.jsdelivr.net/raphael/2.1.2/raphael-min.js"></script>
<script type="text/javascript" src="https://cdn.jsdelivr.net/justgage/1.0.1/justgage.min.js"></script>
<form id="form" method="post">
  <input type="text" id="cost" placeholder="enter number from 0 - 100" />
  <input type="submit">
</form>
<div id="gauge">

</div>