Calculate value/price based on rows in textarea - javascript

Im trying to calculate a price that is depending on how many rows you use in a textarea. This is what i have come up with so far. The only problem is its won't calculate, i think i have looked at it to much or something.
Let me explain a little, first of its for som textads.
There is a flatfee for minimum of 2 rows and then additional 10 for each new row, with a maximum of 10 rows.
var flatFee = '70.00';
var perRow = '10.00';
function rowCount(area, maxlength) {
//var area = document.getElementById("textarea-1")
// trim trailing return char if exists
var text = area.value.replace(/\s+$/g, "");
var split = text.split("\n");
if (split.length > maxlength) {
split = split.slice(0, maxlength);
area.value = split.join('\n');
alert("You can not enter more than " + maxlength.toString() + " lines");
}
return false;
}
var div = $('span.rowCount');
jQuery('textarea#textarea-1').on('input', function($) {
var count = rowCount(this.value);
div.html(count.rows);
/*var additionalFees = perRow*count.rows;*/
if (count.rows > 2) {
var additionalFees = perRow * (count.rows - 2);
}
var total = parseFloat(flatFee) + parseFloat(additionalFees);
$('span.total').html(parseFloat(total.toString()).toFixed(2));
/*var total = $('span.total');*/
console.log(total);
});
<textarea cols="32" rows="10" maxlenght="320" class="form-control" name="textarea-1" id="textarea-1" placeholder="Type or paste your prompt here."></textarea>
<p>You have <span class="rowCount">0</span> rows.Total <span class="total">0</p>

Modified your function a bit. Works now
var flatFee = '70.00';
var perRow = '10.00';
function rowCount(area, maxlength) {
//var area = document.getElementById("textarea-1")
// trim trailing return char if exists
var text = area.replace(/\s+$/g, "");
var split = text.split("\n");
if (split.length > maxlength) {
split = split.slice(0, maxlength);
area.value = split.join('\n');
alert("You can not enter more than " + maxlength.toString() + " lines");
}
return {rows:split.length};
}
var div = $('span.rowCount');
jQuery('textarea#textarea-1').on('input', function($) {
var count = rowCount(this.value);
div.html(count.rows);
/*var additionalFees = perRow*count.rows;*/
var additionalFees=0;
if (count.rows > 2) {
additionalFees = perRow * (count.rows - 2);
}
var total = parseFloat(flatFee) + parseFloat(additionalFees);
//$('span.total').html(total.toString().toFixed(2));
/*var total = $('span.total');*/
console.log(total);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<textarea cols="32" rows="10" maxlenght="320" class="form-control" name="textarea-1" id="textarea-1" placeholder="Type or paste your prompt here."></textarea>
<p>You have <span class="rowCount">0</span> rows.Total <span class="total">0</span></p>

https://jsfiddle.net/5mcbt8ua/4/
HTML
Flat Rate / First 2 rows: 70<BR>
Additional Rows: 10 per row
<div id="compute" contenteditable="true" style="border:1px solid #ccc;">
</div>
Total Price: <font id="total">0</font>
<BR>
<font id="msg"></font>
jQuery
var flatFee = 70;
var perRow = 10;
$('#compute').keypress(function(){
$("#msg").html('Press enter to compute');
var count = $(this).find('div').length;
var total = flatFee;
if(count > 1)
{
total = flatFee + (count * 10) - 10;
}
$("#total").html(total);
});

Related

Loop through the sum of the two inputs until in doubled (javascript)

I am stuck here with duch issue. There are 2 two entry boxes are for an amount and an interest rate (%).
If you click on the button, the page will show an overview of the balance until the amount have to be doubled.
Taking a simple numbers forexample 10 - is amount and 4 - is 4% intereste rate. So the result have to stop on amount of 20.
document.getElementById("button").onclick = loop;
var inputB = document.getElementById("inputB");
var inputC = document.getElementById("inputC");
var result = document.getElementById("result")
function loop() {
var s = inputB.value;
var r = inputC.value;
var doubleS = s * 2;
for (var i = 1; i <= doubleS; i++) {
s = ((r / 100 + 1) * s);
result.innerHTML += s + "<br>";
}
}
<! DOCTYPE html>
<html>
<body>
<br>
<input type="text" id="inputB" value="10"><br>
<input type="text" id="inputC" value="4"><br><br>
<button id="button">Klik</button>
<p> De ingevoerde resultaten: </p>
<p id="result"></p>
<script async src="oefin1.js"></script>
</body>
</html>
The issue is with your for loop bounds.
This will loop doubleX number of times: for (var i = 0; i < doubleX; i++)
This will loop until x surpasses doubleX: for (;x < doubleX;), which btw is better written with a while loop: while (x < doubleX)
document.getElementById("button").onclick = loop;
var inputB = document.getElementById("inputB");
var inputC = document.getElementById("inputC");
var result = document.getElementById("result")
function loop() {
var s = inputB.value;
var r = inputC.value;
var doubleS = s * 2;
result.innerHTML = '';
while (s < doubleS) {
s = ((r / 100 + 1) * s);
result.innerHTML += s + "<br>";
}
}
<input type="text" id="inputB" value="10"><br>
<input type="text" id="inputC" value="4"><br><br>
<button id="button">Klik</button>
<p> De ingevoerde resultaten: </p>
<p id="result"></p>
Easiest way is to just use a for loop without the convoluted math with s in the middle:
function loop() {
var s = inputB.value;
var r = inputC.value;
var doubleS = s * 2;
for (var i = s; i <= doubleS; i *= ((r / 100) + 1)) {
result.innerHTML += i + "<br>";
}
}
use a while loop and check is the value of s is bigger than or equal to doubleS
document.getElementById("button").onclick = loop;
var inputB = document.getElementById("inputB");
var inputC = document.getElementById("inputC");
var result = document.getElementById("result")
function loop() {
var s = inputB.value;
var r = inputC.value;
var doubleS = s * 2;
while(true) {
s = ((r / 100 + 1) * s);
result.innerHTML += s + "<br>";
if(s >= doubleS){
break
}
}
}
<! DOCTYPE html>
<html>
<body>
<br>
<input type="text" id="inputB" value="10"><br>
<input type="text" id="inputC" value="4"><br><br>
<button id="button">Klik</button>
<p> De ingevoerde resultaten: </p>
<p id="result"></p>
<script async src="oefin1.js"></script>
</body>
</html>

Decrement the counter in javascript when hyperlink is typed in a TextArea

I have a textArea in which the Text will be typed and when text is typed the counter will be decreased by 1 for each character typed.. but I want when the landing link is typed in the textArea the counter will be decrement by exactly 16 and after that when normal text is typed again it will be decremented by 1 for each character .... any kind of help will be appreciated thanks
TextArea
var maxLimit = 160;
$(document).ready(function(e) {
$('#msgArea').keyup(function() {
var lengthCount = this.value.length;
if (lengthCount > maxLimit) {
this.value = this.value.substring(0, maxLimit);
var charactersLeft = maxLimit - lengthCount + 1;
$('#msgArea').css('background-color', '#FFFF00');
} else {
var charactersLeft;
var textmsg = document.getElementById('msgArea').value;
var pattern = new RegExp(
'((http|https)(://))?([a-zA-Z0-9]+[.]{1}){2}[a-zA-z0-9]+(/{1}[a-zA-Z0-9]+)*/?',
'i'
);
if (pattern.test(textmsg)) {
lengthCount = lengthCount - 16;
charactersLeft = maxLimit - lengthCount;
} else {
charactersLeft = maxLimit - lengthCount;
$('#spnCharLeft').text(charactersLeft + ' Characters left');
}
}
$('#spnCharLeft').css('display', 'block');
if (lengthCount < maxLimit) {
$('#msgArea').css('background-color', '#fff');
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="col-sm-offset-2 col-sm-10">
<label>Message</label>
<textarea id="msgArea" class="form-control" rows="3"></textarea>
<span id="spnCharLeft"></span>
</div>
var maxLimit = 160;
$(document).ready(function(e) {
$('#msgArea').keyup(function() {
var spanCharLeft = $('#spnCharLeft');
var charactersLeft;
var textmsg = this.value;
var lengthCount = textmsg.length;
var pattern = new RegExp(
'((http|https)(://))?([a-zA-Z0-9]+[.]{1}){2}[a-zA-z0-9]+(/{1}[a-zA-Z0-9]+)*/?',
'ig'
);
var matches = textmsg.match(pattern);
if (!matches) {
matches = [];
}
matches.forEach(matched_string => {
lengthCount = lengthCount - matched_string.length + 16;
});
charactersLeft = maxLimit - lengthCount;
spanCharLeft.text(charactersLeft + ' Characters left');
if (lengthCount < maxLimit) {
$('#msgArea').css('background-color', '#fff');
} else {
this.value = this.value.substring(0, maxLimit);
spanCharLeft.text('0' + ' Characters left');
$('#msgArea').css('background-color', '#fff000');
}
$('#msgArea').css('display', 'block');
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="col-sm-offset-2 col-sm-10">
<label>Message</label>
<textarea id="msgArea" class="form-control" rows="3"></textarea>
<span id="spnCharLeft"></span>
</div>
This should do it. Make note of the use of matches = textmsg.match(pattern). You need to parse your string for each match of the pattern and then increase the lengthCount appropriately lengthCount = lengthCount - matched_string.length + 16. Also note that I've changed the regex to use the g global flag.
PS: I realise that this part is ugly
if(!matches) {
matches = [];
}
I would appreciate edits on that

On mouse hover, display the corresponding sizes of bars, as mentioned in the input field

function draw() {
var nums = document.getElementById("number").value.split(",");
console.log(nums);
var w = 40;
var factor = 20;
var n_max = Math.max.apply(parseInt, nums);
var h_max = factor * n_max;
console.log("h max is " + h_max);
console.log("n max is " + n_max);
//var h_max = Math.max(h);
//var a = parseInt(nums);
//var create = document.getElementById("shape");
for (var i = 0; i <= nums.length; i++) {
//var x = parseInt(nums[i]);
//var final_width = w / x;
var x_cor = (i + 1) * w;
//var y_cor = i * w * 0.5;
var h = factor * nums[i];
console.log(x_cor);
console.log(h);
//console.log(h_max);
var change = document.getElementById("histContainer");
//change.className = 'myClass';
var bar = document.createElement("div");
bar.className = 'myClass';
//var c_change = document.createElement("div2");
//change.appendChild(c_change);
change.appendChild(bar);
console.log(change);
//change.style.x.value = x_cor;
//change.style.y.value = y_cor;
bar.style.position = "absolute";
bar.style.top = (h_max - h) + "px";
//bar.style.transform = "rotate(-1deg)"
bar.style.left = i * w * 1 + "px";
bar.style.backgroundColor = "rgb(1,211,97)";
bar.style.opacity = "0.6";
bar.style.width = w + "px";
bar.style.height = h + "px";
//var color1 = document.getElementById("histContainer");
//var bar_color = document.createElement("div");
//color1.appendChild(change);
//bar.style.color = "rgba(1,211,97,0.6)";
}
}
function color() {
//draw();
var change1 = document.getElementsByClassName('myClass');
for (var i = 0; i < change1.length; i++) {
change1[i].style.backgroundColor = "rgb(255,0,27)";
console.log("Change1 = " + change1[i]);
}
// var bar1 = document.createElement("div2");
// change1.appendChild(bar1);
// console.log(change1);
//change1.style.backgroundColor = "rgb(1,,254,16)";
}
$(document).ready(function() {
$(document).on("mouseover", ".myClass", function() {
//var number = this.nums;
//$(this.nums).text($(this.nums).index());
//$(".myClass").append(nums);
var shade = $(this).css("opacity");
$(this).css("opacity", "1.0");
$(document).on("mouseout", ".myClass", function() {
$(this).css("opacity", shade);
});
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
Number:<input type="text" id="number" /><br>
<input type="button" id="button1" value="Draw" onClick="draw()" /><br>
<input type="button" id="button2" value="Change Color" onClick="color()" /><br>
<div id="histContainer" style="position: relative;"> </div>
<!-- <label for="mouseover" id="label1">Bar Value</label><br>
<input type="text" name="mouseover" id="text2" value="0"/><br> -->
<!-- <input type="button" id="color_change" style="float: right;" value="Change Color" /> -->
My Question is- I have entered some numbers as Input, and corresponding histogram is made according to the input values. Now, I have created mouseover() on each bar, and WANT to display their proportionate sizes, as given in input.
Can you provide me some help? Only thing which i figured out was- I have to call my draw function in the jQuery mouseover.
REFER TO the draw() and jQuery function(last)
I have figured out the answer. It is required that the nums array has to be re-declared again.
Solution Achieved
$(document).ready(function() {
$(document).on("mouseover",".myClass", function(){
//var numbers = $("#number").serialize();
//var number = this.nums;
var nums = document.getElementById("number").value.split(",");
$(this).text(nums[$(this).index()]);
//$(".myClass").append(nums);
var shade = $(this).css("opacity");
$(this).css("opacity", "1.0");
$(document).on("mouseout",".myClass", function() {
$(this).css("opacity", shade);
});
});
});

My variable refused to display in my Div

The country is changing along side the shipping. I could alert my shipping but will refuse to display in my div. What could be wrong? All calculations working well and displays well except for the #usashipping please help. My country changes and give the correct value for the calculation. The shipping fee just will not display.
<!-- language: lang-js -->
<script type="application/javascript">
var price= "";
var userprice="";
var flpay='';
var total='';
var shipping='';
var fees=30.0;
$('#country').change(function() {
var input = $(this).val();
var shipping;
if (input == 40) {
shipping = 10.0;
$('#usashipping').html('10.0');
} else if (input == 236) {
shipping = 10.0;
$('#usashipping').html('10.0');
} else {
shipping = 30.0;
$('#usashipping').html('30.0');
}
if(fees=='') {
$('#fees').html(30);
}
if(flpay=='')
{
$('#flpay').html(2*19.99);
}
if(total=='')
{
var tot=19.99*2.0 +30.0 + shipping;
var total= tot.toFixed(2);
$('#total').html(total);
}
$('.add').click(function() {
var $input = $(this).next();
var currentValue = parseInt($input.val());
var newinput= currentValue + 1;
$('#gems').val(newinput);
(newinput);
if(newinput==1)
{
var np1=(19.99*2.0);
flpay= np1.toFixed(2);
$('#flpay').html(flpay);
var tot= (fees + shipping + flpay);
var total= tot.toFixed(2);
$('#total').html(total);
var newp=19.99;
var price= newp.toFixed(2);
$('#price').html(price);
useprice= 19.99;
}
else if(newinput>1)
{
//useprice=useprice;
var newprice= 19.99 + (9.99*(newinput-1));
var np1 =(2*newprice);
var flpay = np1.toFixed(2);
$('#flpay').html(flpay);
var tot =( fees + shipping + (2*newprice) );
var total= tot.toFixed(2);
$('#usashipping').html(shipping);
$('#total').html(total);
var newp= newprice.toFixed(2);
$('#price').html(newp);
}
// newprice= price * 2;
// $('#price').html(newprice);
});
<!-- language: lang-html -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js">
</script>
<div>
First & Last Months Payment = $<span data-first-last-month-fees="" id="flpay"></span>
</div>
<div>
Shipping Fee = $<span data-shipping-fee="" id="usashipping"></span>
</div>
<div>
Total due today : $<span data-total-due="" id="total"></span>
</div>
Your code should work perfectly, but there are few things that you could improve in your code:
Instead of declaring shipping variable 3 times in each condition, you need to declare it only once, then update it in each condition, and make sure it's stored as a string so it can be displayed correctly in your HTML.
Instead of updating the HTML content of your span in every condition, just update it with the shipping amount in the end.
This is how should be your code:
$('#country').change(function() {
var input = $(this).val();
var shipping;
if (input == 40) {
shipping = '10.0';
} else if (input == 236) {
shipping = '20.0';
} else {
shipping = '30.0';
}
$('#usashipping').html(shipping);
});
Demo:
$('#country').change(function() {
var input = $(this).val();
var shipping;
if (input == 40) {
shipping = '10.0';
} else if (input == 236) {
shipping = '20.0';
} else {
shipping = '30.0';
}
$('#usashipping').html(shipping);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<select id="country">
<option value="40">40</option>
<option value="236">236</option>
<option value="100">100</option>
</select>
<div>
Shipping Fee = $<span data-shipping-fee="" id="usashipping"></span>
</div>
I can see error showing in your code. I found "$('.add').click" inside "$('#country').change". Also "$('#country').change" function you declared local variable "var shipping;" that's why no change on global "shipping;" value but you using it inside "$('#country').change" function. I modified little bit now try with following code and comment reply if not work for you:
var price= "";
var userprice="";
var flpay='';
var total='';
var shipping='';
var fees=30.0;
$('#country').change(function() {
var input = $(this).val();
if (input == 40) {
shipping = 10.0;
$('#usashipping').html('10.0');
} else if (input == 236) {
shipping = 10.0;
$('#usashipping').html('10.0');
} else {
shipping = 30.0;
$('#usashipping').html('30.0');
}
if(fees=='') {
$('#fees').html(30);
}
if(flpay=='')
{
$('#flpay').html(2*19.99);
}
if(total=='')
{
var tot=19.99*2.0 +30.0 + shipping;
var total= tot.toFixed(2);
$('#total').html(total);
}
})
$('.add').click(function () {
var $input = $(this).next();
var currentValue = parseInt($input.val());
var newinput = currentValue + 1;
$('#gems').val(newinput);
(newinput);
if (newinput == 1) {
var np1 = (19.99 * 2.0);
flpay = np1.toFixed(2);
$('#flpay').html(flpay);
var tot = (fees + shipping + flpay);
var total = tot.toFixed(2);
$('#total').html(total);
var newp = 19.99;
var price = newp.toFixed(2);
$('#price').html(price);
useprice = 19.99;
}
else if (newinput > 1) {
//useprice=useprice;
var newprice = 19.99 + (9.99 * (newinput - 1));
var np1 = (2 * newprice);
var flpay = np1.toFixed(2);
$('#flpay').html(flpay);
var tot = (fees + shipping + (2 * newprice));
var total = tot.toFixed(2);
$('#usashipping').html(shipping);
$('#total').html(total);
var newp = newprice.toFixed(2);
$('#price').html(newp);
}
// newprice= price * 2;
// $('#price').html(newprice);
})
I only changed the div id from #usashipping to something else and it works just fine. Maybe #usashippingis now a constant in jquery library.

jQuery slider with input value on drag after refresh

I've found this grate slider which is combo of 4 sliders sharing 100% value. Problem is that it doesn't pick value of input, yet it resets to 25% for each slider every time page is refreshed. Can someone help by making slider picking value of inputs before they determine position of slider knob.
HTML
<div align="center" class="title">Statistiche:</div>
<div id="outer_container">
<div id="container">
<span class='multislider'>Hokuto ShinKen (<input type='text' required name='question_3' class='amount' value='5' data-min='0' data-max='100'/>)
<div class='slider tied'>
</div>
Nanto (<input type='text' required name='question_3' class='amount' value='15' data-min='0' data-max='100'/>)
<div class='slider tied'>
</div>
Gento (<input type='text' required name='question_3' class='amount' value='50' data-min='0' data-max='100'/>)
<div class='slider tied'>
</div>
Artiglio del Monte Taishan (<input type='text' required name='question_3' class='amount' value='30' data-min='0' data-max='100'/>)
<div class='slider tied'></div>
</span>
</div>
</div>
jQuery
var init = true;
var elements = $(".multislider").children(".slider.tied").length;
var MAX = 100;
var inpVal = $('.txt_name').val();
var initValue = (inpVal) >> 0;
//var initValue = (MAX / elements) >> 0;
var InitMod = MAX % elements;
$(".slider.tied").each(function() {
var slidersTied = $(".slider.tied");
var context = $(this);
var input = context.prev(".amount");
var val = input.data('answer');
var min = input.data('min');
var max = input.data('max');
var range = 1;
var proceed = false;
$(this).empty().slider({
value: val,
min: min,
max: max,
range: range,
animate: "slow",
create: function(event, ui){
if (InitMod > 0) {
$(this).slider('value', initValue + 1);
$(this).prev('.amount').val(initValue + 1);
InitMod = InitMod - 1;
}
else
{
$(this).slider('value', initValue);
$(this).prev('.amount').val(initValue);
}
},
slide: function(e, ui) {
// Update display to current value
$(this).prev('.amount').val(ui.value);
var current = ($(this).index() / 2) >> 0;
var total = 0;
var counter = 0
slidersTied.not(this).each(function() {
total += $(this).slider("option", "value");
counter += 1;
});
total += ui.value;
if (total != MAX){
proceed = true;
}
var missing = MAX - total;
console.log("missing: " + missing);
counter = 0;
if(proceed) {
//carico vettore elementi
var elements = [];
slidersTied.each(function() {
elements[counter] = $(this);
counter += 1;
});
var endIndex = counter - 1;
counter = endIndex + 1;
while (missing != 0) {
console.log("current counter: " + counter);
do {
if (counter == 0)
{
counter = endIndex;
}
else
{
counter = counter - 1;
}
} while(counter == current)
console.log("elemento attuale: " + counter);
var value = elements[counter].slider("option", "value");
var result = value + missing;
if (result >= 0)
{
elements[counter].slider('value', result);
elements[counter].prev('.amount').val(result);
missing = 0;
}
else
{
missing = result;
elements[counter].slider('value', 0);
elements[counter].prev('.amount').val(0);
}
}
}
}
});
});
Example
http://jsfiddle.net/vuQz5/116/
Thanks
There are two issues, var val = input.data('answer'); is wrong, there is no such data value what you need is to get the input value like this:
var val = input.val();
val = (val) ? val : 0;
and also use that value in create method instead of initValue there is no need for if condition you only need whatever is in the else clause:
$(this).slider('value', val);
$(this).prev('.amount').val(val);
Check this fiddle

Categories