Replacing JQuery .val() with JS .value - javascript

I'm going through some legacy code on a submission form and replacing JQuery w/ vanilla JS.
Right now, I have this function that uses .val() (JQuery) to grab the value for an undefined input:
myFunction: function(){
var subscription = $('input[name="subscription_id"]').val();
// Do something with subscription
}
When I run the code in my browser, I get no issues - the code is meant to work only if a subscription is passed into the input - if it's not there, we just get an undefined value. The value returned by the JQuery combo of $() and .val() console logs to 'undefined'.
When I replace the JQuery with vanilla JS, like so:
myFunction: function(){
var subscription = document.querySelector('input[name="subscription_id"]').value;
// Do something with subscription
}
And then try to run my form, I get the following error in the console:
Uncaught TypeError: Cannot read property 'value' of null
Why is this happening? And is there a workaround for this? Any help is appreciated. Thanks in advance.

This happens because
document.querySelector('input[name="subscription_id"]')
does not exist. For vanilla js, you need to check if it exists first, then get the value if it does. jQuery has a silent fail for this.
var element = document.querySelector('input[name="subscription_id"]');
// If it exists, return its value, or null
var subscription = element ? element.value : null;

Just use a condition:
var elem = document.querySelector('input[name="subscription_id"]');
var subscription = elem ? elem.value : "";

Related

Cannot read property of undefined of an apparently NOT undefined - SOLVED

I am using a control of Telerik (AutoCompleteBox) which contains an embedded dropdown control that can be accessed through the property _dropDown. I am using the dropDownItemDataBound event to trigger the following code:
var autoComplete = $find("<%= RadAutoCompleteBox1.ClientID %>");
console.log(autoComplete._dropDown._items);
When I click over the [] in the console I get this (that is expected):
[]
0: b.RadAutoCompleteBox.DropDownItem
_attributes: c.AutoCompleteBoxAttributeCollection {_data: {…}, _keys: Array(0)}
_element: null
_template: null
_text: "Chevrolet TRAVERSE "
_value: "GM1"
Thus I supposed that I could do this:
var autoComplete = $find("<%= RadAutoCompleteBox1.ClientID %>");
console.log(autoComplete._dropDown._items[0]._text); // Chevrolet TRAVERSE
console.log(autoComplete._dropDown._items[0]._value); // GM1
Instead I get:
Uncaught TypeError: Cannot read property '_text' of undefined
It doesn't make sense to me because since autoComplete._dropDown._items is obviously an array (and it's NOT undefined!) I should be able to access it by indexing it and get the property contents. Not?
EDIT:
Following the suggestion of #ChrisG that mentioned that perhaps the arry was STILL empty when I tried to log the data to the console, I changed my code into the event to this (to give it a little time and see what happens):
waitAndDisplay();
function waitAndDisplay(timeout = 50) {
setTimeout(function () {
var autoComplete = $find("<%= RadAutoCompleteBox1.ClientID %>");
console.log(autoComplete._dropDown._items[0]._text);
}, timeout);
}
Indeed it worked however it doesn't seem to be a safe approach. Any idea on how to ENSURE that the data is fully loaded before to try to read it?
SOLUTION:
I was after the suggestion of #ChrisG on use a callback to data loaded and figured that I goofed in the documentation of the control because in fact there IS an event that triggers after the dropdown is fully loaded, so I will post the solution here. This way the callback function to be used is OnClientRequested and not the dropDownItemDataBound as I did initially:
function OnClientRequested(sender, eventArgs) {
var myarray = eventArgs.get_data();
console.log(myarray[0].Text);
console.log(myarray[0].Value);
}
It will return the proper data.

JavaScript value not getting fetched undefined is coming

Why this code lines are not working
let a = document.getElementsByTagName("input")[0].value;
let b = document.getElementsByTagName("input")[1];
b.value = a;
A simple code to get value from one text and paste it into another text.
The issue code be that your code is running before the DOM is fully loaded. In that case you should get the following error:
Uncaught TypeError: Cannot read property 'value' of undefined
To solve the above issue either you can palce your code at the bottom of the body tag or wrap the code with DOMContentLoaded.
Demo:
<script>
document.addEventListener('DOMContentLoaded', (event) => {
let a=document.getElementsByTagName("input")[0].value;
let b=document.getElementsByTagName("input")[1];
b.value=a;
});
</script>
<input value="123"/>
<input />
JavaScript can't get input element.
Why did you decided to get inputs by theirs tagname? Use id's or classes for getting it.
Second is, check it for availability at all.
for example:
const [firstInput, secondInput] = document.getElementsByTagName("input");
if (firstInput && secondInput) {
secondInput.value = firstInput.value || 'default value';
}
Something like that.

how to get/set TestStep's property value using javascript in soapUI?

i have tried using Groovy script.
the following code is to set property value using roovy script:
testRunner.testCase.testSuite.testCases[testCaseName].testSteps[testStepName].setPropertyValue("request",object);
"request" is a property of testStep.
object is a some value.
when i try above code in javascript but i got following error:
org.mozilla.javascript.ecmaerror: TypeErro: org.mozilla.javascript.ecmaerror Cannot read property "testSteps" from undefined.
So please tell me how to use in using javascript?
hurra, i got solution. Please see following code:
var project = testRunner.getTestCase().getTestSuite().getProject();
var testSuite = project.getTestSuiteByName("TestSuite");
var testCasesItr=testSuite.getTestCaseList().iterator();
while(testCasesItr.hasNext())
{
var testStepsItr = testCasesItr.getTestStepList().iterator();
while(testStepsItr.hasNext()){
var testStep = testStepsItr.next();
log.info(testStep.getPropertyValue("response"));
// here you can set property
// testStep.setPropertyValue("request","someValue");
}
}
above code will run for all the testcases.

Unable to get property 'queryselectorall' of undefined or null reference

I am getting below mentioned error in my jQuery function:
var timer = document.getElementById(id);
var pdays = timer.querySelector('.days');
var phours = timer.querySelector('.hours');
var pminutes = timer.querySelector('.minutes');
var pseconds = timer.querySelector('.seconds');
0x800a138f - JavaScript runtime error: Unable to get property 'querySelector' of undefined or null reference
Please suggest to me where I can find jQuery file for .queryselectorall() method or remove above mentioned error in jQuery code ?
here is a suggestion!
maybe your JavaScript is executing before your page loads so your document.querySelectorAll() code is returning data with undefined or null reference (zero length).
try to wrap with onload()
onload = yourFunction(){
document.querySelectorAll()
}

TypeError: $(...) is null - how to use noconflict()

i get error TypeError: $(...) is null.
<script>
$('w_pages').observe('change', function(){
parent.preview.location = 'W/preview/<?=$page['parent_id'] ?>/?p='+$('w_pages').value;
});
$('w_layout').observe('click', function(){
parent.preview.Tiny.showURL('S/layout/'+$('w_pages').value+'?ajax=true',true)
});
</script>
i read that it is because of a conflict. how do i wrap this in noConflict()
There is no conflict here.
You are using the dollar function of Prototype, which returns a reference to the element with id equal to its argument. If no such element exists in the page it returns null, which in turn causes the TypeError.
I don't know why no such element exists in your page or how to make the JS work like it should, but you can avoid the immediate error by checking the return value before calling methods on it:
var wPages = $('w_pages');
if (wPages) {
wPages.observe('change', function(){
parent.preview.location =
'W/preview/<?=$page['parent_id'] ?>/?p='+wPages.value;
});
}
// The same for w_layout
i fixed it. i was indeed missing the element. thanx for putting me in the right direction.

Categories