Rails, collection_check_boxes, maximum picked - html

I have a form which uses collection_check_boxes for an input.
= f.collection_check_boxes :color_ids, group.colors, :id, :name
I would like to prevent users from checking more than n boxes in the form.
I know how to do it in the model, I just need the views part. Thanks!

In the end, I decided to use jquery.
1 In the view I put the maximum amount at the end of the class like this:
= f.collection_check_boxes :color_ids, group.colors, :id, :name, item_wrapper_class: "bla bla2 #{group.maximum.to_s}"
2 When an input[type=checkbox] is clicked I find how many others are marked
$(this).parent().parent().siblings().children().children(':checked').length
3 I find the maximum allowed value from step 1 by the following line
max = parseInt($(this).parent().parent().attr('class').split(' ').pop());
4 I compare the maximum allowed with the checked and prevent from checking if the first one is less. The whole code looks like this
$('input[type=checkbox]').on('change', function(evt) {
var max;
max = parseInt($(this).parent().parent().attr('class').split(' ').pop());
if ($(this).parent().parent().siblings().children().children(':checked').length + 1 > max) {
this.checked = false;
}
});

Related

Using DataTables how to display a running total of an amount entered in each row?

http://live.datatables.net/dalogaci/1/edit
I have an amount of money to be dispersed and am using DataTables to display a list of people and allow entry of an amount next to each person (their share of the disbursement). I want to provide a running total of the amount entered into the table so I can warn when the total to be dispersed has been reached or passed.
Kind regards,
Glyn
You can use the following approach.
In my case, I display the running total in a <div>, rather than an input box, as the value is only for display purposes:
<div id="showsum">Grand Total: $0.00</div>
The end result:
The script for this - which I have tried to explain with comments in the code:
<script type="text/javascript">
// define the table variable here so the doSum()
// function will have access to it, when needed:
var table;
// reads each value from the final column in the table, checks
// if the value is a number (as opposed to blank), and then
// keeps a running total. Ensure we round fractions of pennies
// as needed.
//
// When handling money, use a big number library - see this:
// https://stackoverflow.com/questions/1458633/how-to-deal-with-floating-point-number-precision-in-javascript
//
function doSum() {
//var foop = table.columns(5).nodes().to$();
var sum = 0.0;
// this gets each node (cell) in the final column:
table.columns(5).nodes().to$()[0].forEach(function (item) {
// see if the display value is a number (i.e. not blank):
var amt = parseFloat($('input', item ).val());
if (!isNaN(amt)) {
sum += amt;
}
});
// round and display to 2 decimal places:
sum = (Math.round((sum + Number.EPSILON) * 100) / 100).toFixed(2);
$('#showsum').text("Grand Total: $" + sum);
}
$(document).ready(function() {
table = $('#example').DataTable( {
"columnDefs": [ {
"targets": 5,
"data": function ( row, type, val, meta ) {
// note the use of onchange="doSum()" in the following:
return '<input type="number" min="0" max="99999.99" step=".01" placeholder="0.00" onchange="doSum()">';
}
} ]
} );
} );
</script>
For a change to be added to the grand total, you have to hit "enter", or click outside of the input field, if you type the value in manually.
Because you are dealing with money, the code should really be using a "big number" format to eliminate the risk of inaccuracies in fractions of pennies (due to limitations in floating point arithmetic). For example see here.
Final note: I see this question was down-voted. I think that may have been because you only link to your demo code, instead of showing the relevant parts in the question itself. The link to the demo is useful - but showing code in the question itself is generally a "must-do", I think.

How to display one image at the time from images array which are fetched from database?

In this application I'm uploading images to my local uploads folder and in MySQL database I'm storing the image's name. How can I display one image at the time from images array which are fetched from database? Currently I managed to display all uploaded images using EJS. How can i set it that the single displayed image "src" changes every 10 seconds or so?
<% for(i=0; i<images.length; i++) { %>
<img src="/uploads/<%= images[i].name %>" alt="">
<% }; %>
I am not much aware about EJS so if there is any syntax error change it at your end. First create a unique id for all images and same class name.
<% for(i=0; i<images.length; i++) { %>
<% if(i == 0) { %>
<img class="allImage" src="/uploads/<%= images[i].name %>" alt="" id="image_<%= i %>">
<% }; %>
<% if(i != 0) { %>
<img class="allImage" src="/uploads/<%= images[i].name %>" alt="" image_id="test<%= i %>" style="display:none;">
<% }; %>
<% }; %>
You can make if-else condition or use if inside style tag.
Now you need to define a javascript global variable. Value of that variable start from 0.
var a = 0;
Create a function and call it after every 10 seconds
window.setInterval(function(){
myFuction();
}, 10000);
Check the length of images so when last image display we can start again with 0.
myFuction(){
a = a + 1; // increment global variable to show next image
var length = $('.allImage').length;
if(length == a || length > a){
a = 0;
}
$('.allImage').hide(); // First hide all image with same class
$('#image_'+a).show(); // Show next image
}
Hope this will help you to get your output. This work for me in php so I hope this will also work for you. If any syntax error, change it at your end. Thanks
I haven't used EJS before, but I imagine something using setTimeout since you have a rough time in which you want the image to change.
Here's an example: https://repl.it/#johnoro/Image-shuffling-example
If you want it to loop without randomness, then you'll just want to keep an index instead.
I went ahead and added a link to version without randomness as well. Since EJS is just JavaScript, I assume this should be easy to convert for your purposes. Let me know if you need any more help!
And, for the purposes of showing the code without having to head over to another site:
// Selects the DOM node with the unique id, 'switch'.
const img = document.querySelector('#switch');
const images = [
"https://picsum.photos/350",
"https://picsum.photos/300?blur",
"https://picsum.photos/300?grayscale&blur=2"
];
function changeImage() {
// This'll give us a floating point number that's between 0 and the length of the images.
const rand = Math.random() * images.length;
// This'll give us an integer between 0 and the last index of our images.
const index = Math.floor(rand);
img.src = images[index];
// Notice that the function calls itself with our desired time, in this case 5000 milliseconds, or 5 seconds.
setTimeout(changeImage, 5000);
}
// We have to call it for the first change!
setTimeout(changeImage, 5000);

BigCommerce Stencil - Product Variant Stock Levels

A client wants to set up A/B testing on the Product Detail Page related to the stock_level of a product's variants. Once the user selects their options, if the quantity is less than 5, I'd show something like "Hurry, only 3 more in stock"...
I believe I have the correct Inventory settings enabled, because I can retrieve the stock_level of a product without options.
Has anyone had success pulling variant SKU stock_levels in stencil?
Thanks
This can be done using javascript in the assets/js/theme/common/product-details.js file. On initial page load and each time a product option is changed, there is a function updateView(data) that is called. The data parameter contains all the info you need for the selected variation.
Starting on line 285, replace this:
updateView(data) {
const viewModel = this.getViewModel(this.$scope);
this.showMessageBox(data.stock_message || data.purchasing_message);
with this:
updateView(data) {
const viewModel = this.getViewModel(this.$scope);
if(data.stock < "5") {
data.stock_message = "Hurry, only " + data.stock + " left!";
}
this.showMessageBox(data.stock_message || data.purchasing_message);

Creating a user generated list in flash

I'm trying to create a flash application that will keep track of user generated values. The app should basically allow the user to input the name of the item and it's cost. The total costs should then be added up to show a total value to the user. I can probably figure out how to add the values together, but I'm not really sure how to allow the user to create a list and then allow the user to save it. Can anyone point me towards a tutorial or point me in the right direction?
I am using variables to add user inputed numbers to come up with a total. The first problem is that actionscript 3.0 does not allow variables for texts. I just converted it to 2.0 to fix this. The second problem, is when I test the app and put in my values and click submit, I get NaN in the total values field. Is there a reason why it wouldn't add the values?
Here is the code I used for the submit button:
on (release) {
total = Number(rent) + Number(food) + Number(travel) + Number(entertainment) + Number(bills);
}
Am I missing anything?
Can I give the input text instance names and then give them variables? How are some ways to go about this?
Thanks for the help!
Have an object array, say for example
var stack:Array = new Array();
Then push the item name and it's cost to that array when user inputs, like
stack.push({item:AAA, cost:xx});
So that you can generate the list whenever you want with that array.
You have to see how this works in code. A list in actionscript could be stored inside an array, vector, dictionary or even an Object.
Var myList:Array = [];
myList.push({name: "item 1", cost: 5 });
myList.push({name: "item 2", cost: 7.5 });
If you want to grab the 'product' of "item 1" from the list, you have to create a function for that, lets call it getProductByName
function getProductByName(name:String):Object
{
for each(var product:Object in myList)
{
if (product.name === name) return product;
}
return null; // no match found
}
You can call that function like this:
var product = getProductByName("item 1");
trace(product.cost); // 5
And you can alter the product, so lets make it more expensive
product.cost += 1;
trace(product.cost); // 6
Have fun! If you are using classes, you would create one for the product, with public name and cost, and in that case you'de better use a vector, to ensure working with the right type.
This is what fixed the issue for me in action script 3.0:
myButton.addEventListener(MouseEvent.CLICK, addThem);
function addThem(e:MouseEvent)
{
totalField.text = String ( Number(field1.text) + Number(field2.text) + ....);
}
I also had to name the instances appropriately.

ASP.NET-MVC Linq2Sql logic to get linked items on condition

I have a subcontract table with a company field. On the company page, I do not want the company to be able to be deleted if it is attached to an active subcontract. I am currently using the following expression to display the delete button. (Doesn't actually delete, just sets company to inactive.)
<% if (item.company1.subcontracts.Count == 0) { %>
This works for excluding all companies which are attached to subcontracts. However, my subcontract table also has an active_status field. What I really want is to be able to delete companies which are either not attached to a subcontract or are attached to an inactive subcontract (active_status == 0).
How about the following:
<% var subcontracts = item.company1.subcontracts;
if (subcontracts.Count == 0 || subcontracts.Any(x => x.active_status == 0)) { %>
This solves your problem if the active_status is accessible through subcontracts
Maybe I am misunderstanding you, but it seems adding just an OR to the IF should do the trick:
<% if (item.company1.subcontracts.Count == 0 || item.company1.active_status == 0) { %>