jQuery: Each Loop Oddity - loops

I want to go through all fields of a form and determine if the fields are populated with data. When all fields are given, I'd like a button save to appear.
This is the Fiddle with code, that works (!) ...
This is the same in JavaScript.
The jQuery-Object to iterate through:
formElements = $ 'form input[type="text"], form input[type="number"], form textarea'
The Function:
formFilled = ->
filled = true
formElements.each ->
if $(this).val().length is 0
filled = false
filled
The Event-Handler:
formElements.on 'keyup', (keyup) ->
keyup.preventDefault()
if formFilled()
save.show()
else
save.hide()
Any suggestions?

# I know the answer:
JavaScript validates the number-input fields and accepts only values that are numbers.
I stupidly tested those fields with text input ... silly.
The code is fine. Just the testing was bad. Sorry for wasting your time.
This works:
formInputs = $ 'input[type="text"], input[type="number"], textarea'
formFilled = ->
filled = true
formInputs.each ->
if $(this).val().length is 0
filled = false
filled
formInputs.on 'keyup', (keyup) ->
if formFilled()
saveButton.show()
else
saveButton.hide()

Related

Transforming null into array.length = 0

Probably a noob Question: On my server, there is a filter which returns all available options if an array of the filter object has length.0 for certain options.
Now if say i have an input "All Options" from the user side, this option when clicked must somehow tell the array to have length.0, so the server returns all options .
I tried to set the Input to
<mat-option [value]= null >Alle</mat-option>
But that results in an array that has the value null instead of no length at all.
I also tried
If (data.array[1] == undefined){
data.array.length == 0
}
But that did not work
Leave the value to null and then do it like this:
if (!data.array) {
data.array = [];
}

How to remove the text from label when checkbutton is not being checked?

i'm working on this code.i want to make it display the text from the checkbutton on the label, and also remove the text when the checkbutton is not being checked.the first question is i can't remove it since the system responses
TypeError: list indices must be integers or slices, not str
the other question is i want to make a shuffle button which can shuffle the text in the label.i tried random.shuffle() but it seems doesn't work. thanks in advance!!
import tkinter as tk
import random
window = tk.Tk()
checkbutton_frame = tk.Frame(window)
checkbutton_frame.grid(column=0, row=1)
contentvar = tk.StringVar()
label = tk.Label(window, textvariable=contentvar,
bg='white', font=('Arial', 10), width=20, height=20, wraplength=50)
label.grid(column=6, row=1, padx=20,
pady=20, columnspan=2)
cb_list = ['ray', 'kevin', 'jacky']
cb_vars = []
checked = []
check_list = 1
def display():
for text, var in zip(cb_list, cb_vars):
if var.get():
checked.append(text)
contentvar.set(list(set(checked)))
else:
for i in checked:
del checked[i]
def shuffle():
random.shuffle(checked)
for r, element in enumerate(cb_list):
var = tk.BooleanVar(window, False)
cb = tk.Checkbutton(checkbutton_frame, variable=var,
text=element, command=display)
cb.grid(column=check_list, row=r, sticky='w')
cb_vars.append(var)
shuffle_button = tk.Button(window, text='SHUFFLE', command=shuffle)
shuffle_button.grid(column=8, row=2)
window.mainloop()
In the function display() you have:
else:
for i in checked:
del checked[i]
but checked is a string, so i will be a string. Try:
for i, dummy in enumerate(checked):
There were a few more things: the function display() appends to the list checked for checked items even if they are already there. This makes it look like the delete does not work. You can't see that you have to many of any item as you put them through a set before you load them into the label as set doesn't allow identical items.
Then you should set the contentvar after all processing, i.e. last in the function. Here's a version that works:
def display():
for text, var in zip(cb_list, cb_vars):
if var.get():
if text not in checked:
checked.append(text)
else:
if text in checked:
checked.remove(text)
contentvar.set(checked)
Now the texts in the label appear in the order you put them there.
The function shuffle() works just fine and shuffles the list checked. But you will have to load it into the label as well:
def shuffle():
random.shuffle(checked)
contentvar.set(checked)

Using checkboxes to create an array

A background to why im trying to do this.
I am creating a program for work, this is one of many way of doing this process, where users select test that they have carried out, around 50 possible test using a userform that I've made. From the selection it runs through each userform based off which checkboxes were ticked, without the need to choose another test.
i.e. if they select 1,2,5 then the program will eventually load UserForm1 -> UserForm2 -> NOT UserForm3 -> NOT UserForm4 -> UseeForm5
The idea is that the user selects the options they want then based off the options selected create an array of either 0 if they didn't select the option or (1,2,3,4...) if they did, this number depends upon which checkbox was selected. i.e CheckBox1 = 1 CheckBox2 = 2 etc.
From this array I think i'll be able to select the correct userform using the .find feature in excel with a for loop.
But I have an issue when I run my code below,
Sub List_Create()
Dim tests(5) As Integer
If CheckBox1.Value = True Then
tests(0) = 1
Else: tests(0) = 0
End If
If CheckBox2.Value = True Then
tests(1) = 2
Else: tests(1) = 0
End If
If CheckBox3.Value = True Then
tests(2) = 3
Else: tests(2)= 0
End If
If CheckBox4.Value = True Then
tests(3) = 4
Else: tests(3) = 0
End If
If CheckBox5.Value = True Then
tests(4) = 5
Else: tests(4) = 0
End If
End Sub
I get a
runtime 424 error object required.
Which when debugged is on the line If CheckBox1.Value = True Then
Where have i gone wrong with my code? Is this possible, im not sure if it is?
You need to explicitly reference the userform to evaluate the checkbox value.
If userformX.CheckBox1.Value = True Then

Can't sum values in Angularjs if one value is an empty string

I am building a simple Appgyver mobile app using Angularjs and Coffeescript - I'm a beginner with both of these.
I wish to determine the total cost for a list of up to 20 items stored on the database. However, there may be less than 20 items.
I have attempted to do the calculation with ng-bind, which works perfectly as long as all strings contain values. However, if there are less than 20 pairs (values go up to q20 and p20) then the calculation returns NaN.
I would like to determine the total of all existing values for the list. I have looked at numerous examples on stackoverflow, Angularjs.org and other sites and have experimented with a myriad of alternative methods, however I think I lack the basic understanding of how to make this work. Any help would be appreciated.
This is the code I have used, shortened to 3 pairs instead of 20:
<span ng-bind="client['q1'].price * client['p1'].price + client['q2'].price
* client['p2'].price + client['q3'].price * client['p3'].price"></span>
This is the existing controller:
angular
.module('client')
.controller("ShowController", ($scope, Client, supersonic) ->
$scope.client = 0;
$scope.showSpinner = true
$scope.dataId = undefined
_refreshViewData = ->
Client.find($scope.dataId).then (client) ->
$scope.$apply ->
$scope.client = client
$scope.showSpinner = false
supersonic.ui.views.current.whenVisible ->
_refreshViewData() if $scope.dataId
supersonic.ui.views.current.params.onValue (values) ->
$scope.dataId = values.id
_refreshViewData()
$scope.remove = (id) ->
$scope.showSpinner = true
$scope.client.delete().then ->
supersonic.ui.layers.pop()
)
I think you are overloading (in the linguistic sense, not the coding sense) ng-bind. Doing all of that code in your HTML is messy and is not what it was created for. You would be better off doing the math in your controller, and then referencing it in ng-bind. You have only 3 pairs here, but you say you have 20, and could be more, so do it that way:
<span ng-bind="totalPrice"></span>
And in your controller:
var setTotalPrice = function() {
var ret = 0, i, maxClient = 6, client = $scope.client; // or however else you keep track of them
for (i=1;i<=maxClient;i++) {
if (client['q'+i] && client['q'+i].price && !isNaN(client['q'+i].price) &&
client['p'+i] && client['p'+i].price && !isNaN(client['p'+i].price)) {
ret += (client['q'+i].price * client['p'+i].price);
}
}
$scope.totalPrice = ret;
};
$scope.setTotalPrice = setTotalPrice;
setTotalPrice();
Just call setTotalPrice in your controller whenever you want, or on an ng-click.
Please don't abuse ng-bind for calculations! Instead calculate the values in your controller and bind the resulting value.
Problem with your code is -if any of the values is not a number your result becomes NaN. In the controller function you check for the presence of value and then operate. You may want to check whether the value is non-null as well as a number string and then operate on it.

get_by_id() not returning values

I am writing an application that shows the user a number of elements, where he has to select a few of them to process. When he does so, the application queries the DB for the rest of the data on these elements, and stacks them with their full data on the next page.
I made an HTML form loop with a checkbox next to each element, and then in Python I check for this checkbox's value to get the data.
Even when I'm just trying to query the data, ndb doesn't return anything.
pitemkeys are the ids for the elements to be queried. inpochecks is the checkbox variable.
preqitems is the dict to save the items after getting the data.
The next page queries nothing and is blank.
The comments are my original intended code, which produced lots of errors because of not querying anything.
request_code = self.request.get_all('rcode')
pitemkeys = self.request.get_all('pitemkey')
inpochecks = self.request.get_all('inpo')
preqitems = {}
#idx = 0
#for ix, pitemkey in enumerate(pitemkeys):
# if inpochecks[ix] == 'on':
# preqitems[idx] = Preqitems.get_by_id(pitemkey)
# preqitems[idx].rcode = request_code[ix]
# idx += 1
for ix, pitemkey in enumerate(pitemkeys):
preqitems[ix] = Preqitems.get_by_id(pitemkey)
#preqitems[ix].rcode = request_code[ix]
Update: When trying
preqitems = ndb.get_multi([ndb.Key(Preqitems, k) for k in pitemkeys])
preqitems returns a list full of None values, as if the db couldn't find data for these keys.. I checked the keys and for some reason they are in unicode format, could that be the reason? They look like so.
[u'T-SQ-00301-0002-0001', u'U-T-MT-00334-0007-0002', u'U-T-MT-00334-0008-0001']
Probably you need to do: int(pitemkey) or str(pitemkey), depending if you are using integer or string id

Resources