Dynamically update fields via input field and dropdown menu
I am trying to dynamically update a textbox through an input field. Then it will be attached to the dropdown menu with values. I also need to show the date to show 30 days from today.
Here is my HTML:
<div>
<label for="payment">Payment:</label>
<input type="text" name="amount" id="amount" onChange="myfunction()"/>
<br /><br />
<label for="delivery">Delivery:</label>
<select id="delivery" name="delivery">
<option value="1">Fast</option>
<option value="2">Medium</option>
<option value="3">Slow</option>
</select>
</div>
<br />
<div>
Payment Breakdown: <br /><br />
Payment:
<div name="amount" id="amount"></div>
Freight:
<div name="delivery" id="delivery"></div>
Total Payment:
<div name="total" id="total"></div>
Due Date:
<div name="date" id="date"></div>
</div>
I am scared with the Javascript part and it all fits.
I've gotten to this and now I'm stuck. (Not very far I know)
function myFunction()
{
var amount = document.getElementById("amount");
var delivery = parseInt($(this).find("option:selected").val());
total = amount + delivery
$("#total").html(total);
};
I've looked at examples on Stackoverflow and Google, but nothing like what I'm trying to achieve. While I know there is an answer, I am not sure I am asking the correct question.
Greetings
source to share
I would change it to this. Here I have a function updateCost()
that gets called when the amount changes or the delivery changes. I also added code to handle the date.
Extract the inline event onchange
from the sum:
<input type="text" name="amount" id="amount"/>
JavaScript:
function updateCost()
{
var amount = $('#amount').val();
var delivery = parseInt($('#delivery').val());
var total = amount + delivery
$("#total").html(total);
$("#amountdiv").html(amount);
$("#deliverydiv").html(delivery);
// handle the due date
var todayPlus30 = new Date();
todayPlus30.setDate(todayPlus30.getDate()+30);
var dateStr = todayPlus30.getDate() + "/" + (todayPlus30.getMonth()+1) + "/" + todayPlus30.getFullYear();
$('#date').html(dateStr);
}
$(document).ready(function(){
$('#amount').change(function(){ updateCost(); });
$('#delivery').change(function(){ updateCost(); });
});
There are several problems in the source code:
- Invalid case when calling a built-in function
- Use
this
inside a function whenthis
it is not actually any of your elements (you didn't pass it as an argument). - Use
amount
in a calculation when itamount
is an input element rather than a value. - From a usability point of view, it will just try to update when the amount is changed, I think it would be better to update both the amount change and shipping.
source to share