I have this Javascript function which i use to append elements do my form. When the form is submitted, all elements are passed in as params.
Here's the problem. The elements that my function appends are part of a Hash. This basically works as the rails "nested-attributes".
All seems to be working fine, except when one of the "Hashs" is empty. When i delete all elements from the collection, the hash params is not passed to the controller.
Example (Imagine i appended Honda, Toyota, Hyundai using my JS function)
Cars
[Honda]
[Toyota]
[Hyundai]
This is how the hash is set up in the JS function (every time i click the "add"):
CarsHash.name= "cars_hash"+"["+"tmp_cars"+"]"+"["+i+"]"+"car_name"
If i were to submit the form, the values would be passed as Hash to the controller like this:
cars_hash=>{tmp_cars=>"{"1"=>{car_brand=> "honda"},"2"=>{car_brand=> "toyoda"},"3"=>{car_brand=> "hyundai"}"}
However, if i decide to delete all those values from the hash (using the delete button which also has functionality stated on the JS function) and submit the form, the Hash is not even present as a param. Then, when i get to my controller and i try to populate the variable i use for iterating/inserting into my DB:
Controller
cars_hash = params[:cars_hash][tmp_cars]
It gives me this error:
undefined method `[]' for nil:NilClass
I understand, the param is not even present so its essentially nil. I tried with all this possibly options:
if not params[:cars]["tmp_cars"].blank?
if not params[:cars]["tmp_cars"].empty?
if params[:cars]["tmp_cars"].present?
if params[:cars]["tmp_cars"] != nil
But no luck. Can anyone suggest me a way to get this to work? Again, the param will only be not nil IF the hash as a value. For it to have a value, an element must be appended to the document through the JS function.
Try doing:
cars_hash = params[:cars_hash] && params[:cars_hash][tmp_cars]
I would strongly recommend installling andand gem which is perfect for situations like this. With this gem you can wirte the code above like:
cars_hash = params[:cars_hash].andand[tmp_cars]
UPDATE:
Your code was not working because params[:cars_hash] returned nil, on which you were trying to call [] method, and such a method is not defined for nil object. Hence you need to check whether params[:cars_hash] is nil or not before you call anything on it.
&& operator have this nice property that it is not even executing the right argument whan the left argument is falsy - there is no point of doing this. Since every expression in ruby returns value of the last executed command, && returns whatever left expression returns if it is falsy (false or nil) and otherwise it runs the expression on its right side and returns its value. This is pretty common to use this && in this context in Ruby.
Related
I just want to verify the element exists somehow. Trying to print it so I can compare against a string or something.
Here is the problematic code.
session = HTMLSession()
r = session.get('https://www.walmart.com/ip/Sony-PlayStation-5-Video-Game-Console/994712501')
r.html.render(timeout=20)# this call executes the js in the page
oos=r.html.xpath('/html/body/div[1]/div[1]/div/div[2]/div/div[1]/div[1]/div[1]/div/div/div/div/div[3]/div[5]/div/div[3]/div/div[2]/div[1]/section/div[2]/div/div/div/div/div')
print(oos)
#print returns []
I try to print(oos.text) and I get a callback error
#'list' object has no attribute 'text'
also tried print(oos.full_text) same error
'list' object has no attribute 'full_text'
Seems like its a list? So I tried to iterate through it.
for i in oos:
print(i)
#Prints absolutely nothing!
Pretty sure the element doesn't exist. Based on an examination of print(html) I believe I am being redirected to a capthcha page.
Therefore I am going to assume that the [] is essentially an empty list and all code is more or less doing what it's supposed to.
I'm trying to set up a JMeter run that does this:
Make Rest API request
Use a JSON Extractor to check the response for a given array of values.
I define success as all of the "Items[*].Success" nodes equaling "true"
If the response is successful, break out of the loop (continue to step #5)
If the response is a failure, go back to step #1
... the rest of my test steps
Here's what I've set up to do this:
Use a BeanShell Assertion to initialize a loop variable:
${__setProperty(is_any_calc_pending,true)};
While Controller with a condition set to
${__BeanShell(props.get("is_any_calc_pending")}
My problem is here, the loop never stops
Make Rest API call (This works as expected)
JSON Extractor (This also works as expected)
Names of created variables = api_successes
JSON Path expressions = $.Items[*].Success
Match No. = -1
Compute concatenation = checked
Default Values = unset_api_successes
JSR223 PostProcessor set to Javascript to update the value of the loop variable.
Here's my code for step #5. It simply checks whether or not there's a "false" in the api_successes_ALL variable that the JSON Extractor creates.
var api_successes_ALL = vars.get('api_successes_ALL')
var all_successful = api_successes_ALL.indexOf('false') < 0
props.put('is_any_calc_pending',!all_successful)
Most of this works as I expect; I can check this using the Debug Sampler. The problem I'm having is that the loop never stops. The condition never causes the loop to break.
In the log, I see this line:
DEBUG o.a.j.c.WhileController: Condition value: 'false'
The documentation says that the While Controller will continue until the condition is false. From what I see in the log, the condition is always false. I also don't understand why the While Controller never sees that the value of my is_any_calc_pending changes. I can see in the Debug Sampler that the value changes.
Is the variable being re-initialized somehow? I'm wondering if my variable or property is going out of scope.
I got it. Here's what I did:
Simple Controller (I'm not sure if this is necessary)
Make Rest API call to initiate process
While Controller, see condition code below
Make Rest API call to check status
JSON Extractor with the same property values I listed in my question
I didn't expect it, but the While Controller has access to the variables generated in the JSON Extractor. I think the Simple Controller may have caused this.
While Controller condition. I left the log.warn() call in there to show how I debugged the condition.
${__javaScript(
log.warn( vars.get("api_successes_ALL") );
!!vars.get("api_successes_ALL") ?
(vars.get("api_successes_ALL").indexOf("false") >= 0) :
"true";
)}
Found it...
The JSON PostProcessor has to be a child of the Request, not of the While Loop.
Lost a few hours on this.
WhileLoop
HTTP Request
JSON extractor
Delay
I'm trying to use jQuery and AJAX to validate that users entered a number in a particular field and that they didn't leave it blank and I'm a little confused as to why I can seem to do one, but not the other.
I'm doing this in a jQuery change() function so any time they change the value in that field, it updates it in the database without refreshing the whole page and it works fine until I try to use isNull() to validate.
I'm saving their input to a variable called UserInput and first checking to make sure it's a number with this:
if (!isNaN(UserInput))
which works perfectly. I'm also trying to check and make sure it isn't empty by using this:
if (isNull(UserInput))
Intellisense completes isNull() for me just like it did for isNaN() and all appears well in Visual Studio, it compiles without error. I've also tried isNullOrUndefined() here with a similar result, intellisense completes it for me and all seems well. Right up until I change the value in the field, at which point it promptly gives me this error:
JavaScript runtime error: 'isNull' is undefined.
I'm not sure why it's undefined (especially since intellisense is completing it for me) or how to go about defining it.
I also tried this because it seemed like it covered all the bases, not just isNull():
https://stackoverflow.com/a/5515349/8767826
and I put an alert() inside the if and I didn't get an error, but my alert didn't fire either.
The end goal is to get it to change to a zero on the client side if they leave do leave it blank.
Anyway I'm kind of stumped and I appreciate any help anyone can offer.
Thanks
There's no need for an isNull function; you can check
if (UserInput === null)
isNaN exists because NaN, unlike every other value in JavaScript, is not equal to itself.
But null doesn't mean the field is blank! If the field is blank, its value will be the empty string. Check for that instead:
if (UserInput === '')
I am trying to write a similar true/false statement, Similar to how the .selected() method would work in Angular typescript.
The idea is to show an image if the calculation or *ngIf statement evaluates to True. The code is written in the app.html side
Code:
<img src="/project/x.png" *ngIf="selectedimage.indexOf(v) !== -1"><a href="{{i['link']}}" target="blank" (click)="update_viewed(z)">
There is a *ngFor statement right before this code, with ;let z = index at the end. The overall code creates a # of rows dynamically depending on how many elements exist in an array. (code not provided for this here.) Then, if the user clicks on the href link, the index value is passed into a method, which pushes it to an array. in console.log(this.selectedimage) I can see the values being added in each time I click the href reference. Not sure why the ngIf logic isn't working.
All help much appreciated.
You cannot use indexOf with *ngIf on the template, I would recommend you to create a function that returns true/false based on the logic. Use indexOf within the function and call it with *ngIf
I'm using a script template to create chunks of code when a user clicks a button, this works fine, but I want to be able to calculate a total within these cloned regions so I have a in-line onBlur statement as follows
onblur = "multiply.call(this, this.form.elements.Qty{{ID}}.value, this.form.elements.Cost{{ID}}.value, this.form.elements.Total{{ID}})"
As the cloning function updates ID to a value this evaluates to
onblur = "multiply.call(this, this.form.elements.Qty1.value, this.form.elements.Cost1.value, this.form.elements.Total1)"
My function is
function multiply(one, two, three) {
console.dir(three);
document.getElementById(three).value = (parseFloat(one) + parseFloat(two)).toFixed(2); // error here
};
If I display one and two they have the values from the form, however I get an error writing back to the for of Uncaught TypeError: Cannot set property 'value' of null.
The console shows the ID of the element three as Total1
I think this might be something to do with the jQuery clone and the DOM not being updated. The values are passed OK, but the object might not be.
Any ideas?
document.getElementById(three) returns no match (thus the undefined).
You're passing an element to your function multiply as parameter three, and you're later using it as a string representing the ID of it.
If three is verified to be an element, don't call document.getElementById(three).value in first place, but directly three.value.