How disable wrong options in selects depend on selected option? - javascript

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

Related

Calculate total price, based on several input fields values

I'm trying to make a form that contains several different products with different options to calculate and I need to get the total price.
Scenario:
(a+b) * c = price
(a+b) * c = price
(a+b) * c = price
price + price + price = toltal
This is my script, but it doesn't work
$(document).ready(function () {
$("#form").on("keyup", ".form-calc", function () {
var parent = $(this).closest(".items");
var sum = parent.find(".form-line").val((parent.find(".form-cost").val() + parent.find(".form-cost-skift").val()).toFixed(2));
parent.find(".form-line").val((parent.find(".form-qty").val() * sum).toFixed(2));
var total = 0;
$(".form-line").each(function () {
total += parseFloat($(this).val() || 0);
});
$("#total").val(total.toFixed(2));
});
});
JSFiddle
What I'm missing?
Maybe something like this? https://jsfiddle.net/tnzcz8a3/3/
$(document).ready(function () {
$("#form").on("keyup", ".form-calc", function () {
var parent = $(this).closest(".items");
var sum = 0;
var total = 0;
if (!isNaN(parent.find(".form-cost").val())) sum += +parent.find(".form-cost").val();
if (!isNaN(parent.find(".form-cost-skift").val())) sum += +parent.find(".form-cost-skift").val();
if (!isNaN(parent.find(".form-qty").val())) sum *= +parent.find(".form-qty").val();
parent.find(".form-line").val(sum.toFixed(2));
$(".form-line").each(function () {
total += parseFloat($(this).val() || 0);
});
$("#total").val(total.toFixed(2));
});
});

Can't make the function true when the argument is passed JQuery

Problem is simple. When the scoring variable is higher than 10, I can't make the sprawdzRyzyko() function return boolean true.
var high_ryzyko_kraj = ['Polska', 'Afganistan', 'Ukraina'];
var less_ryzyko_kraj = ['Serbia', 'Egipt'];
var scoring = 0;
$('#country, #country-bd, #country-wd').change(function(){
caunt = $(this).val();
var arr = $.inArray(caunt, high_ryzyko_kraj);
var drr = $.inArray(caunt, less_ryzyko_kraj);
if (arr>-1){
scoring += 4 ;
sprawdzRyzyko();
}else if(drr>-1){
scoring += 2 ;
sprawdzRyzyko();
}
});
console.log(scoring);
var sprawdzRyzyko = function () {
if (scoring > 10){
return true;
}
}
// For Testing
var a = sprawdzRyzyko();
if (a){
console.log("Hey it works!");
}
Fiddle
You can set the scoring variable above 10 by sting the selects to 3 countries in high_ryzyko_kraj array.
Here is a solution. Answer Fiddle
function sprawdzRyzyko() {
if (scoring > 10) {
return true;
}
};
Try this: http://jsfiddle.net/uJA39/15/
var high_ryzyko_kraj = ['Polska', 'Afganistan', 'Ukraina'];
var less_ryzyko_kraj = ['Serbia', 'Egipt'];
var scoring = 0;
var sprawdzRyzyko = false;
$('#country, #country-bd, #country-wd').change(function(){
if ($.inArray($(this).val(), high_ryzyko_kraj)>-1)
scoring += 4;
else if($.inArray($(this).val(), less_ryzyko_kraj)>-1)
scoring += 2;
if (scoring > 10){
alert("Hey it works!");
sprawdzRyzyko=true;
}
});
I don't know your dynamics but are you sure that scoring shouldn't be set to 0 (zero) every time DDL changes (so inside change event handler)?
Hope this helps,
Have a nice day,
Alberto

how to remove NaN from field value and show value?

I make a dynamic form, if i delete a row then in loop result is NaN of the deleted element i want when i delete element its 0 value pass not NaN. Like i delete 5th element when 1=5 it shows NaN. How to remove this error and instead 0 will be add in sum value, how i do?
$("body").on('change', '.quantity', function() {
var that = $(this);
if ($('#itemcounter').val()==""){
$('#itemscounter').val("1");
var counter=$('#itemscounter').val();
var quantity=$('#quantity').val();
var unitprice=$('#unitprice').val();
var linetotal=quantity*unitprice;
that.parent().find('.linetotal').val(linetotal)
$("#invoicetotalamount").val(+linetotal)
var discount=document.getElementById('discount').value ;
var discountamount= discount/100 * linetotal;
var amount=linetotal-discountamount;
$("#balanceamount").val(+amount);
} else {
var counter=$('#itemscounter').val();
var quantity=$('#quantity').val();
var unitprice=$('#unitprice').val();
var linetotal=quantity*unitprice;
$('#linetotal').val(+linetotal);
var sum=linetotal;
for (i = 2; i <=counter; i++) {
var quantity=parseFloat($('#quantity' + i).val());
var unitprice=parseFloat($('#unitprice' + i).val());
var linetotal=quantity*unitprice;
$('#linetotal' + i).val(+linetotal);
alert(sum);
sum=+sum +(+(linetotal));
}
$("#invoicetotalamount").val(+sum);
var discount=document.getElementById('discount').value ;
var discountamount= discount/100 * sum;
var amount=sum-discountamount;
$("#balanceamount").val(+amount);
}
});
Check the value if its a number like this:
var quantity=parseFloat($('#quantity' + i).val());
if(isNaN(quantity)){
quantity=0;
}
you can check it with if else loop for dynamic data:
var str_val = $('#itemscounter').val();
if(str_val == NaN){
str_val =0; //use str_val at the place you want
alert(str_val);
}
You can check to see if it's NaN
var quantity = !isNaN($('#quantity' + i).val()) ? parseFloat($('#quantity' + i).val(), 2) : 0;

Array not resetting when input changed

I'm trying to populate select box using value from input text. So far I've been doing good in populating the select box. But the problems came when I change the input field into another value. The select box won't reset the array instead of adding the option value in the end of array. Here's my code:
HTML:
<input type="text" name="ttc_list" id="ttc_list" />
<select name="priority_list" id="priority_list">
<option value="">Choose TTC First...</option>
</select>
Javascript:
$(document).ready(function(){
$("select#priority_list").attr("disabled","disabled");
$('input[name="ttc_list"]').change(function() {
var arr = [];
arr.length = 0;
var ttc = $("#ttc_list").val();
if(ttc == 100 || ttc == 101)
{
var prty100_Start = 40;
var prty100_End = 80;
while(prty100_Start < prty100_End+1){
arr.push(zeroPad(prty100_Start++,2));
}
}
else
{
var prty200_Start = 1;
var prty200_End = 5;
while(prty200_Start < prty200_End+1){
arr.push(zeroPad(prty200_Start++,2));
}
}
var selectOptions = {
100: arr,
101: arr,
200: arr,
204: arr,
210: arr
}
$("select#priority_list").removeAttr("disabled");
console.log($(this).val());
if(selectOptions[$(this).val()])
{
console.log(selectOptions[$(this).val()]);
$.each(selectOptions[$(this).val()], function() {
$('select[name="priority_list"]').append('<option>' + this + '</option>');
});
}
});
});
function zeroPad(num, numZeros) {
var n = Math.abs(num);
var zeros = Math.max(0, numZeros - Math.floor(n).toString().length );
var zeroString = Math.pow(10,zeros).toString().substr(1);
if( num < 0 ) {
zeroString = '-' + zeroString;
}
return zeroString+n;
}
Example: When user filled '100' in input text, it works fine in populating select box from '40' to '80', but when user changes the input text to '200' without refreshing the page, the select box show options from '40' to '80' and '01' to '05' instead of only '01' to '05'.
Expected result: When user changes the input text to '200' without refreshing the page, the select box shows options only from '01' to '05'
Here's my working demo http://jsfiddle.net/danc32/6UqYS/1/.
Where should I put my arr.length = 0 to reset my array?
Because you are using .append('<option>' + this + '</option>');, every time you change you add the new options to the existing list. Instead you could use:
.html('<option value="">Choose TTC First...</option>'); // remove old options
to reset the select and remove the old options, then use:
.append('<option>' + this + '</option>'); // add new options
to add the new ones.
See this JSFiddle for complete code.
You need to clear the contents of the select element before adding new items... also there is no need to recreate the selectOptions object within the change handler.. it is a static object so it can be created only once as given below
$(document).ready(function () {
var $priority_list = $("#priority_list").prop("disabled", true);
var selectOptions = {};
var arr_40_80 = arrays(40, 80);
selectOptions['100'] = arr_40_80;
selectOptions['101'] = arr_40_80;
var arr_1_5 = arrays(1, 5);
selectOptions['200'] = arr_1_5;
selectOptions['204'] = arr_1_5;
selectOptions['210'] = arr_1_5;
$('input[name="ttc_list"]').change(function () {
var ttc = $(this).val(), arr = selectOptions[ttc];
$priority_list.prop("disabled", false).empty();
if (arr) {
$.each(arr, function () {
$priority_list.append('<option>' + this + '</option>');
});
}
});
});
function arrays(start,end){
var arr = [];
while (start <= end) {
arr.push(zeroPad(start++, 2));
}
return arr;
}
function zeroPad(num, numZeros) {
var n = Math.abs(num);
var zeros = Math.max(0, numZeros - Math.floor(n).toString().length);
var zeroString = Math.pow(10, zeros).toString().substr(1);
if (num < 0) {
zeroString = '-' + zeroString;
}
return zeroString + n;
}
Demo: Fiddle

How to assign radio buttons a value in javascript

What I need to do is turn the 4 different values (when clicked) on the page into a number that I can use to calculate the output in the chart.
http://jsfiddle.net/nlem33/eyGMu/7/
var min_value = 0,
max_value = 10,
units = 0,
price = 0;
var sliderHandler = function (event, ui) {
var newdata = [],
newdata2 = []
data = [],
sum = 0;
if(this.id === 'slider1') {
$('#slider1_value').html(ui.value);
units = ui.value;
} else {
$('#slider2_value').html('$' + ui.value);
price = ui.value;
}
for(var i = 0; i < 12; i++) {
data.push(units * price);
for(var j = 0; j < i; j++)
sum += data[j];
newdata.push(229 * units * i);
newdata2.push(sum);
}
console.log(newdata);
chart.series[0].setData(newdata2);
chart.series[1].setData(newdata);
}
Add a variable called selected and use this event handler:
var selected = 1;
$(document).ready(function() {
$(".product").click(function(){
selected = this.id.replace("product", "");
alert(selected);
});
});
See the updated fiddle. Then you can use the selected variable anywhere.
In order to use the value of a radio button rather than the number in its id, use the following code instead:
var selected = 1;
$(document).ready(function() {
$("input[name=chooseProduct]").change(function(){
selected = $(this).val();
alert(selected);
});
});
See next updated fiddle for that example as well.

Categories

Resources