我有一个仅显示价格的 html 表单,但不向服务器提交任何内容。这现在工作正常。
如何添加仅从 url 变量运行此表单的功能,这样如果您使用 url 变量来到此页面,就不必单击提交按钮?
像这样: www.my-domain.com/formurl/?smoker=yes&amount=500000&age=20 应该在页面加载完成时显示价格,并根据 url 变量更改表单值。
这是我的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
});
});