0

I am trying to create a form on an HTML page (that also has Bootstrap code) and when the user clicks the submit button I want the data to be captured and processed by an external javascript file in the same directory. However, I don't think I am doing this correctly because when I click on the submit button the page reloads and the result of the addition does not show up below.

Here's a link to the files: https://gist.github.com/anonymous/2dc8c07d87469716f9d2

Thanks in advance!

user2411857
  • 3
  • 1
  • 4

2 Answers2

2

You have to change

<button type="submit" class="btn btn-default" method="POST" onclick="process()">Submit</button>

to

<button type="button" class="btn btn-default" onclick="process()">Submit</button>

Also

function process(){
var q1 = document.getElementById("firstquartergrade").value;
var q2 = document.getElementById("secondquartergrade").value;
var result = q1+q2;
document.getElementById("result").innerHTML = result;
}

to

function process(){
var q1 = parseInt(jQuery("#firstquartergrade").val());
var q2 = parseInt(jQuery("#secondquartergrade").val()); 
var result = q1+q2; 
jQuery('#result').html(result);
}
Syam Mohan M P
  • 1,047
  • 8
  • 23
  • I tried that and it still does not work. I then tried changing it from jQuery('#result').html(result) to jQuery('#result').text(result) and it prints out "NaN" on the page – user2411857 Jun 21 '14 at 04:05
  • @user2411857 This answer is wrong. You can't do `parseInt()` of a DOM object. You will need to do: `parseInt($("#firstquartergrade").val());` – Spencer Wieczorek Jun 21 '14 at 04:09
1

You can achieve it using ajax.

Here is small demo your can refer :

Note : Change actionUrl as per your requuirement

test.Html:

    <form action='actionUrl' class='ajax' method='post'>
         <input type='text' name='name' placeholder='Enter Name'/>
         <input type='submit' value='submit'/>
    </form>
    <div id='somediv'></div>
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
    <script src='main.js'></script>

Here is global method for ajax.You can use it for all.

Main.js :

    $('form.ajax').on('submit',function(){

    var vForm=$(this),
        url=vForm.attr('action'),
        type=vForm.attr('method'),
        data={};

    vForm.find('[name]').each(function(){
       var vInput=$(this),
       name=vInput.attr('name'),
       value=vInput.attr('value');
       data[name] = value;
     });

     $.ajax({
        url:url,
        type:type,
        data:data,
        success:function(response){
            $('#somediv').html(response);
          } 
     });
     return false;
    });
Darshan Patel
  • 2,839
  • 2
  • 25
  • 38