简体   繁体   中英

Replacing JQuery .val() with JS .value

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 : "";

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM