/    Sign up×
Community /Pin to ProfileBookmark

Get Value in Javascript is input exists

I have a JS variable set var myvar = 0; Easy.

I want to run an form onsubmit function that says if a field with a specific ID exists get that value and reset myvar to this value.

Easy enough if I know it’s there

var myvar = parseInt(document.getElementById(‘inputID’).value);

But if inputID doesn’t exist I want to leave it at 0;

Any ideas?

to post a comment
JavaScript

3 Comments(s)

Copy linkTweet thisAlerts:
@cootheadSep 17.2020 — Hi there kiwis80,

does this help...

<i>
</i>&lt;!DOCTYPE HTML&gt;
&lt;html lang="en"&gt;
&lt;head&gt;

&lt;meta charset="utf-8"&gt;
&lt;meta name="viewport" content="width=device-width,height=device-height,initial-scale=1"&gt;

&lt;title&gt;Untitled document&lt;/title&gt;

&lt;/head&gt;
&lt;body&gt;

&lt;!--&lt;input id="inputID" type="text" value="20"&gt; remove comment to test for change --&gt;

&lt;script&gt;
(function( d ) {
'use strict';
var myvar = 0;
if ( d.getElementById( 'inputID' )) {
myvar = d.getElementById( 'inputID' ).value;
}
console.log( myvar );
}( document ));
&lt;/script&gt;

&lt;/body&gt;
&lt;/html&gt;


[i]coothead[/i]
Copy linkTweet thisAlerts:
@tazmeahDec 29.2020 — @coothead's answer looks satisfactory to me, assuming one interpretation of your question. I'm going to assume a different interpretation where the input always exists but is not required to submit the form. If there is no value in the input, set myvar to 0, otherwise set myvar to the numerical value of the input. If that is what you mean, I'd use this script.

var myvar = parseInt(document.getElementById("inputID").value) || 0;
Copy linkTweet thisAlerts:
@VITSUSADec 29.2020 — Thanks coothead, you have provided very easy solution of this problem. It's really helpful.
×

Success!

Help @kiwis spread the word by sharing this article on Twitter...

Tweet This
Sign in
Forgot password?
Sign in with TwitchSign in with GithubCreate Account
about: ({
version: 0.1.9 BETA 4.24,
whats_new: community page,
up_next: more Davinci•003 tasks,
coming_soon: events calendar,
social: @webDeveloperHQ
});

legal: ({
terms: of use,
privacy: policy
});
changelog: (
version: 0.1.9,
notes: added community page

version: 0.1.8,
notes: added Davinci•003

version: 0.1.7,
notes: upvote answers to bounties

version: 0.1.6,
notes: article editor refresh
)...
recent_tips: (
tipper: @Yussuf4331,
tipped: article
amount: 1000 SATS,

tipper: @darkwebsites540,
tipped: article
amount: 10 SATS,

tipper: @Samric24,
tipped: article
amount: 1000 SATS,
)...