Reputation:
I just started coding and I am trying to make a little webpage that finds the date of birth of a user. So I would like to substract the age from the current year (2017). However I don't know how to do that. Can you help me? Html code:
<body>
<h1 id="title"> Date of birth finder
<h1>
<h2 id="age"> Insert your age here: </h2>
<div>
<form>
<input type="number" name="quantity" min="0" max="2016">
</form>
</div>
<button id="bSubmit">Submit</button>
<div class="user-answer">
<form>
<input type="text" name="year">
</form>
</div>
</body>
<script>
var age = document.getElementById("quantity").value
$("bSubmit").on(click, function {
});
</script>
Upvotes: 1
Views: 219
Reputation: 55
You can also try this code, it may give you some luck as to what your looking for.
$("#bSubmit").on("click", function ()
{
age = document.getElementById("quantity");
year_of_birth = 2017 - age;
});
Upvotes: 0
Reputation: 42304
There are a few reasons why your script isn't working as expected:
id
attribute in order to target with getElementById
, not just a name
attribute. That would be written in HTML as <input id="quantity" name="quantity">
click
in jQuery's on()
needs to be written in quotation marks.bSubmit
with a hashtag at the start (which denotes that it's an ID that you're referencing).age
within the function, or else the value won't get updated when you change it.Here's an updated, working script :)
$("#bSubmit").on('click', function() {
var age = document.getElementById("quantity").value;
console.log(age);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h2 id="age"> Insert your age here: </h2>
<div>
<form>
<input type="number" id="quantity" name="quantity" min="0" max="2016">
</form>
</div>
<button id="bSubmit">Submit</button>
If instead you'd like to replace the user-answer
, simply subtract the input from the current date instead of logging to the console:
$("#bSubmit").on('click', function() {
var age = document.getElementById("quantity").value;
$("[name='year']").val((new Date()).getFullYear() - age);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h2 id="age"> Insert your age here: </h2>
<div>
<form>
<input type="number" id="quantity" name="quantity" min="0" max="2016">
</form>
</div>
<button id="bSubmit">Submit</button>
<div class="user-answer">
<form>
Current year minus input: <input type="text" name="year">
</form>
</div>
Hope this helps! :)
Upvotes: 0
Reputation:
This solution also updates based on the current year:
$("#bSubmit").on("click", function (){
$("[name='year']").val((new Date()).getFullYear() - $("[name='quantity']").val());
});
If you don't want that:
$("#bSubmit").on("click", function (){
$("[name='year']").val(2017 - $("[name='quantity']").val());
});
Upvotes: 1
Reputation: 1389
$("#bSubmit").on("click", function (){
$("[name='year']").val(new Date.getFullYear() - $("[name='quantity']").val());
});
- refining programmer5000 example
Upvotes: 0