I'm quite new to javascript and need help to firstly get value from checkbox (which should tell the code that user going to get -25%) and then calculate the price with discount. At the moment my code let's user to input number (how much is wanted) and then javascript calculates the number and outputs it to <p id=test>...</p>.
I have tried different kind of codes for discount and outputting it but because of my knowledge (at least I think so) they won't work. I can't see if javascript is getting some information from checkbox or not.
PS: The most important for me is to get javascript understanding what is the value of checkbox. Calculating I guess isn't hard :)
My html code looks like this:
<body>
<p style="color:green">Check the checkbox to get discount</p>
<h2 style="display:inline;">
<input type="checkbox" name="checkbox1" id="checkbox1" class="css-checkbox" value="25" />Item:</h2> LiPo Battery 3S2P 5200mAh
<p style=float:right>Quantity:
<input type="text" id="Text" value="">
<button onclick="funktsioon()">Price</button></p><br>
Item price: <input type="hidden" id="price" value="29.30"><b>29.30</b> euro
</p>
<br>
<b><p id="test">Full price: ... euro</p></b>
<b><P id="test3">Price with discount: ... euro</p></b>
And javascript:
<script> function funktsioon() {
var price = document.getElementById("price").value; var mult = document.getElementById("Text").value;
var fprice = (mult*price).toFixed(2).fontcolor("green");
document.getElementById("test").innerHTML =
"Full price: " + fprice + " euro";
var disc = document.getElementById(checkbox1).value;
...need some code here... i guess.
document.getElementById("test3").innerHTML =
"Price with discount: " + some_kind_of_var_i_guess? + " euro";
} </script>
You can get the state of a checkbox with .checked
var disc = 1.0
if (document.getElementById("checkbox1").checked){
disc = 0.25;
}
var pWithDisc = fprice * disc;
document.getElementById("test3").innerHTML = "Price with discount: " + pWithDisc + " euro";
Related
I have two text input text box and I want to do the total of whatever no entered by the user. Below is my code:
$(document).ready(function(){
var total = 0;
$(".test").on("input", function(){
// Print entered value in a div box
total += parseInt($(this).val());
$("#result").text( total);
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<p><input type="text" class="test" placeholder="Type something..." id="myInput"></p>
<p><input type="text" class="test" placeholder="Type something..." id="myInput"></p>
<div id="result"></div>
When I input 10 first then it takes 11, then if I enter 100 then it takes 111, I am no getting why this happening. Where I am making an error, guide me?
On your code when you enter the first digit it's been calculated to the total because of your code total += parseInt($(this).val()). for example, if your press first digit as 1 then at that time total is updating as total = total + 1 which equals 1, on the second keypress, for example, take 0, then your input value becomes 10. it is calculating to the current total value as total = total + 10. that's why you are getting 11 as answer
Try like this.
$(document).ready(function(){
$(".test").on("input", function(){
let total = 0;
$('.test').each(function() {
if (!isNaN(parseInt($(this).val()))) {
total += parseInt($(this).val());
}
});
$("#result").text(total);
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<p><input type="text" class="test" placeholder="Type something..." id="myInput1"></p>
<p><input type="text" class="test" placeholder="Type something..." id="myInput2"></p>
<div id="result"></div>
The reason it didn't showed you the result you want to, is because the calculation is wrong. You now add the number to the total, every time one input field changes. So if you type 123, it takes 0 + 1 , then 1 + 12, then 13 + 123 so you'll have 136 as result.
I wrote a possible solution for your question. The code is in the fiddle below.
You could add a function where you calculate the total of all input fields (may be more than 2, it's generic).
function calculateTotal(){
var total = 0;
$(".test").each(function( index ) {
var value = $(this).val();
if(value == ""){
return;
}
total += parseInt(value);
});
$("#result").text(total);
}
And on the change of your input fields, you just execute that function.
$(document).ready(function(){
$(".test").on("input", function(){
calculateTotal();
});
});
Your example is in this fiddle: https://jsfiddle.net/xL6hgder/2/
You just update total with that input value that you're trying to change.
For getting the total for both input values you have to take both values and add it with the total.
Try below code-
$(document).ready(function() {
$(".test").on("change", function() {
var total = 0;
$('.test').each(function() {
if (!isNaN(parseInt($(this).val()))) {
total += parseInt($(this).val());
}
});
// Print entered value in a div box
$("#result").text(total);
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<p><input type="text" class="test" placeholder="Type something..." id="myInput"></p>
<p><input type="text" class="test" placeholder="Type something..." id="myInput"></p>
<div id="result"></div>
$(document).ready(function () {
$(".test").on('input', function () {
var total = parseInt($("#result").text());
total = parseInt($("#myInput").val()) + parseInt($("#myInput1").val());
$("#result").text(total);
});
});
<p><input type="text" class="test" placeholder="Type something..." id="myInput" /></p>
<p><input type="text" class="test" placeholder="Type something..." id="myInput1" /></p>
<div id="result"></div>
Use the change event instead of the input event. It will only fire when the value is "commited", instead of every keystroke. See mdn for details.
I have 2 text fields: "Earnings" and "Deductions",earnings has some components like HRA,Basic pay etc and deductions also has some..
I have another 2 text fields "Total Earnings" and "Total Deductions"
Total Earnings = earning component1 + earning component2
Total Deductions = deduction component1 + deduction component2
What i want is i need to write two functions for showing the results in Total Earnings and Total Deductions.I mean if i enter the values for "Earnings" and "deductions", those should automatically reflect in "Total Earnings" and "Total Deductions"
You just need to set the keyup function for the textbox.
<script type="text/javascript">
function setval()
{
document.getElementById('totearng').value = document.getElementById('earng').value;
document.getElementById('totdedtn').value = document.getElementById('dedtn').value;
}
</script>
<body>
Earning : <input type="text" id='earng' onkeyup="setval()"/><br/>
Deduction : <input type="text" id='dedtn' onkeyup="setval()"/><br/>
Total Earning : <input type="text" id='totearng'/><br/>
Total Deduction : <input type="text" id='totdedtn'/>
</body>
use javascript for calculation
function cal()
{
//calculation part here
//var total_earning = your result
//Earnings textbox
document.getElementById(textfield_name1).value = total_earning;
//Deductionstextbox
document.getElementById(textfield_name2).value = total_earning;
}
<!DOCTYPE html>
<html>
<head>
<script>
function displayResult()
{
var x=(document.getElementById("deduction").value);
var y=(document.getElementById("collection").value);
document.getElementById("total").value=Number(x)+Number(y);
}
</script>
</head>
<body>
<form>
Deduction: <input type="text" id="deduction" onchange="displayResult()">
Collection: <input type="text" id="collection" onchange="displayResult()">
Total:<input type="text" id="total">
</form>
</body>
</html>
Try like this
I am new to Javascript and I am having trouble figuring out why this code does not work the way I think it should.
Here is my Javascript code. All I'm trying to do (for now) is take the values from these text boxes and drop downs, and concatenate them.
<script>
function AdvancedSearch () {
var color = document.getElementByID("AdvSearchColor").value;
var ply = document.getElementByID("AdvSearchPly").value;
var cat = document.getElementByID("AdvSearchCategory").value;
var size = document.getElementByID("AdvSearchSize").value;
var description = document.getElementByID("AdvSearchDescription").value;
var fullsearch = ply + color + cat + description + size;
}
</script>
<form id="advsearach" onsubmit="AdvancedSearch()">
Product Color: <input type="text" name="productcolor" id="AdvSearchProductColor"><br>
Product Ply Rating: <input type="text" name="productply" id="AdvSearchPlyRating"><br>
Product Category: <input type="text" name="productcategory" id="AdvSearchProductCategory"><br>
Product Size: <input type="text" name="productsize" id="AdvSearchProductSize"><br>
Product Description: <input type="text" name="productdescription" id="AdvSearchProductDescription"><br>
<input type="button" onclick="javascript:AdvancedSearch()" value="Search!">
</form>
So I'm having trouble on the trivial of problems, just debugging this and getting it to work. Spent a few hours on it already.. Thanks for anyone who takes the time to look at this, it will probably save me a lot of time in the long run and that is a very nice thing to do.
you should use document.getElementById instead of document.getElementByID. There's a typo "Id" != "ID".
And IDs of your form MUST match those in javascript form o.O
<form id="advsearach">
Product Color: <input type="text" name="productcolor" id="AdvSearchColor"><br>
Product Ply Rating: <input type="text" name="productply" id="AdvSearchPly"><br>
Product Category: <input type="text" name="productcategory" id="AdvSearchCategory"><br>
Product Size: <input type="text" name="productsize" id="AdvSearchSize"><br>
Product Description: <input type="text" name="productdescription" id="AdvSearchDescription"><br>
<input type="button" onclick="javascript:AdvancedSearch()" value="Search!">
</form>
<script>
function AdvancedSearch () {
var color = document.getElementById("AdvSearchColor").value,
ply = document.getElementById("AdvSearchPly").value,
cat = document.getElementById("AdvSearchCategory").value,
size = document.getElementById("AdvSearchSize").value,
description = document.getElementById("AdvSearchDescription").value,
fullsearch = ply + color + cat + description + size;
console.log(fullsearch);
}
</script>
I am trying to make a simple code generator using inputs added by the user.
It will go something like this:
"predefined code" + UserInput1 + "predefined code" + "UserInput2"
I assume I will need to assign variables to the UserInput which will change depending on what it writes in the text box.
I will need also a function that will show the output as I press the button in a text area
But I lack the skills to compose it since I'm a very started in JavaScript.
Thank you in advance for your help!
Try below code
DEMO
<input type="text" id="a">
<input type="text" id="b">
<div id="result"></div>
<input type="button" value="See Code" onclick="magicCode();">
function magicCode() {
document.getElementById("result").innerHTML = "Hello " + document.getElementById("a").value + " Welcome " + document.getElementById("b").value;
}
I'm creating a form using html form controls and javascript to help streamline some processes at work. I've temporarily put the form online here.
In one section of the form, I have a text box associated with a radio button. The other radio buttons in the section display their values properly when the "Display" button is hit at the bottom of the page, but the radio button with the text box does not. It seems that I'm not correctly assigning the value of the text box to the value of the radio button. What am I doing wrong?
Here's the javascript:
<script LANGUAGE="JavaScript" type="text/javascript">
function display() {
for (var i=0; i < document.form2.paymenttype.length; i++)
{
if (document.form2.paymenttype[i].checked)
{
var radio_paymenttype_val = document.form2.paymenttype[i].value;
}
}
for (var i=0; i < document.form2.contracts.length; i++)
{
if (document.form2.contracts[i].checked)
{
var radio_contracts_val = document.form2.contracts[i].value;
}
}
DispWin = window.open('','NewWin', 'toolbar=no,status=no,scrollbars=yes,width=800,height=600')
message = "<h2>Royalty Advance Payment Letter</h2>";
message += "<hr />";
message += "<span STYLE=\'font-family: Garamond\'>";
message += "<p>" + document.form2.agentfirstname.value + " " + document.form2.agentlastname.value + "<br />";
message += document.form2.agencyname.value + "<br />";
message += document.form2.agentaddress1.value + "<br />";
message += document.form2.agentaddress2.value + "<br />";
message += document.form2.agentcity.value + ", " + document.form2.agentstate.value + " " + document.form2.agentzip.value + "<br />";
message += document.form2.agentcountry.value + "<br />";
message += "</p>";
message += "<p>Dear " + document.form2.agentfirstname.value + ",</p>";
message += "<p>Please find enclosed a check in the amount of $";
message += document.form2.paymentamount.value + " representing the amount due upon ";
message += radio_paymenttype_val + " ";
message += document.form2.authorfirstname.value + " ";
message += document.form2.authorlastname.value + "'s <em>";
message += document.form2.booktitle.value + "</em>.";
message += radio_contracts_val + "</p>";
message += "<p>Regards,<br /><br /><br /><br />My Name<br />Associate Editor</p>";
message += "</span>";
DispWin.document.write(message);
}
</script>
And here's the HTML for that section:
<div class="required">
<fieldset>
<legend>Payment Type:</legend>
<label for="payment_sig" class="labelRadio"><input type="radio" name="paymenttype" id="payment_sig" class="inputRadio" value="signature for" /> Signature</label>
<label for="payment_danda" class="labelRadio"><input type="radio" name="paymenttype" id="payment_danda" class="inputRadio" value="delivery and acceptance of" /> Delivery & Acceptance</label>
<label for="payment_pub" class="labelRadio"><input type="radio" name="paymenttype" id="payment_pub" class="inputRadio" value="publication of" /> Publication</label>
<label for="payment_pbpub" class="labelRadio"><input type="radio" name="paymenttype" id="payment_pbpub" class="inputRadio" value="paperback publication of" /> Paperback Publication</label>
<label for="payment_otherlabel" class="labelRadio"><input type="radio" name="paymenttype" id="payment_otherlabel" class="inputRadio" onclick="this.form.payment_other.focus()" onfocus="this.form.payment_other.focus()" value="" checked="checked" /> Other:</label>
<input type="text" name="payment_other" id="payment_other" class="inputText" value="" />
<small>Remember, this text will be in the middle of a sentence. This text should always end in "of" or "for."</small>
</fieldset>
</div>
Your first for loop goes through and finds the value of the correct radio selected, but in the case of "other" you're not going to have a value assigned. You need to determine when other is selected, then assign radio_paymenttype_val the value of the text box instead. Something to the effect of:
for (var i=0; i < document.form2.paymenttype.length; i++)
{
if (document.form2.paymenttype[i].checked)
{
// assuming "other" is the only case where this radio's value property would be empty.
var radio_paymenttype_val = (document.form2.paymenttype[i].value != ''
? document.form2.paymenttype[i].value
: document.form2.payment_other.value);
}
}
Update
So excuse the delay (took your form field and ran with it). This is (I believe) what you're looking for. Some things to note:
I don't do any form validation. This is something you probably want to tinker with, and can be pretty simple. In the .click() event, just check something like the following (or you can get more elaborate):
if($('#agentfirstname').val()==''){
alert('Missing First Name');
return;
}
Also, I use something fairly new to jQuery, templates. This makes it easier than var+='html html'+var+'html'; (as you can witness in the <script> tag with the ID 'FormTemplate`).
Finally, I tested this on FF4, Chrome4 and IE8 and it should work, but let me know if it doesn't on whatever environment you use.
Anyways, here's the code, hope this helps!
Place inside <head> element of your document
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js"></script>
<Script src="http://ajax.microsoft.com/ajax/jquery.templates/beta1/jquery.tmpl.min.js"></script>
<script type="text/javascript">
$(function(){
// bind to the "display" button ('.' means this is a class name reference)
$('.inputSubmit').click(function(e){
// build up the template values
var tmplData = [{
agentFirstName: $('#agentfirstname').val(),
agentLastName: $('#agentlastname').val(),
agencyName: $('#agencyname').val(),
agentAddr1: $('#agentaddress1').val(),
agentAddr2: $('#agentaddress2').val(),
agentCity: $('#agentcity').val(),
agentState: $('#agentstate').val(),
agentZip: $('#agentzip').val(),
paymentAmount: '$'+$('#paymentamount').val(),
paymentType: $('input[name="paymenttype"]:checked').val() != '' ? $('input[name="paymenttype"]:checked').val() : $('#payment_other').val(),
authorFirstName: $('#authorfirstname').val(),
authorLastName: $('#authorlastname').val(),
bookTitle: $('#booktitle').val(),
contracts: $('input[name="contracts"]:checked').val()
}];
// create the template
var template = $('#FormTemplate').template('letter');
// Create a fake div we can push the template to and pass off to popup
var tmplDiv = document.createElement('div');
$(tmplDiv).attr('id','TemplateDiv').css('display','none');
// Write the template and push it off
$.tmpl('letter', tmplData).appendTo(tmplDiv);
// create the window and populate it with the template
var hWindow = window.open('','NewWin', 'toolbar=no,status=no,scrollbars=yes,width=800,height=600');
hWindow.document.write(tmplDiv.innerHTML);
// stop any further action
e.preventDefault();
});
});
</script>
Place inside <body> element of your document:
<script id="FormTemplate" type="text/x-jquery-tmpl">
<html>
<head>
<title>Letter</title>
</head>
<body>
<h2>Royalty Advance Payment Letter</h2>
<hr />
<span type="font-family:Garamond;">
<p>
${agentFirstName} ${agentLastName}<br />
${agencyName}<br />
${agentAddr1}<br />
${agentAddr2}<br />
${agentCity}, ${agentState} ${agentZip}<br />
</p>
<p>
Dear ${agentFirstName},
</p>
<p>
Please find enclosed a check in the amount of ${paymentAmount} representing the amount due upon ${paymentType}
${authorFirstName} ${authorLastName}'s <em>${bookTitle}</em>.
${contracts}
</p>
<p>
Regards,<br />
<br />
<br />
<br />
Margaret Maloney<br />
Associate Editor
</p>
</span>
</body>
</html>
</script>
Could you simply set a onblur() for the payment_other to set the radio option's value?
<input type="text" name="payment_other" id="payment_other" class="inputText" value="" onblur="document.getElementById('payment_otherlabel').value=this.value;" />
Then if it is ever set, it will automatically copy the value into the radio option. Then when your Display() function is called, I would think the value would be set.
(Realized I missed the semi-colon at the end of the onblur="" statement.)
Have you tried this yet?