Dynamically sum 2 fields on an MVC Edit form - javascript

I have an MVC Edit form with 2 fields called ExVAT and VAT. I want to add another field with the total of these 2 values.
At the moment what I have shows the total of the 2 fields when the form is loaded. But if you were to change one of the other fields the total is not updated to reflect the new total.
So for example in the screen shot below:
I have changed the Ex.Vat Figure from 22 to 32, but the total has not been updated (I'll deal with formatting when the value is correct)
The code to get the total is:
#Html.Raw(Model.Vat + Model.ExVat)
What is the best way to make the total field update as the other fields are edited?

JSFiddle: https://jsfiddle.net/3tnjtLv5/1/
<div>
<div><input id="txtA" type="text" value="1"></div>
<div><input id="txtB" type="text" value="2"></div>
<div id="txtResult">
</div>
<script>
var txtA=$('#txtA');
var txtB=$('#txtB');
var txtResult=$('#txtResult');
function updateSum() {
txtResult.html(parseInt(txtA.val()) + parseInt(txtB.val()));
}
$(function() {
updateSum();
txtA.change('change', updateSum);
txtB.bind('change', updateSum);
});
</script>

Use jQuery input, property change method
jQuery('#Ex.vat', '#vat').on('input propertychange paste', function() {
$('#Total').val($('#Ex.vat').val()+$('#vat').val());
});

Related

How to check if a page comes after clicking the back button using jQuery?

I have a form where I am calculating the total amount using jQuery.
The function I created for that is updateTotal();
and the form action is another page and the action page has this button:
<button class="btn btn-success" onclick="history.go(-1);" type="submit" name="edit">EDIT</button>
so when the user clicks on the EDIT button page goes back to the form again (first page) and all the filled up details are there except the repetitve fields created using jQuery.
The sample form is here in js fiddle
I just want to run this function updateTotal(); if the user comes to the form by clicking the EDIT (basically browse go back) button..
Is there any way to do this in jQuery?
UPDATES FOR FUTURE REFERENCE - I SOLVED IT LIKE THIS
html:
<input type="text" id="amount" name="amount[]" placeholder="Amount" required="required" class="form-control inputChangeVal reqF reqFamount" data-js-input-type="number" />
and the jQuery :
jQuery(document).ready(function() {
var hiddenTot = jQuery('.reqFamount').val() ;
jQuery(".totalAmount").val(hiddenTot);
});
Define a hidden field to store the computed value.
<input type="hidden" id="hiddenTotal" />
Then store the calculated value to the hidden field with Id 'hiddenTotal'.
function updateTotal() {
var price = 0;
$(".inputChangeVal").each(function() {
var t = parseFloat(jQuery(this).val(), 10);
price = price + t;
});
var total = price.toFixed(2);
$(".totalAmount").val(total);
$("#hiddenTotal").val(total);
}
Then when the browse back is triggered the hiddenfield is automatically filled by the browser.
Next check when the document is ready, read the value of hiddenTotal and write to totalAmount.
$(document).ready(function (){
// read value and set value of totalAmount to hiddentotal;
var hiddenTotal = $("#hiddenTotal").val() || 0; //use the hiddenTotal value or if not present set 0 as the default value
$(".totalAmount").val(hiddentotal)
}
Now totalAmount is restored. This even works when you leave the page and return using your browsers history.

How to POST additional values from inputs outside the form [duplicate]

I've read many blogs and posts on dynamically adding fieldsets, but they all give a very complicated answer. What I require is not that complicated.
My HTML Code:
<input type="text" name="member" value="">Number of members: (max. 10)<br />
Fill Details
So, a user will enter an integer value (I'm checking the validation using javascript) in the input field. And on clicking the Fill Details link, corresponding number of input fields will appear for him to enter. I want to achieve this using javascript.
I'm not a pro in javascript. I was thinking how can I retrieve the integer filled in by the user in input field through the link and displaying corresponding number of input fields.
You could use an onclick event handler in order to get the input value for the text field. Make sure you give the field an unique id attribute so you can refer to it safely through document.getElementById():
If you want to dynamically add elements, you should have a container where to place them. For instance, a <div id="container">. Create new elements by means of document.createElement(), and use appendChild() to append each of them to the container. You might be interested in outputting a meaningful name attribute (e.g. name="member"+i for each of the dynamically generated <input>s if they are to be submitted in a form.
Notice you could also create <br/> elements with document.createElement('br'). If you want to just output some text, you can use document.createTextNode() instead.
Also, if you want to clear the container every time it is about to be populated, you could use hasChildNodes() and removeChild() together.
<html>
<head>
<script type='text/javascript'>
function addFields(){
// Generate a dynamic number of inputs
var number = document.getElementById("member").value;
// Get the element where the inputs will be added to
var container = document.getElementById("container");
// Remove every children it had before
while (container.hasChildNodes()) {
container.removeChild(container.lastChild);
}
for (i=0;i<number;i++){
// Append a node with a random text
container.appendChild(document.createTextNode("Member " + (i+1)));
// Create an <input> element, set its type and name attributes
var input = document.createElement("input");
input.type = "text";
input.name = "member" + i;
container.appendChild(input);
// Append a line break
container.appendChild(document.createElement("br"));
}
}
</script>
</head>
<body>
<input type="text" id="member" name="member" value="">Number of members: (max. 10)<br />
Fill Details
<div id="container"/>
</body>
</html>
See a working sample in this JSFiddle.
Try this JQuery code to dynamically include form, field, and delete/remove behavior:
$(document).ready(function() {
var max_fields = 10;
var wrapper = $(".container1");
var add_button = $(".add_form_field");
var x = 1;
$(add_button).click(function(e) {
e.preventDefault();
if (x < max_fields) {
x++;
$(wrapper).append('<div><input type="text" name="mytext[]"/>Delete</div>'); //add input box
} else {
alert('You Reached the limits')
}
});
$(wrapper).on("click", ".delete", function(e) {
e.preventDefault();
$(this).parent('div').remove();
x--;
})
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="container1">
<button class="add_form_field">Add New Field
<span style="font-size:16px; font-weight:bold;">+ </span>
</button>
<div><input type="text" name="mytext[]"></div>
</div>

second javascript not working on my contact form

Ok, all, I have a few questions.
How can I have my total have a $ and how can I move up next to the word Total: ( so it will be side by side)
Once I get a total price, is there a way where I can divide it by 2 to get 1/2 of the price into another field called 'deposit' before copying that to add to another field called 'balance':
I cannot get the date fields to copy
To note this is where I found how to add up the radio buttons ( Here)
This is what I have so far.
This is my form:
Session Date: <input type="text" name="field1" id="f1" />
Session Type payment :
<input type="radio" name="sessiontypepayment" id="sessiontypepayment1" value="100.00" onclick="FnCalculate(this,'extrapeople');"> Mini Session $100.00
<input type="radio" name="sessiontypepayment" id="sessiontypepayment2" value="250.00" onclick="FnCalculate(this,'extrapeople');"> Full Session $250.00
Extra people :
<input type="radio" name="extrapeople" id="extrapeople1" value="25.00" onclick="FnCalculate(this,'sessiontypepayment');"> 1 person $25.00
<input type="radio" name="extrapeople" id="extrapeople2" value="50.00" onclick="FnCalculate(this,'sessiontypepayment');"> 2 people $50.00
<input type="radio" name="extrapeople" id="extrapeople3" value="75.00" onclick="FnCalculate(this,'sessiontypepayment');"> 3 people $75.00
<input type="radio" name="extrapeople" id="extrapeople4" value="100.00" onclick="FnCalculate(this,'sessiontypepayment');"> 4 people $100.00
Total Amount: <div id="total"></div>
Deposit Amount:
Balance Amount:
balance due BY: <input type="text" name="field2" id="f2" />
This is my script what I have so far.
<script type="text/javascript">
$(document).ready(function(){
$("#f1").keyup(function(){
var f2Text = $('#f2').val() + $(this).val();
$('#f2').val(f2Text );
});
});
</script>
<script>
function FnCalculate(id,name)
{
var total=0;
if(document.getElementById(name+"1").checked == true)
{
total = parseInt(document.getElementById(name+"1").value);
}
if(document.getElementById(name+"2").checked == true)
{
total = parseInt(document.getElementById(name+"1").value);
}
total = total + parseInt(id.value);
document.getElementById("total").innerHTML = total;
}
</script>
I would really love help on this please.
First, get rid of all the onclick="FnCalculate(this,'xx');" bits on your inputs.
Then replace your <script>s with this:
<script type="text/javascript">
$(document).ready(function() {
$("#f1").keyup(function() {
$('#f2').val($(this).val());
});
var inputs = $('input[name="sessiontypepayment"], input[name="extrapeople"]');
$(inputs).click(function() {
var total = 0;
$(inputs).filter(':checked').each(function() {
total = total + parseInt($(this).val());
})
$('#total').html('$' + total);
$('#deposit').html('$' + (total / 2));
});
});
</script>
Unsure what you mean by "how can I move up next to the word Total" but I suspect changing <div id="total"></div> to <span id="total"></span> will solve your problem. Either that, or apply some css to the div:
#total {
display: inline;
}
I added the calculation for the deposit, you'll need to add <div id="deposit"></div> to your page somewhere...
You will need jquery. Add this in between <head>...</head>:
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
First, you should have your defaults set to checked='checked' for HTML radio buttons that you want checked initially. I would put default text into <div id='total'>$125.00</div>, as well. You might as well use jQuery for what it's made for and not put Events into your HTML at all. .val() returns a String. To cast a String to an integer put + in front of it. To cast to a floating point Number use parseFloat().
$(function(){
$('#f1,[name=sessiontypepayment],[name=extrapeople]').change(function(){
$('#total').text('$'+(parseFloat($('[name=sessiontypepayment]:checked').val())+parseFloat($('[name=extrapeople]:checked').val())).toFixed(2));
$('#f2').val($('#f1').val());
});
});
To divide by 2 it's /2
As a newbie you should get into the practice of using external <script src so it will get cached into your Browser Memory, for faster load time when your Client revisits your site.

How can I count the total number of inputs with values on a page?

I'm hoping for a super simple validation script that matches total inputs on a form to total inputs with values on a form. Can you help explain why the following doesn't work, and suggest a working solution?
Fiddle: http://jsfiddle.net/d7DDu/
Fill out one or more of the inputs and click "submit". I want to see the number of filled out inputs as the result. So far it only shows 0.
HTML:
<input type="text" name="one">
<input type="text" name="two">
<input type="text" name="three">
<textarea name="four"></textarea>
<button id="btn-submit">Submit</button>
<div id="count"></div>
JS:
$('#btn-submit').bind('click', function() {
var filledInputs = $(':input[value]').length;
$('#count').html(filledInputs);
});
[value] refers to the value attribute, which is very different to the value property.
The property is updated as you type, the attribute stays the same. This means you can do elem.value = elem.getAttribute("value") to "reset" a form element, by the way.
Personally, I'd do something like this:
var filledInputs = $(':input').filter(function() {return !!this.value;}).length;
Try this: http://jsfiddle.net/justincook/d7DDu/1/
$('#btn-submit').bind('click', function() {
var x = 0;
$(':input').each(function(){
if(this.value.length > 0){ x++; };
});
$('#count').html(x);
});

More than 3-Way Checkbox

I want to implement an country-selection-input. In other words, I've got a form with a 25x25px flag, which I want to be clickable - say, german as default, first click changes it to netherlands, second to swiss or w/e.
The last chosen value needs to be in my POST-Array with the other values of the form.
I've tried to accomplish this using 3-Way checkboxes with javascript, but I'm going to need more than 3 options.
Any idea on how to do this? I've thought about an input select, hiding everything but the current value - but I don't know how to submit this to change to the next value.
Thanks in advance for any input, and please don't judge me for such a question - this is my first js/html/css project. :-)
You can do something like this:
HTML
<form method="POST">
<img src="german.png" onclick="switchCountry(this);"/>
<input id="country" name="country" type="hidden" value="german" />
<input type="submit" value="Submit" />
</form>
JavaScript
var countries = ['german', 'netherlands', 'swiss'];
var switchCountry = function(img) {
var input = document.getElementById('country'),
oldValue = input.getAttribute('value'),
newValue = countries[(countries.indexOf(oldValue) + 1) % countries.length];
// Switch input value that will be posted with form
input.setAttribute('value', newValue);
// Switch graphical representation of country
img.setAttribute('src', newValue + '.png');
};
Example here http://jsbin.com/alasip/1/edit

Categories

Resources