Dynamically Update fields through Input field and dropdown - javascript

I'm trying to dynamically update a text field through an input field. This will then be linked to a dropdown selection with values. I also need to show a due date to show 30 days in advance from today's date.
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'm struggling with the Javascript part though and fitting it all together.
I've gotten as far as 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 seems similar to what I'm trying to achieve. Although I know the answer is out there, I'm not sure if I'm asking the right question.
Cheers

I would change it to this. Here I have an updateCost() function which is called when the amount is changed or the delivery is changed. I also added code to handle the due date.
Remove the inline onchange event from the amount:
<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(); });
});
Your original code has a few problems:
The wrong case on the inline function call
The use of this within the function when this is not actually any of your elements (you didn't pass it as an argument).
The use of amount in the calculation when amount is an input element, not a value.
From a usability point of view, it would only try to update when the amount is changed, I think it would be better to update on both change of the amount and delivery.

Related

js / jquery object display just a quick flash

I am messing around with js objects today, ran across a weird glitch.
<form method="get" action="" name="start" >
<fieldset>
<label for="date">Date</label>
<input type="date" name="date" id="date" />
<div> </div>
<label for="smiles">Starting Mileage</label>
<input type="number" name="smiles" id="smiles" />
<div> </div>
<label for="stime">Starting Time</label>
<input type="time" name="stime" id="stime" />
<div> </div>
<label for="submit">Click To Save</label>
<input type="submit" name="submit" id="submit" />
</fieldset>
</form>
<div id="display" name="display" ></div>
`<script>src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js">`
</script>
<script>
$(document).ready(function() {
$("#submit").click(function(){
var date = document.getElementById("date").value;
var smiles = document.getElementById("smiles").value;
var stime = document.getElementById("stime").value;
var record = { date2: date, smiles2: smiles, stime2: stime };
document.getElementById("display").innerHTML = smiles;
});
});
</script>
when you run this, the record.smiles flashes in the div id='display' but doesn't stay. Why? This is asking for more details, I don't know how much more in detail I can go, hopefully this will be enough verbage to make it happen.
Thanks.
It flashes and then disappears because you are clicking a submit button and the default action of a button on a form is to try and submit the form.
To prevent the default action you just need to add a single line of code:
$(document).ready(function() {
$("#submit").click(function(){
event.preventDefault(); // <----add this
var date = document.getElementById("date").value;
var smiles = document.getElementById("smiles").value;
var stime = document.getElementById("stime").value;
var record = { date2: date, smiles2: smiles, stime2: stime };
document.getElementById("display").innerHTML = smiles;
});
});
Also, you mentioned you are "playing around with javascript objects" so i just wanted to let you know that the code you have written here:
var record = { date2: date, smiles2: smiles, stime2: stime };
Could be completely removed and not affect the behavior of your program at all.
It is also unnecessary to add the "2" to your key name. They can just be the same as your variable if you want. Also, as a matter of style and readability formatting you object literals like this is slightly more readable if they become more complex. Have fun!
var record = {
date: date,
smiles: smiles,
stime: stime
};
You must prevent the default action of the submit button, otherwise it will submit the form at the same time, therefore reloading the page, try adding:
$("#submit").click(function(event) {
event.preventDefault()

Trying to calculate the total price of items taking into account the quantity selected Javascript

this is my first time posting on this site. i have a webpage that outlines one of my products that I intent to sell
here is my dilemma. I have this code that asks the user to press + and - buttons for the quantity of the item that they want. Now what i am trying to work out is if the user presses + or - any number of times I need to be able to to take into account the number of clicks and calculate the total price for the order on a separate line. Im very new to javascript all help is appreciated thanks
<form>
<br> Item Price: $463.50
<br> Please Select Quantity
<input type='button' name='subtract' onclick='javascript: document.getElementById("qty").value--;' value='-'/>
<input type='button' name='add' onclick='javascript: document.getElementById("qty").value++;' value='+'/>
<input type='text' name='qty' id='qty' />
</form>
<form>
<br> Item Price: $<span id='price'>463.50</span>
var unitprice = (document.getElementById('price').innerText || document.getElementById('price').textContent);
var price = parseFloat(unitprice);
var count = parseInt(document.getElementById("qty").value, 10)
var total = price * count;
alert(total); // or do whatever you want
I would separate out the Javascript code into its own <script> element, and do something like:
<form>
<br/> Item Price: $<span id="price">463.50</span>
<br/> Please Select Quantity
<input type="button" name="subtract" id="subtract" value="-"></input>
<input type="button" name="add" id="add" value="+"></input>
<input type="text" name="qty" id="qty" value="0"></input>
<br/> Total
<input type="text" name="total" id="total" value="0"></input>
</form>
The Javascript would look like:
$(function() {
var price = parseFloat($('#price').text());
$('#subtract').on("click",function() {
var $qty = $('#qty');
var current = parseInt($qty.val());
if ( current > 0 ) {
$qty.val(current-1);
$('#total').val(price*(current-1));
} else {
$('#total').val(0);
}
});
$('#add').on("click",function() {
var $qty = $('#qty');
var current = parseInt($qty.val());
$qty.val(current+1);
$('#total').val(price*(current+1));
});
});
You can see it in action.
This is all do-able without jQuery, but it makes life a lot easier!
Since you mentioned you're new to this, a word of WARNING: In the real app only use the quantity from the page, and re-calculate out how much to charge them on the back end. It would be very easy for someone to modify either the price or total in the DOM; if you were to use the price or total from the DOM then a malicious user could buy it for any price they wanted! Always assume input is malicious or incorrect.
var value = parseInt(document.getElementById("qty").value, 10)
item_price = item_price * value;
document.getElementById("someid").innertHTML = item_price;

Changing Date with Radio Buttons in Javascript

So I've gotten my code to display the correct current date in the 1st text box, but then when I choose one of the radio buttons to choose my "Pick-Up" date, the 2nd text box does not display the date. Basically, 1st box should show current date, 2nd box should show the date chosen from the radio buttons (imagine dropping off film that needs developed and you are choosing whether you want it 1 day, 2 days, or 3 days processing). I am including my full code so you can see what I'm doing. Can someone please show me what I'm doing wrong...
<script type="text/javascript">
function my_curr_date() {
var currentDate = new Date()
var day = currentDate.getDate();
var month = currentDate.getMonth() + 1;
var year = currentDate.getFullYear();
var my_date = month+"-"+day+"-"+year;
document.getElementById("dateField").value=my_date;
}
function orderReady(orderTime){
dateToday.setDate(dateToday.getDate()+orderTime);
var ready=dateToday.getMonth()+"/"
+dateToday.getDate()+"/"+dateToday.getFullYear();
document.getElementById("duedateField").value=ready;
}
<p>Item<br />
<input type="radio" name="item" value="print_5x7" onclick="orderReady(1)" />5x7 Prints(1 day)
<input type="radio" name="item" value="poster" onclick="orderReady(1)" />Poster (1 day)
<input type="radio" name="item" value="mug" onclick="orderReady(2)" />Coffee Mug (2 days)
<input type="radio" name="item" value="shirt" onclick="orderReady(3)" />T-shirt (3 days)</p>
<p>Today's Date<br />
<input type='text' name='dateField' id='dateField' value='' /><br />
Pick-up Date<br />
<input type='text' name='duedateField' id='duedateField' value='' /></p>
You did not set the duedateField value to the result you have calculated
i think this
function orderReady(orderTime){
dateToday.setDate(dateToday.getDate()+orderTime);
var ready=dateToday.getMonth()+"/"
+dateToday.getDate()+"/"+dateToday.getFullYear();
document.getElementById("duedateField").value=due_date;
}
should be
function orderReady(orderTime){
dateToday.setDate(dateToday.getDate()+orderTime);
var ready=dateToday.getMonth()+"/"
+dateToday.getDate()+"/"+dateToday.getFullYear();
document.getElementById("duedateField").value=ready;
}
you have to set ready for the duedateField value
it is so simple dude
function orderReady(orderTime){
dateToday.setDate(dateToday.getDate()+orderTime);
var ready=dateToday.getMonth()+"/"
+dateToday.getDate()+"/"+dateToday.getFullYear();
document.getElementById("duedateField").value=due_date;
}
you should replace value=due_date with value=ready

How to dynamically add text fields to a form based on a number the user puts in

I'm attempting to make a form that asks the user for a number of units, then asks whether or not they would like those units to be provisioned, and depending on the answer, generates text fields corresponding with the number of units the typed in, along with a text field asking for an account number.
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js">
</script>
<script type="text/javascript">
function Getunits(value) {
var units = document.getElementById('units');
for(count=0; count<=units; count++) {
$("<input type='text'>").appendTo("inpane");
}
document.getElementByTag('futureacc').InnerHTML='What is your account number? <input type="text" value="accountnum">';
}
</script>
</head>
<body>
<div id="container">
<form method="post" action="sendcontact.php">
<div id="unitammount" class="inpane">
Number of units ordered: <input type="text" name="units" id="units"/><br />
</div>
<div id="futureacc" class="inpane">
Are these units to be provisioned? <input type="radio" name="select" value="yes" onClick="Getunits('units.value')"/> Yes <input type="radio" name="select" value="no"/> No
</div>
Obviously I would like the new text fields to appear inside the futureacc div and inpane div respectively.
I don't know whether it's the loop that doesn't do anything or that I'm not appending correctly but as I currently have it this does nothing...
Any help would be greatly appreciated.
You had a number of errors with your code. It was confusing because you were mixing jQuery and pure Javascript. It's generally better to just use jQuery if you've decided to use it anyway. Your loop should have been iterating while it was smaller than units.val(), not while it was smaller than or equal to units. innerHTML is spelled with a lowercase "i," and your appendTo selector needed a period before the class name. I went ahead and cleaned up your code so it should work now!
HTML:
<div id="container">
<form method="post" action="sendcontact.php">
<div id="unitammount" class="inpane">
Number of units ordered: <input type="text" name="units" id="units"/>
</div><br>
<div id="futureacc" class="inpane">
Are these units to be provisioned? <input type="radio" name="select" value="yes" onClick="getUnits()"/> Yes <input type="radio" name="select" value="no"/> No <br>
</div>
</form>
</div>​
Javascript:
function getUnits() {
var units = $("#units").val();
for (var count = 0; count < units; count++) {
$("<input type='text' /><br>").appendTo("#futureacc");
}
$("#futureacc").append('<br>What is your account number? <input type="text" placeholder="accountnum">');
}​
WORKING DEMO
var units = document.getElementById('units');
needs to be
var units = document.getElementById('units').value;
you are passing value to onclick but it is a string will not give you exact value anyway you are not using it in you function so it doesnt have any side effect.
also you need to some error check to make sure that user has entered a number
with
for(count=0; count<=units; count++)
You are adding 1 more text box than user entered value. so if user has entered 4 you are creating 5 <= should be changed to <
This is wrong
onClick="Getunits('units.value')"
Instead use this:
onClick="Getunits(units.value)"
try this
$(document).ready(function(){
$('input[name=select]').click(function(){
if($(this).val() ==='yes'){
var numberOfTextboxes = $('#units').val();
for(var i =0; i<numberOfTextboxes; i++){
$('#unitammount').append('<input type="text" />');
}
}
});
});
See the fiddle

Javascript/Ajax/Jquery Dynamically calculate form on change

I have a small form which is going to be populated from Mysql and human input. What I want to do is populate 3 other fields based on the other ones.
Example:
Total Parts (Mysql)
Labor (User)
Misc (User)
Sub Total (Dynamic total of above)
Tax (Dynamic calc of above - sub * 13%)
Total (Sub + Tax)
I have searched around but can not quite find what I am looking for, and my skills are zero in Javascript/Ajax/Jquery so I haven't been able to modify anything to work, although I have tried miserably.
Can someone help me out on this or point me to a script that may suit my needs.
Thanks
Alright sorry, I thought you were looking for some complex code. Here is a simple example of exactly what you're looking for.
<html>
<head>
</head>
<body>
<script>
function doMath() {
var totalparts = parseInt(document.getElementById('parts_input').value);
var labor = parseInt(document.getElementById('labor_input').value);
var misc = parseInt(document.getElementById('misc_input').value);
var subtotal = totalparts + labor + misc;
var tax = subtotal * .13;
var total = subtotal + tax;
document.getElementById('subtotal_input').value = subtotal;
document.getElementById('tax_input').value = tax;
document.getElementById('total_input').value = total;
}
</script>
<div>Total Parts: <input type="text" id="parts_input" value="1" readonly="true" /></div>
<div>Labor: <input type="text" id="labor_input" onBlur="doMath();" /></div>
<div>Misc: <input type="text" id="misc_input" onBlur="doMath();" /></div>
<div>Sub Total: <input type="text" id="subtotal_input" readonly="true" /></div>
<div>Tax: <input type="text" id="tax_input" readonly="true" /></div>
<div>Total: <input type="text" id="total_input" readonly="true" /></div>
</body>
</html>
Obviously this doesn't grab the dynamic value from a database. If you use PHP you can swap this line:
<div>Total Parts: <input type="text" id="parts_input" value="1" readonly="true" /></div>
for one like this:
<div>Total Parts: <input type="text" id="parts_input" value="<?PHP include('getTotalParts.php'); ?>" readonly="true" /></div>
Where the getTotalParts.php is a file you make to get your database information. It can simply grab the information and do a "echo $totalParts;"
You can just use onblur (activated when a user leaves each of the input fields) to calcuate the fields.
...<input name="labour" id=total onblur="$('#total').val($('#sub').val() + $('#tax').va())">
You haven't provided enough information to comment on the "Total Parts" field.

Categories