1

I have a html form which only shows a price, but don't submit anything to the server. This works fine now.

How can I add the function of running this form just from url variables, so you don't have to click the submit button if you are coming to this page with url variables?

Something like this: www.my-domain.com/formurl/?smoker=yes&amount=500000&age=20 should display the price when the page is finished loading, and change the form values according to the url variables.

Here is my html:

<form class="form-horizontal">
        <label class="control-label" for="smoker">Do you smoke?</label>
        <select id="smoker" name="smoker"><option value="No">No</option><option value="Yes">Yes</option></select>

        <label class="control-label" for="amount">Amount</label>
        <select id="amount" name="amount"><option value="500000">500 000</option><option value="1000000">1 000 000</option><option value="1500000">1 500 000</option><option value="2000000">2 000 000</option></select>

        <label class="control-label" for="age">Age</label>
        <input id="age" name="age" type="text" />


        <button class="btn" id="calc" type="submit">Show price</button>
</form>


<div class="alert alert-info hide" id="price-result"></div>

$(document).ready(function () {

    //JSON object
    var obj = {"data":
    [
        {"age": "18","500000": "645","1000000": "1018","1500000": "1391","2000000": "1764","smoker": "No"},
        {"age": "19","500000": "645","1000000": "1018","1500000": "1391","2000000": "1764","smoker": "No"},
        {"age": "20","500000": "645","1000000": "1018","1500000": "1391","2000000": "1764","smoker": "No"},
        {"age": "18","500000": "964","1000000": "1544","1500000": "2125","2000000": "2705","smoker": "Yes"},
        {"age": "19","500000": "964","1000000": "1544","1500000": "2125","2000000": "2705","smoker": "Yes"},
        {"age": "20","500000": "964","1000000": "1544","1500000": "2125","2000000": "2705","smoker": "Yes"}
    ]

    };        

    //Find the value when form is submitted
    $('#calc').click(function(e) {
        e.preventDefault();

        var data = jQuery.grep(obj.data, function(element, index){
          return element.age && element.smoker; // retain appropriate elements

        });    

        var selectedSmoke = $('#smoker').val().toString().toLowerCase();
        var selectedAmount= $('#amount').val().toString().toLowerCase();
        var selectedage = $('#age').val().toString().toLowerCase();

        var amount = "";

        $.each(data,function(k, v){

            if( data[k].age.toString().toLowerCase() == selectedage &&  
                data[k].smoker.toString().toLowerCase() == selectedSmoke &&
                data[k][selectedAmount] != undefined){

                amount = data[k][selectedAmount];


            }

        });


        //Empty the div
        $('#price-result').empty();

        //Show the result in div
        var displayText = "<h3>Price:" + amount + "</h3>";

        $("#price-result").append(amount == "" ? "Not a valid age" : displayText).removeClass("hide");

        return false;//Stop page from reloading

    });


});
Tomas Jacobsen
  • 2,368
  • 6
  • 37
  • 81

2 Answers2

8

to fill input form URL

function getURLParameter(name) {
  return decodeURI(
   (RegExp(name + '=' + '(.+?)(&|$)').exec(location.search)||[,null])[1]
   );
}
var smoker = getURLParameter('smoker');
var amount = getURLParameter('amount');
var age = getURLParameter('age');

$('#smoker').val( smoker );
$('#amount').val( amount );
if(age != 'null'){
    $('#age').val( age );
    calculAmount(obj);
}

//Find the value when form is submitted
$('form').submit(function(e) {
    e.preventDefault();
    calculAmount(obj);
});

To send data to server, you can use get, post or ajax jquery

Replace $('#calc').click(function(e) by $('form').submit(function(e)

using get:

 //Empty the div
 $('#price-result').empty();

$.get("www.my-domain.com/formurl/",
 { smoke: selectedSmoke , amount: amount ,age: selectedage} );

or

$.post('www.my-domain.com/formurl/', $("form").serialize(), function(data) {
  console.log("data sent");
});

or

$.ajax({
         type : 'POST',
         url : 'www.my-domain.com/formurl/',
         data: $("form").serialize(),
         success : function(data){                                               
                   console.log("data sent");
          },
          error: function (request, status, error) {
                 console.log(request.responseText);
          } 
      });
Ouadie
  • 13,005
  • 4
  • 52
  • 62
  • Tried this, but don't I need some extra code, since the function is tied up in "click" function? – Tomas Jacobsen Apr 29 '13 at 08:19
  • No, did not work. But I don't get any errors either. Tried both your suggestions. – Tomas Jacobsen Apr 29 '13 at 08:33
  • Did you check if the request was sent or not? You can see all requests using **Dev tools** https://developers.google.com/chrome-developer-tools/docs/console – Ouadie Apr 29 '13 at 09:02
  • If I put the ajax function inside the click function, nothing gets logged to the console. If I put it outside the click function I get "data" sent", but the price is not showing, and the form options are not updated with the variables from the url. – Tomas Jacobsen Apr 29 '13 at 10:27
  • let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/29110/discussion-between-ouadie-and-garreth-00) – Ouadie Apr 29 '13 at 12:24
0

if you want to take get vars from URL you can do it like this

$(document).ready(function(){
    var getVars = getURLVariables();
    for(var i in getVars){
        if(i == "smoke"){
            $('#smoke').val(getVars[i]);
        }
    }

});

function getURLVariables(){
    var getVars = [];
    var split = location.href.split('?')[1].split('&');
    if(split != null){
        for(var i in split){
            var parts = split[i].split('=')
            getVars[parts[0]] = parts[1];
        }
    }   
}
gradosevic
  • 4,809
  • 2
  • 36
  • 51