im a noob at javascript and was wondering how it is possible to display an alert message when the total value goes below 0. The page in question is here (http://cashmoneypaid.com/order-form-phones-work) and the script i have tried is below. Thanks so much for the help.
function checkTotal() {
document.listForm.total.value = '';
var sum = 20;
for (i = 0; i < document.listForm.choice.length; i++) {
if (document.listForm.choice[i].checked) {
sum = sum + parseInt(document.listForm.choice[i].value);
}
}
document.listForm.total.value = sum;
}
$("#total").ready(function() {
if (sum > 0) {
alert("We are sorry, but at this time we can not offer you any money for your item");
}
});
Since you use jQuery change it all!!
$(function(){
var sum = 20;
$('form input[type="checkbox"]').change(function(){
if (this.checked)
sum -= parseFloat(this.value);
else
sum += parseFloat(this.value);
if (sum < 0)
alert('bla bla bla');
});
});
Live DEMO
You can also use this trick:
$('form input[type="checkbox"]').change(function(){
var value = parseFloat(this.value) * (this.checked ? -1 : 1);
sum += value
...
Live DEMO
Related
I am using laravel and stuck in a condition. i add counter and a condition that when counter equals to 4 disable the button and no more item added.
this is my code
var increment = 0;
$(document).ready(function(){
$(".compare").click(function(){
increment++;
document.getElementById('compare').innerHTML = "";
document.getElementById('compare').innerHTML = "Compare (" +increment+")";
if(increment == 4)
{
var array = document.getElementsByClassName('compare');
for (var i = 0 ; i < array.length ; i++)
{
array[i].setAttribute('disabled','');
}
}
i want's to disable button after reaching the limit and no more item added from anywhere if the counter equals to 4.
var increment = 0;
$(document).ready(function() {
$(".compare").click(function() {
increment++;
document.getElementById('compare').innerHTML = "";
document.getElementById('compare').innerHTML = "Compare (" + increment + ")";
if (increment == 4) {
var array = document.getElementsByClassName('compare');
for (var i = 0; i < array.length; i++) {
array[i].setAttribute('disabled', '');
}
}
})
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button class="compare" id="compare">INCREMENT</button>
Not really Laravel related, but you don't need jQuery just to add a counter. Vanilla JS gets the job done:
<button id="btn" onclick="buttonCheck()">Click me</button>
<script>
var counter = 0;
function buttonCheck(){
counter++;
if (counter >= 4)
document.getElementById("btn").setAttribute("disabled", "disabled");
}
</script>
Seeing that you already have jQuery in your code. I'll give an example using jQuery.
var increment = 0;
$(document).ready(function(){
$(".compare").click(function(){
increment++;
document.getElementById('compare').innerHTML = "";
document.getElementById('compare').innerHTML = "Compare (" +increment+")";
if(increment == 4)
{
$(".compare").prop("disabled", true);
//prop() is used to set attribute value of an html element
}
}
}
Most of the time, this would work. But in some cases that it won't, you could manipulate this with CSS.
var increment = 0;
$(document).ready(function(){
$(".compare").click(function(){
increment++;
document.getElementById('compare').innerHTML = "";
document.getElementById('compare').innerHTML = "Compare (" +increment+")";
if(increment == 4)
{
$(".compare").css("pointer-events", "none");
}
}
}
I want to get the average by input radio button value.
I have a form with 3x 10 radio fields counting from 1 to 10.
Now I want to calculate the average, so you get a final score.
I get it working with a text field, but I don't know how to do it with radio buttons checked.
This is my javascript:
$('.beoordeling').keyup(function () {
var total = 0,
valid_labels = 0,
average;
$('.beoordeling').each(function () {
var val = parseInt($(this).val(), 10);
if (!isNaN(val)) {
valid_labels += 1;
total += val;
}
});
console.log(total)
average = total / valid_labels;
$('.eindstand').val(average);
});
I have created a jsfiddle with how I have it now.
http://jsfiddle.net/Q2MEq/
Demo Fiddle
Check this code.
$('.beoordeling').change(function () {
var total = 0,
valid_labels = 0,
average;
$('.beoordeling:checked').each(function () {
var val = parseInt($(this).val(), 10);
if (!isNaN(val)) {
valid_labels += 1;
total += val;
}
});
console.log(total)
average = total / valid_labels;
$('.eindstand').val(average);
});
Use change events in case of inputs like radio and not keyup.
use :checked selector to get selected radio buttons only.
See for this you need to have radio buttons with different name attributes or without it, and then you can change to this:
$(':radio').change(function () {
var total = 0,
valid_labels = 0,
average;
$(':checked').each(function () {
var val = parseInt($(this).val(), 10);
if (!isNaN(val)) {
valid_labels += 1;
total += val;
}
});
console.log(total)
average = total / valid_labels;
$('.eindstand').val(average);
});
Demo
Please check this
$('.beoordeling').keyup(function () {
var total = 0,
valid_labels = 0,
average;
$('.beoordeling').each(function () {
var val = parseInt($(this).val(), 10);
if (!isNaN(val)) {
valid_labels += 1;
total += val;
}
});
console.log(total)
average = total / valid_labels;
$('.eindstand').val(average);
});
Demo: JSFiddle
You can determine whether or not a radio button is checked with ".checked"
document.getElementById("radio_1").checked
... will return true if the button is checked, false otherwise.
I am trying to calculate all fields in the form which have the same class (shown below in the code), I have managed to get this to work, I think I may be setting the wrong value types in javascript as its not adding them together correctly. Its adding them on top of each other and not to each other. so instead of 4.00 + 5.50 equalling to 9.50 it would read 04.0005.50.
function calculate() {
var total = 0;
$('input.calc').each(function() {
var num = this.value;
//Number(this.value, 10);
if (!isNaN(num)) {
total += num.toFixed(2);
}
});
$("#total").val(total);
}
Any help its appreciated, Thanks
<script language="javascript">
function calculate() {
var total = 0;
$('input.calc').each(function() {
var num = this.value;
//Number(this.value, 10);
if (!isNaN(num)) {
total += num.parseFloat(num);
}
});
$("#total").val(total);
}
</script>
function calculate() {
var total = 0;
$('input.calc').each(function() {
var num = parseFloat(this.value);
//Number(this.value, 10);
if (!isNaN(num)) {
total += num;
}
});
$("#total").val(total);
}
I'd like to create a simple math practising js script.
For example:
The sum is given (=10) and there are four select with numbers from 0 to 10.
And if I choose a number I should disable the wrong options. I mean, the sum of selected options can not bigger then 10.
I tried this way: click here
$(document).on("change", "select.number", function(){
var sum = 10;
var number = $(this).children("option:selected").val();
var sum_number = 0;
$("select.number option:selected").each(function(){
sum_number = parseInt($(this).val(),10) + parseInt(sum_number,10);
});
$("select.number option").attr("disabled", false);
if(sum_number>0){
var act_person = act_max_person = 0;
$("select.number").each(function(){
$(this).children("option:not(:first)").each(function(){ // first is 0
if(parseInt($(this).val(),10) + parseInt(sum_number,10) > sum) $(this).attr("disabled", true);
});
});
}
});
But it's vary far from the perfect...
Try
$(document).on("change", "select.number", function () {
var sum = 10;
var number = $(this).children("option:selected").val();
var sum_number = 0;
$("select.number option:selected").each(function () {
sum_number += parseInt($(this).val(), 10);
});
$('select.number option').prop('disabled', false);
if (sum_number > 0) {
var diff = sum - sum_number;
$('select.number').each(function () {
var idx = parseInt($(this).val(), 10) + diff + 1;
$(this).find('option').slice(idx).prop('disabled', true)
})
}
});
Demo: Fiddle
and there we go:
I'm writing(in fact it feels more like trying and asking) a GreaseMonkey script using JS and including(also using) the jQuery library.
I created another table with some input-fields. Example(input-fields-only):
+ " < input type=\" text\" id=\" field_1\" name=\" min_field_1\" value=\"\" > "
+ " < input type=\" text\" id=\" field_2\" name=\" min_field_2\" value=\"\" > "
+ " < input type=\" text\" id=\" field_3\" name=\" min_field_3\" value=\"\" > "
+ " < input type=\" text\" id=\" field_4\" name=\" min_field_4\" value=\"\" > "
//the results should be rendered in another input-field in this case with id=field_result_min
+ " < input type=\" text\" id=\" field_result_min\" name=\"min_field_result\" > "
+ " < input type=\" text\" id=\" field_result_max\" name=\"max_field_result\" > "
+ " < input type=\" text\" id=\" field_result_avg\" name=\"avg_field_result\" > "
My aim was to get the min,max and avg value of the fields and render the result in another input field.
//returns the min value of all input-fields starting with a name attribute of min
$("input[name^='min']")min.()
This won't work because jQuery library hasn't any min() or max() like JS does.
So i tried sth. like
<input type="button" value="=" onclick="window.document.getElementById('field_result_min') = Math.min(window.document.getElementById('field_1').value,window.document.getElementById('field_2').value,window.document.getElementById('field_3').value,window.document.getElementById('field_4').value)" >
Hm...again I'm stuck and confused - even while I'm explaining.
Question: How do I render the min and max values of some input-fields in one input-field?
Any help would be much appreciated.
Faili
Update
This is how I solved it. Well, it's just the avg and max(min is deriveable). Any changes or mistakes should come from copy and paste and changing sth. in the code here at stackoverflow.
function calculateAvg() {
var fields = [1*window.document.getElementById('field_1').value,1*window.document.getElementById('field2').value,1*window.document.getElementById('field').value,1*window.document.getElementById('field4').value,1*window.document.getElementById('field5').value,1*window.document.getElementById('field6').value];
var total = 0;
var anzahl = 0;
for(i=0;i 0) {
total = total+fields[i];
anzahl=anzahl+1;}
}
var durchschnitt = (total/anzahl);
window.document.getElementById('fieldavg').value = durchschnitt;
}
$("#fieldavg").blur (calculateAvg);
function calculateMax() {
var fields = [1*window.document.getElementById('field_1').value,1*window.document.getElementById('field2').value,1*window.document.getElementById('field').value,1*window.document.getElementById('field4').value,1*window.document.getElementById('field5').value,1*window.document.getElementById('field6').value];
var max = 0;
for(i=0; i<fields.length;i++) {
if(fields[i] > 0) {
if(max<fields[i]){
max=fields[i];
}
}
}
window.document.getElementById('field8').value = max;
}
$("'field_8").blur (calculateMax);
So, thanks for your help. I really needed it.
Faili
Using other libraries are one way to do it, but solving small issues by hand [using raw javascript] would be nicer.
Change the selectors in code below, and check.
$(function(){
sel = $('.field')
min_field = $('#min');
max_field = $('#max');
avg_field = $('#avg');
len = $(sel).length;
$(sel).change(function(){
sum = 0
list = []
$(sel).each(function(){
val = Number($(this).val());
list.push(val);
sum += val;
})
$(min_field).val(Math.min.apply(Math, list))
$(max_field).val(Math.max.apply(Math, list))
$(avg_field).val(sum/len);
})
})
Happy Coding.
Try this:
var values = $("input[name^='min']").map(function(){
return isNaN(this.value) ? [] : +this.value;
}).get();
var min = Math.min.apply(null, values);
And then you can add that min-value to another input field like so:
$('#some-input').val(min);
You might want to have a look at the jQuery Calculation Plug-in. The syntax for your example would be something like this:
var MinVal=$("input[name^='min_field_']").min(); // Get minimum value
var MaxVal=$("input[name^='min_field_']").max(); // Get maximum value
var AvgVal=$("input[name^='min_field_']").avg(); // Get average value
This would be faster version:
var MinField=$("input[name^='min_field_']");
var MinVal=MinField.min(); // Get minimum value
var MaxVal=MinField.max(); // Get maximum value
var AvgVal=MinField.avg(); // Get average value
Without plugins you can do something like this JSFiddle
Array.prototype.avg = function() {
var total = this[0];
var len = this.length;
for (var i = 1; i != len; i++) total += this[i];
return total / len;
}
Array.prototype.min = function() {
return Math.min.apply( Math, this );
}
Array.prototype.max = function() {
return Math.max.apply( Math, this );
}
var values = $("input[id^='field_']").map(function(){
var value = $(this).val();
if (value.length == 0 || isNaN(value)) {
return 0;
} else {
return parseFloat(value);
}
}).get();
$('#max').val(values.max());
$('#min').val(values.min());
$('#avg').val(values.avg());
The prototypes should help in future.