Booking calculator using Javascript - javascript

I am trying to create a calculator to calculate the price of selected objects in this form. But the problem I am facing, is my lack of skill within Javascript.
Currently I have created a very simple setup, but it is still alot of job to be done to make it work, or at least that is what I believe.
Then comes my question, I want it to be able to calculate depending on currently selected objects, and amount of days one wish to stay.
As of right now, the only thing I've got going is the very last textbox, there it displays the objects selected on the checkboxes. What I want it to do is to be able to display every object selected into it together with a total price.
example: "You wish to order [selectDestination] for [days] with [selectRom] single rooms and [selectRom2] double rooms. Wish/wish not to rent equipment depending on what is clicked on in checkboxes. For total [endPrice]"
I know I am asking for a lot here. Any help is more than welcome. But if anything seem unclear or too broad to ask about. Please leave a comment below and I'll respond and try to make it more obvious what I am asking for.
JSFIDDLE
https://jsfiddle.net/sa6bLukq/1/
var select = document.getElementById("selectDestinasjon");
var options = [{
"place": "Konsberg",
"price": "$20"
}, {
"place": "Trysil",
"price": "$30"
}, {
"place": "Beitostølen",
"price": "$40"
}];
for (var i = 0; i < options.length; i++) {
var opt = options[i];
var el = document.createElement("option");
el.textContent = opt.place;
el.value = opt.price;
select.appendChild(el);
}
var select = document.getElementById("selectRom");
var select2 = document.getElementById("selectRom2");
var options = ["1", "2", "3"];
for (var i = 0; i < options.length; i++) {
var opt = options[i];
var el = document.createElement("option");
el.textContent = opt;
el.value = opt;
var el2 = document.createElement("option");
el2.textContent = opt;
el2.value = opt;
select.appendChild(el);
select2.appendChild(el2);
}
function myFunction() {
var coffee = document.forms[0];
var txt = "";
var i;
for (i = 0; i < coffee.length; i++) {
if (coffee[i].checked) {
txt = txt + coffee[i].value + " ";
}
}
document.getElementById("order").value = "You wish to order: " + txt;
}
<div>
<form action="">
<br><b>Where do you want to go</b>
<br>
<select id="selectDestinasjon">
<option>Choose a destination</option>
</select>
<br><b>Pick a booking date</b>
<br>
<input type="date">
<br><b>Amount of days you wish to stay</b>
<br>
<input type="number">
<br><b>How many single rooms? </b>
<br>
<select id="selectRom">
<option>How many single rooms?</option>
</select>
<br><b>How many double rooms?</b>
<br>
<select id="selectRom2">
<option>How many double rooms?</option>
</select>
<br>Skipass 200kr:
<input type="checkbox" name="coffee" value="Skipass">
<br>Ski Equipment 1000kr:
<input type="checkbox" name="coffee" value="Ski Equipment">
<br>
<input type="button" onclick="myFunction()" value="Confirm order">
<br>
<input type="text" id="order" size="50">
</div>
<div id="totalPrice"></div>
</form>

I try something, with what i understood. My english is limited, so maybe i miss-understood something. But there is my solution :
First add "id" and "data-price" attribute to each element, for select them easily, then set a data-price for calcul tour total-price.
I also change your "order" field to textarea for better display.
<div>
<form action="">
<br><b>Where do you want to go</b>
<br><select id="selectDestinasjon">
<option>Choose a destination</option>
</select>
<br><b>Pick a booking date</b>
<br><input type="date" id="date">
<br><b>Amount of days you wish to stay</b>
<br><input type="number" id="number" data-price="20">
<br><b>How many single rooms? </b>
<br><select id="selectRom" data-price="12">
<option>How many single rooms?</option>
</select>
<br><b>How many double rooms?</b>
<br><select id="selectRom2" data-price="15">
<option>How many double rooms?</option>
</select>
<br>Skipass 200kr:<input type="checkbox" id="skipass" value="Skipass" data-price="45">
<br>Ski Equipment 1000kr:<input type="checkbox" id="equipment" value="Ski Equipment" data-price="100">
<br>
<input type="button" id="myb" value="Confirm order">
<br>
<textarea id="order" cols="35" rows="7"></textarea>
</form>
<div id="totalPrice"></div>
</div>
Then the Javascrip/Jquery :
I kept your select initialiation, I just remove the "$" to price on you option.
And i rewrite "myFunction" for calculationg total, and write on a single string, every selected item :
$("#myb").click(function() {
var price = 0;
var txt = "";
txt += "You wish to order "+$("#selectDestinasjon option:selected").text();
price = $("#selectDestinasjon").val();
txt += " the "+$("#date").val();
txt += " for "+$("#number").val()+" days";
price *= $("#number").val();
txt += " with "+$("#selectRom option:selected").text()+ " single rooms";
price += $("#selectRom").data("price")*parseFloat($("#selectRom option:selected").text());
txt += " and "+$("#selectRom2 option:selected").text()+ " double rooms.";
price += $("#selectRom2").data("price")*parseFloat($("#selectRom2 option:selected").text());
if ($("#skipass").prop("checked") && $("#equipment").prop("checked") ) {
txt += " Wish a skipass and equipment to rent.";
price += $("#skipass").data("price")+$("#equipment").data("price");
} else if ($("#skipass").prop("checked") ) {
txt += " Wish a skipass.";
price += $("#skipass").data("price");
} else if ($("#equipment").prop("checked") ) {
txt += " Wish to rent equipment.";
price += $("#equipment").data("price");
} else {
txt += " Wish not to rent equipement.";
}
$("#order").val(txt);
$("#totalPrice").text(price+"$");
})
You can try this solution on JSFiddle

Related

how do I check dynamically generated radio input value

I have to generate multiple input fields dynamically for each time user clicks "add" button and I was successfully able to get them. Each contact should have this radio input field in different different name so I've created a name in an array form.
Here's what I have so far and I wonder how I'm supposed to get the radio value for each person:
var options = '';
var count = 0;
var maxfields = 4;
$('button#add').click(function() {
options = '<p>Visit Type:
<label class="radio-inline">
<input type="radio" class="c_visittype' + count +'" name="c_visittype[]" value="Student" required>Student</label>
<label class="radio-inline">
<input type="radio" class="c_visittype' + count +'" name="c_visittype[]" value="Visitor" required>Visitor</label> </p>';
if(count < maxfields){
count++;
$(options).fadeIn("slow").appendTo('.companion');
return false;
}
});
$('.c_visittype' + count).on('click', function(){
$('input:radio[name="c_visittype"]').attr('checked', 'checked');
});
Each person should get a choice of either 'student' or 'visitor' and I have to get this value for multiple persons whenever more person fields created.The reason why I put field's name as an array is to iterate it in the next page by php.
<script src="http://code.jquery.com/jquery-2.2.4.min.js" integrity="sha256-BbhdlvQf/xTY9gja0Dq3HiwQF8LaCRTXxZKRutelT44=" crossorigin="anonymous"></script>
<script>
$( document ).ready(function() {
var options = '';
var count = 0;
var maxfields = 4;
$('button#add').click(function() {
var options = '<p style="display: none">Visit Type:<label class="radio-inline"> <input type="radio" class="c_visittype' + count +'" name="c_visittype' + count +'[]" value="Student" required>Student</label> <label class="radio-inline"><input type="radio" class="c_visittype' + count +'" name="c_visittype' + count +'[]" value="Visitor" required>Visitor</label> </p>';
if(count < maxfields){
count++;
$('.companion').append(options);
$(".companion p:last").fadeIn();
}
});
});
</script>
<button id="add">add</button>
<div class="companion">
</div>
$('input[name=c_visittype[]]:checked').val();
That's how you access the value of a checked radio button with jQuery.
var inputValues = [];
$('.c_visittype:checked').each(function() {
inputValues.push($(this).val());
});
// Your code using inputValues
For update on changes:
$(function() {
$('.c_visittype').click(function(){
// Insert code here
}
)});
Make sure to move the numbering from the class attribute to the name attribute (like it was, everything was part of the same set of options). Also, put the whole string on 1 line.

Real Time Calculations?

I have searched through all of SOF and couldn't find any topic that matches my problem.
I have written an HTML form that I will use PHP to process later, but I have some options in the form that a user can choose. Here is the HTML code
<label for="FIELD6">Model Type: </label><br>
<input type="radio" id="basemodel" name="FIELD6" value="Normal Model" checked onclick="doMath()" />Normal Model<br>
<input type="radio" id="workshopmodel" name="FIELD6" value="Workshop Model" onclick="doMath()" data-clicked="no" />Workshop Model
<p id="total"></p>
So the user can choose between a Normal and Workshop Model. I am trying to set it so that when the user checks the workshopmodel radio button, it adds to the total price (specified in paragraph tags). Here is my attempt at my barely-known language, jQuery:
function doMath() {
var basePrice = 15;
var baseModel = 0;
var customModel = 5;
var modelTotal = ;
function workshopModel() {
if(getElementById("workshopmodel").click(function() {
modelTotal = basePrice + customModel;
}
}
function defaultModel() {
if(getElementById("basemodel").click(function() {
modelTotal = total basePrice + baseModel;
}
}
}
$("#total").html('<font color="black">Total Price:</font><font color="#09ff00">' + workshopModel() + '');
So I am trying to make it add to the basePrice in real time, and then print it in place of the ID marked "total" every time the user makes a change in selection (in real-time). So if the user chooses workshopmodel, the script will add 15 and 5, resulting in 20, and if they choose basemodel, the script will add 15 and 0, resulting in 15. I left the variable modelTotal undefined as it should be defined later on in the script. Can anyone help me out with this?
This should work how you want. Also, does not require jQuery.
function doMath() {
var basePrice = 15;
var baseModel = 0;
var customModel = 5;
var modelTotal;
if (document.querySelector('input[name="FIELD6"]:checked').value == "Normal Model") {
modelTotal = basePrice + customModel;
}
if (document.querySelector('input[name="FIELD6"]:checked').value == "Workshop Model") {
modelTotal = basePrice + baseModel;
}
console.log(modelTotal);
document.getElementById('total').innerHTML = '<span style="color:black">Total Price:' + modelTotal + '</span>';
}
<label for="FIELD6">Model Type:</label>
<br>
<input type="radio" id="basemodel" name="FIELD6" value="Normal Model" onclick="doMath()" />Normal Model
<br>
<input type="radio" id="workshopmodel" name="FIELD6" value="Workshop Model" onclick="doMath()" />Workshop Model
<div id="total"></div>
Here is a working example of what I think you are asking for.
<label for="FIELD6">Model Type:</label><br>
<input type="radio" id="basemodel" name="FIELD6" value="Normal Model" checked onclick="doMath(this)" />Normal Model<br>
<input type="radio" id="workshopmodel" name="FIELD6" value="Workshop Model" onclick="doMath(this)" data-clicked="no" />Workshop Model
<p id="total"></p>
<script type="text/javascript">
function doMath(ele) {
var total = 15;
if($(ele).attr('id') === 'workshopmodel') {
total += 5;
}
$("#total").html('<font color="black">Total Price:</font><font color="#09ff00">' + total);
}
</script>

correct use of select and js together? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
I am trying to use select to give users a option of two things. 1 option is owner the other option is is non owner. i want to be able to ask them different questions if they are owner or not. i want them to be able to enter there answers numerically 1-10, and give them feedback based on the answers. ill try to make it super clear if i can. one question with two options. when that is selected the owner or non owner questions will be asked and added i have include a fiddle with what i have. I am all over the place, and have no idea don't mind me. if someone can show me on that works that would be great!!! change anything in it, just want it to work. http://jsfiddle.net/philyphil/CcVsz/11/
<select class="myOptions">
<option data-val="" selected>Pick an option</option>
<option data-val="owner">Owner</option>
<option data-val="not-owner">Not Owner</option>
</select>
I'd suggest, to handle the summation, changing the jQuery to:
$('#butt').click(function () {
/* this gets an array of the numbers contained within visible
input elements */
var nums = $('.list input:visible').map(function () {
return parseInt(this.value, 10);
}),
// initialises the total variable:
total = 0;
/* iterates over the numbers contained within the array,
adding them to the 'total' */
for (var i = 0, len = nums.length; i < len; i++) {
total += nums[i];
}
var msg = '';
if (isNaN(total)) {
msg = 'Input three numbers, please...';
} else if (total < 30) {
msg = "That's bad, should be higher...";
} else if (total > 40) {
msg = "That's bad, should be lower...";
} else {
msg = "You got it... Nice work.";
}
$('#output').text(msg);
});
And also not using the id attribute to select the elements to sum, instead using class-names:
<div class="list owner">
<p>a</p>
<input class="numbers" type="text" size="2" />
<br/>
<p>b</p>
<input class="numbers" type="text" size="2" />
<br/>
<p>c</p>
<input class="numbers" type="text" size="2" />
<br/>
<!-- questions for owners -->
</div>
<div class="list not-owner">
<p>x</p>
<input class="numbers" type="text" size="2" />
<br/>
<p>y</p>
<input class="numbers" type="text" size="2" />
<br/>
<p>z</p>
<input class="numbers" type="text" size="2" />
<br/>
<!-- questions for non-owners -->
</div>
JS Fiddle demo.
To test if someone is, or says they are, the owner:
var total = 0,
isOwner = $.trim($('.myOptions option:selected').val()) === 'owner';
if (isOwner) {
console.log("It's the owner");
}
The above jQuery is coupled to a select element in which the option elements have values:
<select class="myOptions">
<option value="-1" data-val="" selected>Pick an option</option>
<option value="owner" data-val="owner">Owner</option>
<option value="not-owner" data-val="not-owner">Not Owner</option>
</select>
JS Fiddle demo.
References:
jQuery.trim().
map().
:selected selector.
:visible selector.
Your selector was wrong inside click handler for 'not owner' btw IDs must be unique on context page. Best way is to use class instead of IDs and check for visible boxes:
$('.myOptions').change(function(){
$('.list').removeClass('active')
.filter('.' + $('.myOptions').children('option:selected').attr('data-val'))
.addClass('active');
});
/* want to say if owner do this
when I un-comment this it breaks
var qbc = $('#owner')
var c = $('#myOptions')
if $(c == qbc){
prompt("worked!!!!")
}
*/
$('#butt').click(function () {
var $boxOne = $('.box:visible').eq(0);
var k1 = parseInt($boxOne.val(), 10);
var $boxTwo = $('.box:visible').eq(1);
var k2 = parseInt($boxTwo.val(), 10);
var $boxThree = $('.box:visible').eq(2);
var k3 = parseInt($boxThree.val(), 10);
var total = k1 + k2 + k3;
var msg = '';
if (isNaN(total)) {
msg = 'Input three numbers, please...';
} else if (total < 30) {
msg = "That's bad, should be higher...";
} else if (total > 40) {
msg = "That's bad, should be lower...";
} else {
msg = "You got it... Nice work.";
}
$('#output').text(msg);
});
/* else i will change question number and do same thing */
DEMO

dropdown selection will not work with text only numbers used in JS for calculation of total

I have a form that only captures following fields.(see below) I need to revise it, so that field "formdesc" (form description) captures what was selected in the dropdown as text only. But now there is an options id = [0, 1, 2,3] that are used for price point in JS to calculate total ammount purchased.
HTML:
<form action="http://" method="get" name="form">
<input id="forminv" type="hidden" name="forminv" value="StudentOrg"> (fixed value)
<input id="formbal" type="hidden" name="formbal" value="0"> (this pulls total from id=tot)
<input type="text" name="formfname"> (this pulls first name)
<input type="text" name="formlname"> (this pulls last name)
<type="text" name="formid"> (this for a student number)
<select id="apparelType" name="formdesc"> (this should pull value from selection)
<option selected value="na">Select</option>
<option value="0">T-Shirt</option> (I need to change this value to “shirt”)
<option value="1">Shorts</option> (here too, but can't work with JS below)
<option value="2">Hat</option> (here too)
<option value="3">Bag</option> (here too)
<input id="numb" type="number" name="formterm"> (this pulls quantity, and changes total)
<id="tot"<Total: $0.00 >
<input type="submit" value=" Make a Credit Card Payment">
</form>
JS:
$(document).ready(function () {
$('#numb').keyup(function () {
var appVal = new Array();
appVal[0] = 15; (if I change this, stops working)
appVal[1] = 20;
appVal[2] = 25;
appVal[3] = 30;
var cost = 0;
var fmapVal = $('#apparelType').val();
if (fmapVal == 'na') {
alert('Please select an apparel type.');
} else {
cost = appVal[fmapVal];
};
//alert(cost);
var getNumb = $('#numb').val();
var baseTotal = cost * getNumb;
var getTax = baseTotal * .06;
var getTotal = baseTotal + getTax;
$('#tot').html('Total: $' + etTotal.toFixed(2));
$('#formbal').val(getTotal.toFixed(2));
});
});
Here is working fiddle
change $('#tot').html() to $('#tot').val()
If you require the selected items text, then use;
var txt = $('#apparelType').find('option:selected').text();

javascript how to add textboxs' values and titles to textarea

I have this html:
<input type="radio" name="r1" value="v1"><input name="asd1" title="text1" id="asd1"><br>
<input type="radio" name="r2" value="v2"><input name="asd2" title="text1" id="asd2"><br>
<input type="button" name="but1">
<textarea rows=6 cols=80 name="conclus" id="idConclus">
</textarea><br><br>
Is there a way on js to fill textarea with titles and values of inputs by selecting some of them and clicking a button?
e.g.: "text1 - value1, text2 - value2" etc.
thanks for material.
mmm... Felix King, in your examples the button updates the form. and if i need to put one testfield 1, then put some text in textarea manually, and then again textfield 2 and so on? i mean, without updating the textarea?
getElementById is your friend :-)
<script>
getValues = new function() {
var myTextArea = document.getElementById('idConclus');
var radio1 = document.getElementById('asd1');
var radio2 = document.getElementById('asd2');
myTextArea.value = radio1.title + ' - ' + radio1.value + ' ,'
+ radio2.title + ' - ' + radio2.value;
}
</script>
<input type="radio" name="r1" value="v1">
<input type="text" name="asd1" title="text1" id="asd1"><br>
<input type="radio" name="r2" value="v2">
<input type="text" name="asd2" title="text1" id="asd2"><br>
<input type="button" name="but1" handler = getValues>
I suggest you read about JavaScript and forms.
Assuming you have this HTML:
<form name="data">
<input name="asd1" title="text1" id="asd1"><br>
<input name="asd2" title="text2" id="asd2"><br>
<input type="button" name="but1" value="update">
<textarea rows=6 cols=80 name="conclus" id="idConclus"></textarea>
</form>
you can do this:
var inputs = ['asd1', 'asd2'];
var form = document.data;
var button = form.but1;
var textarea = form.conclus;
button.addEventListener('click', function() {
var text = Array();
for(var i = 0, length = inputs.length; i < length; i++) {
var input = form[inputs[i]];
text.push(input.title + " - " + input.value);
}
textarea.value = text.join(' ');
}, false);​
See a live example here: http://jsfiddle.net/6kbtH/
Update:
If you want to control which values are put into the textbox, I would use checkboxes, give them the same name and the name of the input as value like so:
<input type="checkbox" name="take" value="asd1"><input name="asd1" title="text1" id="asd1">
<input type="checkbox" name="take" value="asd2"><input name="asd2" title="text2" id="asd2">
Then you can loop with nearly the same code over those values:
var form = document.data;
var inputs = form.take;
var button = form.but1;
var textarea = form.conclus;
button.addEventListener('click', function() {
var text = Array();
for(var i = 0, length = inputs.length; i < length; i++) {
if(inputs[i].checked) {
var input = form[inputs[i].value];
text.push(input.title + " - " + input.value);
}
}
textarea.value = text.join(' ');
}, false);​
Live example: http://jsfiddle.net/sJdqb/
Note: You have to take care of cross-browser issues regarding attaching the event listener yourself if you don't use a JavaScript library. The examples I gave will work in Firefox and WebKit-based browsers.

Categories