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
Related
I tried to no avail to get HTML, CSS and Javascript to limit number of items in datalist, for whatever reason, it is isn't working. The list is populated by a loop on a array.
<datalist id="trainNoList">
<script>
if (markers)
{
var options = '';
var trainNoList = [];
for (var i = 0; i < markers.length; i++) {
var trainNo = markers[i][20];
trainNoList.push(trainNo);
options += "<option value='" + trainNoList[i] + "'></option>";
}
}
</script>
</datalist>
<!-- Use JavaScript to pan to the train when an option is selected -->
<script>
$("#trainNoInput").on("input", function() {
var selectedTrainNo = $(this).val();
// Check if the input is a range
var rangeCheck = selectedTrainNo.split("-");
if (rangeCheck.length === 2) {
vehiclestart = rangeCheck[0];
vehicleend = rangeCheck[1];
} else {
// Perform the same actions as in the original code
for (var i = 0; i < markers.length; i++) {
var trainNo = markers[i][20];
if (trainNo == selectedTrainNo) {
var lat = parseFloat(markers[i][2]);
var lng = parseFloat(markers[i][3]);
var setcontentforpopup = "Vehicle"+markers[i][0]+"";
vehiclestart = 1;
vehicleend = 99999999999999;
var popup = L.popup()
.setLatLng([lat, lng])
.setContent(setcontentforpopup)
.addTo(map);
map.flyTo([lat, lng], 16);
break;
}
}
}
});
$("#trainNoInput").on("focus", function() {
console.debug("The trainNoInput field has received a keyup event");
clearTimeout(ajaxtimeout);
});
$("#trainNoInput").on("blur", function() {
ajaxtimeout = setTimeout(foo, 10000);
console.debug("no");
});
$("#trainNoInput").on("keyup", function(event) {
if (event.keyCode === 13) {
markerLookup = {};
markerClusters.clearLayers();
foo();
}
});
</script>
enter image description here
The desire result is simple - limit number of items shown down to 5 or whatever set amount and add a scroll bar to scroll down to see the remainder of the records
enter image description here
I want yo use test variable in update.js but it shows error when I use as variable but when I pass this value directly it works
can someone please tell me how can use dynamic variable to change quantity of existing products in cart
I have updated my code It will allow user to add only 5 items more than 5 items will be removed It will create string which will look like this
32082238341235:0,39470423048307:0,32164693278835:0,32164693835891:1
and finally the all IDs and qunatity will be updated by update.js
I have got error in last step its shows
{"status":404,"message":"Cart Error","description":"Cannot find variant"}
when i try to update all products
jQuery.getJSON('/cart.js', function(cart) {
var items_new = cart.items;
var count = 0;
count = cart.item_count;
var item_to_remove = count - 5;
if (count > 5) {
var item_to_remove = count - 5;
var combine = ""
if (item_to_remove > 0) {
for (var i = 0; i < items_new.length; i++) {
if (count > 5) {
var c_id = items_new[i].variant_id;
var c_quantity = items_new[i].quantity;
if (c_quantity >= item_to_remove) {
var q = c_quantity - item_to_remove
var data_multiple = c_id + ":" + q + ",";
debugger;
count = count - item_to_remove;
console.log(data_multiple);
var combine = combine + data_multiple;
} else {
var data_single = c_id + ":" + 0 + ",";
count = count - c_quantity;
item_to_remove = item_to_remove - c_quantity
console.log(data_single)
var combine = combine + data_single;
}
}
}
console.log(combine.slice(0, -1));
var test = combine.slice(0, -1);
console.log({
updates: {
test
}
});
jQuery.post('/cart/update.js', {
updates: {
test
}
});
}
t._rerenderCart()
}
t.sidebarDrawer.open()
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
You need to store test as an object within parentheses {} and then pass to updates by using the spread ... operator.
var test = {39470423048307 : 0, 32164693278835 : 0, 32164693835891 : 1};
console.log({updates: {...test}});
jQuery.post('/cart/update.js', {updates:{...test}});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
In your updated code, you are passing a string to updates rather than an object. You should create an object from the data inside the for loop and pass that object to updates. See lines with // CHANGE HERE:
...
var combine = {};
if (item_to_remove > 0) {
for (var i = 0; i < items_new.length; i++) {
if (count > 5) {
var c_id = items_new[i].variant_id;
var c_quantity = items_new[i].quantity;
if (c_quantity >= item_to_remove) {
var q = c_quantity - item_to_remove;
// CHANGE HERE
combine[c_id] = q;
count = count - item_to_remove;
} else {
// CHANGE HERE
combine[c_id] = 0;
count = count - c_quantity;
item_to_remove = item_to_remove - c_quantity;
}
console.log(combine);
}
}
// CHANGE HERE
var test = combine;
console.log({
updates: test
});
jQuery.post('/cart/update.js', {
updates: test
});
...
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;
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.
Given the select box below. I want to be able to dynamically add a new option.
<select id="user_department_id" name="user[department_id]">
<option value=""> </option>
<option value="9">AAAAA</option>
<option value="11">BBBBB</option>
<option value="10">G</option>
<option value="12">Z</option>
<option value="">--</option>
<option value="add">Add a New</option>
</select>
I have been using the following to add a new option:
$('#user_department_id')
.prepend($("<option></option>")
.attr("value",data.id)
.text(data.title)
);
The problem here is that it is position unnaturally, it's above the empty placeholder option and not sorted alphabetically. Is there a magic way to append a new select option in the correct place?
Thanks
This inserts a new option value into (assuming it is already sorted)
$('#yourselectID option').each(function()
{
var option = $(this).text();
option = option.toLowerCase();
var test = option.toLowerCase();
if ( option > test)
{
$(this).before('<option value="'+test+'">' + test+ '</option>');
return false;
}
});
I think you can use .after('blah') with the selector you described.
for example:
$('#user_department_id option[value="12"]').after('<option value="13">Q</option>')
is that of any use?
As mentioned in my comment, you can remove the option that you don't want to sort and then add them back.
Note: The below will work in your case because you want the -- and Add New at the end.
DEMO
var selElem = document.getElementById('user_department_id')
var tmpAry = [];
var igOpt = [];
for (var i = 0; i < selElem.options.length; i++) {
if ($(selElem.options[i]).hasClass('ig')) {
igOpt.push([selElem.options[i].text,
selElem.options[i].value]);
continue;
}
tmpAry[i] = new Array();
tmpAry[i][0] = selElem.options[i].text;
tmpAry[i][1] = selElem.options[i].value;
}
tmpAry.sort();
//merge with ignored options
tmpAry = tmpAry.concat(igOpt);
//remove options
$(selElem).empty();
for (var i = 0; i < tmpAry.length; i++) {
var op = new Option(tmpAry[i][0], tmpAry[i][1]);
selElem.options[i] = op;
}
Keep your options in an array of objects and generate your select from that object. Then add your new items to that array and regenerate your select.
$(function() {
// Any options always on the top
var topOptions = '<option value=""> </option>';
// Your middle, sorted options
var options = [{val: 9, text: "AAAAA"}, {val: 11, text: "BBBBB"},{val: 10, text: "G"},{val: 12, text: "Z"}];
// Any options always on the bottom
var bottomOptions = '<option value="">--</option><option value="add">Add a New</option>';
// Function to populate the select options from above data
function populateOptions(element, options) {
// Sort options
options = options.sort(function(a, b) {
return a.text.toLowerCase() > b.text.toLowerCase();
});
$(element).html('').append(topOptions);
for (var i = 0; i < options.length; i++) {
$('<option>').attr("value", options[i].val).text(options[i].text).appendTo($(element));
}
$(element).append(bottomOptions);
}
// Start by populating the select
populateOptions('#user_department_id', options);
// Add and repopulate when add requested
$('#user_department_id').on('change', function() {
if ($(this).val() == "add") {
// Add option to list
options.push({val: data.id, text: data.text});
// Repopulate select
populateOptions(this, options);
// Select the new item
$(this).val(data.id);
}
});
});
Demo: http://jsfiddle.net/kfC3S/
Not very elegant, but this should do:
$('#user_department_id option').each(function() {
if(this.text > data.title) {
$(this).before('<option value="' + data.id + '">' + data.title + '</option>');
return false;
}
});
You can use underscore's sortedIndex to figure out where to insert the item and then jquery's after function to insert it at that position. This is assuming you want to sort by option text alphabetically:
var option = '<option value="' + data.id + '">' + data.title + '</option>';
var index = _.sortedIndex($('#user_department_id option'), option, function(item) {
return $(item).text();
});
if(index === 0) {
$('#user_department_id').prepend(option);
} else {
$('#user_department_id option').eq(index - 1).after(option);
}