How to calculate value from different function - javascript

I'm trying to calculate several values from an option selected.
<label>Processor</label> </br>
<form action="3.php" method="POST">
<select id="proSelect" name="processor" onchange="proSelectValue()">
<option value="0">Pilih Processor</option>
<?php echo $pro_option;?>
</select>
<input type="text" id="proPrice" readonly placeholder="0"></br></br>
<label>Motherboard</label></br>
<select id="moboSelect" name="motherboard" onchange="moboSelectValue()">
<option value="0">Pilih Motherboard</option>
<?php echo $mobo_option;?>
</select>
<input type="text" id="moboPrice" readonly placeholder="0"></br></br>
There the options is show, and if the option selected then the value of the options is shown in the id="proPrice" and id="moboPrice".
And the javascript for the value on the id="proPrice" is
function proSelectValue() {
var selObj = document.getElementById("proSelect");
var selValue = selObj.options[selObj.selectedIndex].value;
document.getElementById("proPrice").value = selValue;
}
function moboSelectValue() {
var selObj = document.getElementById("moboSelect");
var selValue = selObj.options[selObj.selectedIndex].value;
document.getElementById("moboPrice").value = selValue;
}
Now I wanted to calculate all of the value and show in this input
<label>Total Harga</label>
<input type="text" id="totalPrice" readonly>
How do i calculate the all of the value?

You can create another function to calculate the total and call that function inside both the event handler function.
Demo:
function proSelectValue() {
var selObj = document.getElementById("proSelect");
var selValue = selObj.options[selObj.selectedIndex].value;
document.getElementById("proPrice").value = selValue;
total();
}
function moboSelectValue() {
var selObj = document.getElementById("moboSelect");
var selValue = selObj.options[selObj.selectedIndex].value;
document.getElementById("moboPrice").value = selValue;
total();
}
function total(){
var total = Number(document.getElementById("proPrice").value) + Number(document.getElementById("moboSelect").value);
document.getElementById("totalPrice").value = total;
}
<label>Processor</label> <br>
<form action="3.php" method="POST">
<select id="proSelect" name="processor" onchange="proSelectValue()">
<option value="0">Pilih Processor</option>
<option value="1">Pilih Processor 2</option>
<option value="2">Pilih Processor 3</option>
</select>
<input type="text" id="proPrice" readonly placeholder="0"><br> <br>
<label>Motherboard</label><br>
<select id="moboSelect" name="motherboard" onchange="moboSelectValue()">
<option value="0">Pilih Motherboard </option>
<option value="1">Pilih Motherboard 2</option>
<option value="2">Pilih Motherboard 3</option>
</select>
<input type="text" id="moboPrice" readonly placeholder="0"> <br><br>
<label>Total Harga</label>
<input type="text" id="totalPrice" readonly />
</form>

Related

textarea stays empty despite setting its .innerHTML

I have 2 fields from which i select some values to be concatenated and posted in a div from which, on submit, i save into a database.
So i select values from 'tags1' and 'tags2' and after i push the button 'adauga' the concatendated values show in the textarea with id 'd11'. Up untill now everythign works fine, untill i press the button 'Clear' to clear the div from values. After that if i try to add values again it does not work, nothing is displayed in the 'd11' div.
Below is the html and the script:
<select name="tehnologie[]" id="tags2" size="13" multiple = "multiple">
<option value="GSM">GSM</option>
<option value="UMTS">UMTS</option>
<option value="LTE">LTE</option>
<option value="NR (5G)">NR (5G)</option>
<option value="Radiodifuziune AM">Radiodifuziune AM</option>
<option value="Radiodifuziune FM">Radiodifuziune FM</option>
<option value="TV digital">TV digital</option>
<option value="TV analogic">TV analogic</option>
<option value="PMR/PAMR">PMR/PAMR</option>
<option value="Satelit">Satelit</option>
<option value="Aero">Aero</option>
<option value="RAmator">RAmator</option>
<option value="Alte aplicatii radio">Alte aplicatii radio</option>
</select>
<input name="banda_buffer" type="number" list="frecvente" id="tags1" >
<datalist id="frecvente">
<option value="800">800</option>
<option value="900">900</option>
<option value="1800">1800</option>
<option value="2100">2100</option>
<option value="2600">2600</option>
</datalist>
<input hidden type="text" id="tags3" >
<input type="button" id="adauga" onClick="myFunction1();" name="adauga" value="+" />
<textarea id="d11" name="banda" rows="5" cols="300" readonly class="form-control input-md"></textarea>
<button type="button" onclick="ClearFields();">Clear</button>
<input type="submit" id="submit" name="submit" onClick="alerta();" value="Salveaza" class="btn btn-primary">
And the js:
var cpvuri1=[];
var AreaToDisplay1=document.getElementById('d11');
function myFunction1(){
var text1=document.getElementById('tags1').value;
var text2=document.getElementById('tags2').value;
var text3= text2 +' - '+ text1;
cpvuri1.push(text3);
AreaToDisplay1.innerHTML=cpvuri1;
}
function ClearFields() {
document.getElementById("d11").value = "";
document.getElementById("tags1").value = "";
document.getElementById("tags2").value = "";
document.getElementById("tags3").value = "";
cpvuri1=[];
}
function alerta() {
document.getElementById("tags3").value = cpvuri1;
}
You can use value rather than innerHTML
function myFunction1(){
var text1=document.getElementById('tags1').value;
var text2=document.getElementById('tags2').value;
var text3= text2 +' - '+ text1;
cpvuri1.push(text3);
AreaToDisplay1.value=cpvuri1;
}

Multiply input value with select option data attribute

I have the following code that is not working the way i want it to, apparently, am trying to multiply select option data attributes with input text area values but instead select option value are being used. I need to figure out why its so.
Here is my code;
<input id="count" min="1" value="1" class ="txtMult form-control" type="number" name="txtEmmail" />
<input type="text" value="" class ="txtMult" name="txtEmmail"/>
<span class="multTotal"></span>
<select class="selectpicker">
<option value="1" data-cubics='1'>multiply with 1</option>
<option value="5" data-cubics='5'>multiply with 5</option>
</select>
<span id="grandTotal">250</span>
$(function(){
$('.txtMult').change(function(){
var p=$(this).parent().parent()
var m=p.find('input.txtMult')
var mul=parseInt($(m[0]).val()*$(m[1]).val()).toFixed(2)
var res=p.find('.multTotal')
res.html(mul);
var total=0;
$('.multTotal').each(function(){
total+=parseInt($(this).html());
})
parseInt(total).toFixed(2);
$('#grandTotal').html(parseInt(total).toFixed(2));
});
})
$('.selectpicker').change(function() {
calcVal();
});
function calcVal(){
$(this).data('cubics')*$('.multTotal').html();
$("#grandTotal").html($(this).data('cubics')*$('.multTotal').html())
}
// call on document load
calcVal();
Don't use .html() to get the values, use .text() instead.
You need to get the selected option using this:
$("#grandTotal").html($(this).children(':checked')
$(function() {
$('.txtMult').change(function() {
var p = $(this).parent().parent()
var m = p.find('input.txtMult')
var mul = parseInt($(m[0]).val() * $(m[1]).val()).toFixed(2)
var res = p.find('.multTotal')
res.html(mul);
var total = 0;
$('.multTotal').each(function() {
total += parseInt($(this).text());
})
parseInt(total).toFixed(2);
$('#grandTotal').html(parseInt(total).toFixed(2));
});
})
$('.selectpicker').change(calcVal);
function calcVal() {
$("#grandTotal").html($(this).children(':checked').data('cubics') * $('.multTotal').text().trim())
}
// call on document load
calcVal();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
<div>
<input id="count" min="1" value="1" class="txtMult form-control" type="number" name="txtEmmail" />
<input type="text" value="" class="txtMult" name="txtEmmail" />
<span class="multTotal"></span>
<select class="selectpicker">
<option value="1" data-cubics='1'>multiply with 1</option>
<option value="5" data-cubics='5'>multiply with 5</option>
</select>
<span id="grandTotal">250</span>
</div>
</div>

Adding Comma To Javascript Output

I'm trying to run a function that will add commas to the results of a form that multiplies the values of two drop down boxes.
The function I have works on an html element such as p class="points" but it is not working on the output generated by id="results2"
Any idea what I'm doing wrong?
<form name="myForm" id="myForm">
<label>Select Amount</label>
<select id="box1" type="select" oninput="calculate()" />
<option value="choose" selected>Choose</option>
<option value="15000">$15,000</option>
<option value="20000">$20,000</option>
<option value="25000">$25,000</option>
<option value="30000">$30,000</option>
<option value="35000">$35,000</option>
</select>
<label>Select Type</label>
<select id="box2" type="select" oninput="calculate()" />
<option value="x" selected>Choose</option>
<option value=".21">1</option>
<option value=".40">2</option>
</select>
<input class="button" type="submit" value="Submit" id="multiply">
<p>
<strong>here are the results:</strong>
</p>
<h3>
<strong>$<span id="result2"></span></strong> a week
</h3>
</form>
<script>
$(document).ready(function(){
$('#multiply').click(function(event){
event.preventDefault();
var n1=$('#box1').val();
var n2=$('#box2').val();
var result=Math.round(n1*n2*25);
$('#resultholder4').fadeIn(200);
$('#number1').append(n1);
$('#number2').append(n2);
$('#result2').text(result);
});
});
</script>
<script type="text/javascript">
function numberWithCommas(x) {
return x.toString().replace(/\B(?=(?:\d{3})+(?!\d))/g, ",");
}
$('.points').each(function() {
var v_pound = $(this).html();
v_pound = numberWithCommas(v_pound);
$(this).html(v_pound)
})
</script>
You are just not calling numberWithCommas() on your result. Here is your code with one change (and I had to add the calculate function that is referenced by the select's oninput).
$(document).ready(function() {
$('#multiply').click(function(event) {
event.preventDefault();
var n1=$('#box1').val();
var n2=$('#box2').val();
var result=Math.round(n1*n2*25);
$('#resultholder4').fadeIn(200);
$('#number1').append(n1);
$('#number2').append(n2);
// added call to numberWithCommas, line had been:
//$('#result2').text(result);
// changed to:
$('#result2').text(numberWithCommas(result)); // <--------
});
});
function numberWithCommas(x) {
return x.toString().replace(/\B(?=(?:\d{3})+(?!\d))/g, ",");
}
$('.points').each(function() {
var v_pound = $(this).html();
v_pound = numberWithCommas(v_pound);
$(this).html(v_pound)
});
function calculate() {
// ?
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form name="myForm" id="myForm">
<label>Select Amount</label>
<select id="box1" type="select" oninput="calculate()" />
<option value="choose" selected>Choose</option>
<option value="15000">$15,000</option>
<option value="20000">$20,000</option>
<option value="25000">$25,000</option>
<option value="30000">$30,000</option>
<option value="35000">$35,000</option>
</select>
<label>Select Type</label>
<select id="box2" type="select" oninput="calculate()" />
<option value="x" selected>Choose</option>
<option value=".21">1</option>
<option value=".40">2</option>
</select>
<input class="button" type="submit" value="Submit" id="multiply">
<p>
<strong>here are the results:</strong>
</p>
<h3>
<strong>$<span id="result2"></span></strong> a week
</h3>
</form>
Here is a quick dirty method:
function numberWithCommas(x) {
x = x.toString();
var pattern = /(-?\d+)(\d{3})/;
while (pattern.test(x))
x = x.replace(pattern, "$1,$2");
return x;
}
should add that this was provided by Peter Mortensen:
How to print a number with commas as thousands separators in JavaScript
here is a demo:
https://jsfiddle.net/keinchy/dx7qg4nk/1/
-cheers
Your event handler for #multiply never actually calls numberWithCommas. Replace
$('#result2').text(result);
with
$('#result2').text(numberWithCommas(result));
and it should work.

Doing Calculations with multiple options in Javascript

I'm quite new to Javascript and have started to do simple calculations, but have run into a barrier with <select>.
I want the code to get what the user has selected in the drop-down menu and multiply the number in the "How many nights?" box. The answer will be displayed in the textbox below. The options in the select menu all have prices tied to them.
< script language = "javascript" >
function calculate() {
var val1 = parseInt(document.getElementById("Nights").value);
var val1 = parseInt(document.getElementById("House").value);
var House1 = 100;
var House2 = 175;
var House3 = 150;
var House4 = 135;
var House5 = 150;
var House6 = 120;
var House7 = 180;
var House8 = 120;
var House9 = 80;
var House10 = 105;
var ansD = document.getElementById("answer");
ansD.value = House * Nights;
}
} < /script>
<html>
<head>
<title>Calculate cost</title>
</head>
<body>
<select required class="textfield" name="House" id="House">
<option value="">None</option>
<option value="House1">House 1</option>
<option value="House2">House 2</option>
<option value="House3">House 3</option>
<option value="House4">House 4</option>
<option value="House5">House 5</option>
<option value="House6">House 6</option>
<option value="House7">House 7</option>
<option value="House8">House 8</option>
<option value="House9">House 9</option>
<option value="House10">House 10</option>
</select>
<br />
<br />How many nights?
<input type="text" id="Nights" name="Nights" value="1" />
<input type="button" name="Submit" value="Cost" onclick="javascript:addNumbers()" />
<br />
<br />Your stay will cost £
<input type="text" id="answer" name="answer" value="" />
</body>
</html>
With setting the value for the houses inside the select dropdown, you help yourself quite a lot. You can see that the javascript part is greatly reduced, and that it is actually quite simple to sum the values together
Also, it is important that your button is not of type submit, as it would then submit your script, and well, you don't see the result of your calculate function then ;)
function calculate() {
var houseEl = document.getElementById('houseType'),
nightEl = document.getElementById('nightsCount'),
resultEl = document.getElementById('result');
if (houseEl.selectedIndex < 0 || parseInt(nightEl.value) < 0) {
resultEl.innerHTML = 'n/a';
return;
}
resultEl.innerHTML = parseInt(houseEl.options[houseEl.selectedIndex].value) * parseInt(nightEl.value);
}
window.addEventListener('load', function() {
document.getElementById('btnCalculate').addEventListener('click', calculate);
});
<select id="houseType">
<option value="0">None</option>
<option value="100">House 1</option>
<option value="150">House 2</option>
</select>
<input type="number" min="1" value="1" id="nightsCount" />
<button type="button" id="btnCalculate">Calculate</button>
<div>
The total amount for your stay would be <span id="result"></span> €
</div>
I suggest you to use an Object that keeps "key"-"value" pairs.
a is an Object, it contains keys such as House1, House2 and prices as values.
a[val2] will give you a price for staying one night in the hotel.
if None value (or other not available in the Map value) comes from the form,
isNaN() check will give true and No price message will be printed out.
<html>
<head>
<title>Calculate cost</title>
<script language = "javascript">
function calculate() {
var val1 = parseInt(document.getElementById("Nights").value);
var val2 = document.getElementById("House").value;
var a={};
var prices = [ 100, 175, 150, 135, 150, 120, 180, 120, 80, 105 ];
for (var i = 1; i < 11; i++)
{
a["House"+i] = prices[i];
}
var ansD = document.getElementById("answer");
if (isNaN(a[val2]))
ansD.value="No price!";
else
ansD.value = val1 * a[val2];
}
</script>
</head>
<body>
<select required class="textfield" name="House" id="House">
<option value="">None</option>
<option value="House1">House 1</option>
<option value="House2">House 2</option>
<option value="House3">House 3</option>
<option value="House4">House 4</option>
<option value="House5">House 5</option>
<option value="House6">House 6</option>
<option value="House7">House 7</option>
<option value="House8">House 8</option>
<option value="House9">House 9</option>
<option value="House10">House 10</option>
</select>
<br />
<br />How many nights?
<input type="text" id="Nights" name="Nights" value="1" />
<input type="button" name="Submit" value="Cost" onclick="calculate()" />
<br />
<br />Your stay will cost £
<input type="text" id="answer" name="answer" value="" />
</body>
</html>

how to get multiple inputs spontaneously in JavaScript

I am new to JavaScript and I am trying to make an html page with JavaScript inside it.
The idea is that, when someone selects the value of option from the select, it should generate automatically the fields of firstName, lastName etc depending on the number which is selected. If one is selected then it should have one field of firstName, lastName and if two is selected then it should generate two fields dynamically.
<select id="noOfAuthor" multiple="multiple">
<option value="one">1</option>
<option value="two">2</option>
<option value="three">3</option>
<option value="four">4</option>
<option value="five">5</option>
</select>
If someone selects one then below there should be one code of
Title Name <input type="text" name="txtTitle1">
Author Name <input type="text" name="txtAuthor1" >
Copy right<input type="text" name="txtCopyrightYear1">
If we selects “2” then there should be two code asking
Title Name <input type="text" name="txtTitle1">
Author Name <input type="text" name="txtAuthor1" >
Copy right<input type="text" name="txtCopyrightYear1">
Title Name <input type="text" name="txtTitle2">
Author Name <input type="text" name="txtAuthor2" >
Copy right<input type="text" name="txtCopyrightYear2">
And so on and so forth.
I tried to write a code for doing this, but it is not working.
<html>
<head>
<title>Book Collection</title>
<script language="JavaScript">
function WBook(bookName, writer, yearPublished)
{
this.Title = bookName;
this.Author = writer;
this.CopyrightYear = yearPublished;
}
function showBook(oneBook)
{
var no = showChoices();
var i ;
for(i =0; i<no; i++)
{
document.frmBooks.txtTitle[i].value = oneBook.Title[i];
document.frmBooks.txtAuthor[i].value = oneBook.Author[i];
document.frmBooks.txtCopyrightYear[i].value = oneBook.CopyrightYear[i];
}
}
function displayCollection()
{
var aBook = new WBook("Visual C++ From the Ground Up", "John Paul Mueller", 1998);
showBook(aBook);
}
function showChoices(){
var noOfAuthor = document.getElementById("noOfAuthor");
var result = " You selected";
result += " \n";
for(i=0; i<noOfAuthor.length;i++){
currentOption = noOfAuthor[i];
if(currentOption.selected == true){
result += currentOption.value + "\n";
}
}
result += " \n";
alert(result);
return(result);
}
</Script>
</head>
<body>
<h1>Book Collection</h1>
<form name="frmBooks">
<input type="hidden" name="id" value="" required="true" /><br> <br>
<select id="noOfAuthor" >
<option value="one">1</option>
<option value="two">2</option>
<option value="three">3</option>
<option value="four">4</option>
<option value="five">5</option>
</select>
<button type="button" onclick="showChoices()">Submit</button>
Title Name <input type="text" name="txtTitle1">
Author Name <input type="text" name="txtAuthor1" >
Copy right<input type="text" name="txtCopyrightYear1">
Title Name <input type="text" name="txtTitle2">
Author Name <input type="text" name="txtAuthor2" >
Copy right<input type="text" name="txtCopyrightYear2">
<p><input type="button" value="Show Collection" name="btnShow" onClick="displayCollection()">
</form>
</body>
</html>
You can solve it like this (jsFiddle demo):
<html>
<head>
<title>Book Collection</title>
<script language="JavaScript">
function WBook(bookName, writer, yearPublished)
{
this.Title = bookName;
this.Author = writer;
this.CopyrightYear = yearPublished;
}
function showBook(oneBook)
{
var no = showChoices();
var i ;
for(i =0; i<no; i++)
{
document.frmBooks.txtTitle[i].value = oneBook.Title[i];
document.frmBooks.txtAuthor[i].value = oneBook.Author[i];
document.frmBooks.txtCopyrightYear[i].value = oneBook.CopyrightYear[i];
}
}
function displayCollection()
{
var aBook = new WBook("Visual C++ From the Ground Up", "John Paul Mueller", 1998);
showBook(aBook);
}
function showChoices(){
var noOfAuthor = document.getElementById("noOfAuthor");
var result = " You selected";
result += " \n";
result += noOfAuthor.value
for(i=1; i <= noOfAuthor.length;i++){
if(i <= noOfAuthor.value){
document.getElementById("inputs" + i).style.display = 'block';
} else {
document.getElementById("inputs" + i).style.display = 'none';
}
}
result += " \n";
alert(result);
return(result);
}
</Script>
</head>
<body>
<h1>Book Collection</h1>
<form name="frmBooks">
<input type="hidden" name="id" value="" required="true" /><br> <br>
<select id="noOfAuthor" >
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
</select>
<button type="button" onclick="showChoices()">Submit</button>
<div id="inputs1">
Title Name <input type="text" name="txtTitle1">
Author Name <input type="text" name="txtAuthor1" >
Copy right<input type="text" name="txtCopyrightYear1">
</div>
<div id="inputs2" style="display:none">
Title Name <input type="text" name="txtTitle2">
Author Name <input type="text" name="txtAuthor2" >
Copy right<input type="text" name="txtCopyrightYear2">
</div>
<div id="inputs3" style="display:none">
Title Name <input type="text" name="txtTitle3">
Author Name <input type="text" name="txtAuthor3" >
Copy right<input type="text" name="txtCopyrightYear3">
</div>
<div id="inputs4" style="display:none">
Title Name <input type="text" name="txtTitle4">
Author Name <input type="text" name="txtAuthor4" >
Copy right<input type="text" name="txtCopyrightYear4">
</div>
<div id="inputs5" style="display:none">
Title Name <input type="text" name="txtTitle5">
Author Name <input type="text" name="txtAuthor5" >
Copy right<input type="text" name="txtCopyrightYear5">
</div>
<p><input type="button" value="Show Collection" name="btnShow" onClick="displayCollection()">
</form>
</body>
</html>
very simple with jquery:
<select id="noOfAuthor" multiple="multiple">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
</select>
<div id="inputs"></div>
$( document ).ready(function() {
$("select#noOfAuthor > option").click(function() {
$( "#noOfAuthor" ).attr("disabled", true);
var howMuch = parseInt($( "#noOfAuthor" ).val());
for(i = 0; i < howMuch; i++) {
$( "#inputs" ).append('Title Name: <input type="text" name="txtTitle' + i + '"><br>Author Name: <input type="text" name="txtAuthor' + i + '"><br>Copy right: <input type="text" name="txtCopyrightYear' + i + '"><br><hr />');
}
});
});
So you get inputs as the selected number.
the Three first willl be:
name="txtTitle0"
name="txtAuthor0"
name="txtCopyrightYear0"
demo: http://jsfiddle.net/mxgbc/3/
I would generate the inputs and labels dynamically. This is a pure javascript example, without using jQuery. I can provide a jQuery solution if you need it.
Example http://jsfiddle.net/A62qA/1 // basic select menu
Example http://jsfiddle.net/A62qA/2/ // mutiple choice select menu
HTML
<select id="noOfAuthor" onchange="inputFunction(this)">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
</select>
<div id="myContainer"></div>
JavaScript
function createInputs(i) {
var myContainer = document.getElementById("myContainer");
var titleName = document.createElement("input");
titleName.setAttribute('name', 'txtTitle1' + i);
var label = document.createElement("Label");
label.innerHTML = "Title Name";
myContainer.appendChild(label);
myContainer.appendChild(titleName);
var authorName = document.createElement("input");
authorName.setAttribute('name', 'txtAuthor1' + i);
var label = document.createElement("Label");
label.innerHTML = "Author Name";
myContainer.appendChild(label);
myContainer.appendChild(authorName);
var copyRight = document.createElement("input");
copyRight.setAttribute('name', 'txtCopyrightYear1' + i);
var label = document.createElement("Label");
label.innerHTML = "CopyRight";
myContainer.appendChild(label);
myContainer.appendChild(copyRight);
}
function inputFunction(y) {
var y = y.value;
var myContainer = document.getElementById("myContainer");
for (var i = 0; i < y; i++) {
createInputs(i);
}
}

Categories