Please help me, i've the javascript allmost done. Only the last part is very difficult.
I've used the calculator plugin for contact form7, to calculate the BMI, this works perfectly.
To hide the BMIhigh text also works, and the click
Length (cm):
<label id="centi">[number* cm min:130 max: 220]</label>
Hight (kilo):
<label id="kilo">[number* kilo min:40 max:140]</label>
<label id="calcbutton">[calculate_button "calculate"]</label>
<label id="calc">[calculation calculate precision:1 "kilo / ((cm / 100) * (cm / 100))"]</label>
<label id="BMIhigh">
Your BMI is too high
</label>
[submit "Send"]
At the bottom i've got the following code:
// Hide the BMIhigh text field by default
document.getElementById("BMIhigh").style.display = 'none';
// On every 'click' on the calculator call the displayTextField function
document.getElementById("calcbutton").addEventListener("click", displayTextField);
function displayTextField() {
// Get the inserted values for centi and kilo and calculate the BMI again
// for the function without the help of the calculator build in into the extra plugin.
var centimeter = +document.getElementById("centi").value;
var kilogram = +document.getElementById("kilo").value;
var BMIvar = kilogram / ( ( centimeter / 100 ) * ( centimeter / 100 ) );
// If BMIvar higher than 30 it is too high, the text should show.
// THIS LAST PART DOES NOT WORK
if(BMIvar > 30) {
document.getElementById("BMIhigh").style.display = 'block';
} else {
document.getElementById("BMIhigh").style.display = 'none';
}
}
</script> ```
Your variable BMIvar never get evaluated because,
var centimeter = +document.getElementById("centi").value;
var kilogram = +document.getElementById("kilo").value;
these variables are not being populated properly. CF7 converts field tags into <span> encapsulated <input/> fields,
<label id="centi">
<span class="wpcf7-form-control-wrap cm">
<input type="number" name="cm" value="" class="wpcf7-form-control wpcf7-number wpcf7-validates-as-required">
</span>
</label>
and as such getElementById returns the <label/> element and not the <input/> one. element.value only works for <input/> fields. Try instead to use getElementsByName and replace the above 2 lines with,
var centimeter = 1.0*document.getElementsByName("cm")[0].value;
var kilogram = 1.0*document.getElementsByName("kilo")[0].value;
Here is a jsFiddle with a working example.
Related
Here's how it's supposed to work. By default there are two sets of input fields where the percentage fields have a value of 50% each. Now whenever a new input field is added, the percentage field value should be divided between all of them, for example, if there are 3 sets then percentage fields should have 33.33% each. If there are 4 then 25% each. Now this part works perfectly fine.
Now I'm trying to add more features on top of it. I'll just explain the features in brief and the problem associated with it.
When a user clicks on percentage input field, the previous value disappears and the user types a new percentage value and it gets divided between the two input fields. But the issue with this is it adds two "%" signs at the end of the value which the user just typed in.
The second issue is, suppose the user types in a new percentage value in the first or second percentage field and then adds a new input field through Add Field button, the percentages doesn't divide between all the input values. The new input field doesn't take into consideration the new percentage value. One reason I could think of is the percInput variable doesn't get updated somehow.
The third issue is similar to the second one. If the user adds a new input field first and then types in a percentage value in that new input field, then percentage values are not divided at all. This could also be because of percInput variable not being updated. Another issue associated with this is, clicking on the new percentage input field doesn't remove the previous value, like it does on the default fields.
This is a weird one. If the user clicks on the percentage input field but doesn't adds a value and moves on to adding a new field, then the percentage values just divide between all of them.
All of these issues are somewhat related to each other and I have feeling a that they are all because of one variable, which is, percInput. I guess it doesn't get updated when new input fields are added. Previously I used calculatePercentage function to update the percInput variable, where it worked. But it doesn't work when I tried to use it in the situations above.
Here's the code I tried so far:
const form = document.querySelector("form");
const span = document.querySelector("span");
const addBtn = document.querySelector("#addField");
const html = `
<div class="url-pair">
<input type="url" placeholder="3">
<input type="text" class="perc">
<button class="delete-btn" type="button">Delete</button>
</div>
`;
// percentage variable and percentage calculation for the first time
let percInput = document.querySelectorAll('.urls-container .perc');
let percentage = (100 / percInput.length).toFixed(0).toString() + "%";
percInput.forEach((item) => {
item.setAttribute("value", percentage);
});
const removeField = (e) => {
if (!e.target.classList.contains('delete-btn')) return;
e.target.parentElement.remove();
calculatePercentage();
}
// percentage input variable update and percentage calculation
const calculatePercentage = () => {
percInput = document.querySelectorAll('.urls-container .perc');
percentage = (100 / percInput.length).toFixed(0).toString() + "%";
percInput.forEach((item) => {
item.setAttribute("value", percentage);
});
}
// remove a field
form.addEventListener('click', removeField);
// add input field
addBtn.addEventListener('click', () => {
span.insertAdjacentHTML("beforeBegin", html);
calculatePercentage();
});
const percInputChange = function() {
let val = this.value,
$allInputs = $(percInput);
if(val > 100) {
$allInputs.val((100 / $allInputs.length) + "%");
calculatePercentage();
}else {
$(percInput).not(this).val( (100 - val) / ($allInputs.length - 1) + "%");
setTimeout(() => {
this.value = this.value + "%";
}, 500);
calculatePercentage();
return;
}
};
// event listener when user types in a new percentage value
$( percInput ).on('keyup', percInputChange);
// event listener to hide previous input value
$( percInput ).focus(function() {
this.value = "";
});
// event listener to divide the percetange values when the user clicks away
$( percInput ).blur(function() {
if(this.value === ""){
percInput.forEach(item => {
item.value = ( 100 / percInput.length ).toFixed(0).toString() + "%";
return;
});
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form action="#" method="POST">
<div class="urls-container">
<div class="url-pair">
<input type="url" placeholder="1">
<input type="text" class="perc">
<button class="delete-btn" type="button">Delete</button>
</div>
<div class="url-pair">
<input type="url" placeholder="2">
<input type="text" class="perc">
<button class="delete-btn" type="button">Delete</button>
</div>
<span></span>
</div>
<div>
<div>
<button type="button" id="addField">Add Field</button>
</div>
<div>
<button type="submit">Create</button>
</div>
</div>
</form>
I know this post is a weird one with so many problems. But please bear with me as I am still learning and I won't be able to learn if I don't push myself into these complex coding problems and get stuck. I've spent the whole day yesterday trying different methods based on the knowledge I have. The post would be really big if I put all the methods I tried. So please bear with me. Please help a fellow coder in need. Thanks
PS. I used jQuery and JS together which is not the right thing to do. But I will refactor and change them once I fix the issues.
PS.
I am not quite sure what exactly you want to achieve with your script. But I had a go at making a fresh start by removing redundant bits. The following snippet will allow you to add or remove input lines and it will adjust the percentages accordingly.
Maybe you can specifiy how you want the script to react on any user input?
// add flields:
function addfields(){
let all=$('.urls-container'), r=$('div:last',all).clone(),
url=r.find('input[type=url]')[0];
url.placeholder=+url.placeholder+1;
$('.perc',r).removeAttr('data-manual');
all.append(r); calcperc();
}
// even distribution:
function calcperc(){
let fix=$('.perc[data-manual]'),sum=0;
fix.each(function(){sum+=parseFloat(this.value)});
let rest= $('.perc').not(fix);
rest.val(((100-sum)/rest.length).toFixed(2)+'%')
}
// manual distribution:
function recalc(){let inps=$('.perc'),cur=parseFloat(this.value);
if (inps.length>1){
this.value=cur.toFixed(2)+'%'; this.dataset.manual=1;
calcperc();
} else this.value="100%"
}
// delegated event management:
$('form')
.on('submit',function(e){e.preventDefault()}) // de-activate submit for testing
.on('change','.perc',recalc)
.on('click','.delete-btn',function(){$(this).parent().remove();calcperc()})
.on('click','#addField',addfields);
// initial distribution:
calcperc();
<script type="text/javascript" src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
<form action="#" method="POST">
<div class="urls-container">
<div class="url-pair">
<input type="url" placeholder="1">
<input type="text" class="perc">
<button class="delete-btn" type="button">Delete</button>
</div>
<div class="url-pair">
<input type="url" placeholder="2">
<input type="text" class="perc">
<button class="delete-btn" type="button">Delete</button>
</div>
<span></span>
</div>
<div>
<div>
<button type="button" id="addField">Add Field</button>
</div>
<div>
<button type="submit">Create</button>
</div>
</div>
</form>
My curent version of recalc() allows you to overwrite one of the percentage values. All other values will then be adjusted, so the total is 100% again.
Please also note that in my version the recalc() gets fired on the input event and not the keyup event, otherwise the action of adding the percentage sign would seriously interfere with any input attempt by the user.
Edit
The lastet edit involves "marking" manually changed percentages with a data-manual attribute in the input field. This will protect that field from future recalculations. The remaining percentages will be distributed evenly among the non-fixed fields.
Currently i have developed a program that gets the count of all the inputs field and adding up a percentage for the numbers of fields that are filled individually.
what i need now here, i need to assign a number to each input field and when the user fills an input field i need to show it to the user as a " SCORE ".
below is the program i have built.
<html>
<body>
<label> Name </label>
<input class="track"/>
<label> Name </label>
<input class="track"/>
<h5>Profile Strength <span class='perc'>0</span>%</h5>
</body>
</html>
and the JavaScript is
<script>
$('.track').change(function(e) {
update_progress();
});
// supports any number of inputs and calculates done as %
function update_progress() {
var count = $('.track').length;
var length = $('.track').filter(function() {
return this.value;
}).length;
var done = Math.floor(length * (100 / count));
$('.perc').text(done);
$('.meter').width(done + "%");
}
so when you fill the first input field the 'Profile strength' will show 50% as there are only 2 input fields, and when you fill the second input it will show 100%.
i want to show a number instead of a percentage here like
input 1 = 10
input 2 = 20
so when the user fills input 1 his "SCORE" will be 10,
and when the user fills the next input the total must add on and show 30 in real time.
sorry if have confused a few developers but this the only way i understood the assignment i got.
Try the following:
Html:
<html>
<body>
<label> Name </label>
<input class="track" data-score=10 />
<label> Name </label>
<input class="track" data-score=20 />
<h5>Profile Strength <span class='perc'>0</span>%</h5>
<h5>Score <span id="score">0</span></h5>
</body>
</html>
JS:
$('.track').change(function(e) {
update_progress();
});
// supports any number of inputs and calculates done as %
function update_progress() {
var score = 0
$('input.track').each(function(){
var _score = $(this).data("score")
if ($(this).val().length > 0) {
score += _score
}
})
$('#score').text(score)
var count = $('.track').length;
var length = $('.track').filter(function() {
return this.value;
}).length;
var done = Math.floor(length * (100 / count));
$('.perc').text(done);
$('.meter').width(done + "%");
}
Or, a live version https://jsfiddle.net/wmt6cznh/2/
Is this what you want to achieve?
Here is a sample idea.
Amount - discount = amount paid by the customer.
But the customer pay less and the box due need to be increment dynamically.
Can anyone help me please?
Here is a simple version of what I believe you're asking for:
HTML
Price: <input type="text" id="tb-price" />
Discount (%) <input type="text" id="tb-discount" />
Total: <span id="lbl-total" />
Javascript (jQuery required)
$(function(){
// vars
var $tbPrice = $('#tb-price');
var $tbDisc = $('#tb-discount');
var $lblTotal = $('#lbl-total');
// events
$tbPrice.on('input', calc);
$tbDisc.on('input', calc);
// calculation
function calc(){
var x = $tbPrice.val() * ($tbDisc.val() / 100);
var y = $tbPrice.val() - x;
$lblTotal.html(y);
}
});
Example: http://jsfiddle.net/zkhx1z1d/
Do note that there is no validation here and assumes that the user input is clean. Also this should only be used to show the user what they expect to pay, all calculations should be done/verified by the server as suggested by AlienWebguy
Good day,
I have 3 text fields for input.
TotalWeight
CustomUnitWeight
CustomsNumberOfUnit
There should be a validation to make sure TotalCustomWeight matches TotalWeight (neither higher nor lower).
I started playing around trying to construct a function for validating this no luck and looking for assistance
Scenario :
User input total weight of pkg at 30, then put number of custom unit at 2 and the weight at 10. On click the function calculate 2 * 10 = 20 and look at the total weight 30 and compare the total custom weight. In this case 20 does not equal to 30 therfore throw error message.
HTML
<input type="text" name="TotalWeight" id="TotalWeight" />
<input type="text" name="customsNumberOfUnitsUSA" id="CustomsNumberOfUnits" />
<input type="text" name="CustomsUnitWeight" id="CustomsUnitWeight" onChange="ChkWeight();" />
JAVASCRIPT
$(function(ChkWeight){
$('#CustomsUnitWeight').click(function() {
var TotalWeight = document.getElementById('TotalWeight');
var CustomUnitWeight = document.getElementById('CustomsUnitWeight');
var CustomsNumberOfUnit = document.getElementById('CustomsNumberOfUnits');
var TotalCustomWeight = CustomUnitWeight * CustomsNumberOfUnit;
if (TotalWeight != TotalCustomWeight) {
error message "pkg weight does not match total custom weight"
}
});
});
Well everything else is fine in your code just needs to put .value to get value from your input fields and converting string (simple text) to Float type and then calculate and show alert like
<body>
<input type="text" name="TotalWeight" id="TotalWeight" />
<input type="text" name="customsNumberOfUnits" id="CustomsNumberOfUnits"/>
<input type="text" name="CustomsUnitWeight" id="CustomsUnitWeight" onblur="CheckWeight()" />
//I have changed the event as onblur and calling CheckWeight() function defined in javascript below.
</body>
<script type="text/javascrit">
function CheckWeight()
{
var TotalWeight = document.getElementById('TotalWeight').value;
var CustomUnitWeight = document.getElementById('CustomsUnitWeight').value;
var CustomsNumberOfUnit = document.getElementById('CustomsNumberOfUnits').value;
//parsing text value to Float type for multipication
var TotalCustomWeight = parseFloat(CustomUnitWeight) * parseFloat(CustomsNumberOfUnit);
if (TotalWeight != TotalCustomWeight)
{
alert("pkg weight does not match total custom weight");
}
}
</script
and Off course you must need to validate for value to be number before calculation. This works perfect.
Ive got a document and when the user enters something into one input I need to show a response in a second input box. I can get the user given value, i can process it, but when I try to set the second input box with the result I get the error $.field is null. Here is the code:
$('places').addEvent('keyup', function(){
var places = $('places').value;
alert("PLACE: "+places);
var price = values[places];
var nights = $('nights').value.toInt();
alert("NIGHTS: "+nights);
var total = price * nights;
alert("TOTAL: "+total);
$('pricepernight').set('text', total);
$('pricetotal').set('text', total - ((total / 100) * 21));
});
So I get the place value. I pull the price of the place out of an assoc array. I then multiple that price by the amount of nights field in by the user and this is then my total amount. It is this amount that I cannot set to. Note that the alert shows the correct amount.
and the html looks like this
<div class='block'>
<input type="text" id="places" />
</div>
<div class='block'>
<label for="nachten">Aantal nachten</label>
<input type="text" id="nights" />
</div>
<div class='block long'>
<span class='label'>Prijs per slaapplaats per nacht</span>
<input type="text" class='resultfield' id='pricepernight' />
</div>
<div class='block last'>
<span class='label'>Totaalprijs excl. btw</span>
<input type="text" class='resultfield' id='pricetotal'/>
</div>
Firebug responds:
String contains an invalid character
[Break On This Error]
...x:\'4W\',3X:18.1l,al:18.1l,1Q:18.1l,as:18.1l,8S:18.1l,1F:O,3E:{x:\'1u\',y:\'1o\'...
Any ideas/suggestions anyone? Thank you in advance!
right. you seem to have used a mix of mootools and jquery code.
$('nights').addEvent('keyup', function(){
var places = $('places').value;
var price = values[places];
var nights = $('nights').value;
var total = price * nights;
alert(total);
$('#pricepernight').val(total);
//$('#pricetotal').val(total - ((total / 100) * 21));
});
in mootools 1.2+, this should be:
$('nights').addEvent('keyup', function(){
var places = $('places').get('value');
var price = values[places];
var nights = $('nights').get('value');
var total = price * nights;
alert(total);
$('pricepernight').set('value', total);
//$('#pricetotal').val(total - ((total / 100) * 21));
});
there's an implied global array values. also, this is not very safe as nights may not be integer.
the point is. #id -> id and .val() -> set('value', 'newvalue') - or .get('value')
There are couple of minor mistakes here.
First, you should use # sign to select based on your id attributes
like places and nights
Check http://api.jquery.com/id-selector/
Second, use val() to read the value from the html controls rather
than value
Check http://api.jquery.com/val/
try this
$('#nights').keyup(function(){
var places = $('#places').val();
var price = values[places];
var nights = $('#nights').val();
var total = parseInt(price) * parseInt(nights);
alert(total);
$('#pricepernight').val(total);
//$('#pricetotal').val(total - ((total / 100) * 21));
});
and what is values[places]?