0

I am trying to fetch the value from text input in HTML to a variable in javascript. An uncaught type error had appeared. The following are my HTML code:

 <form name="purchaseform" id="formma">
 KJW M700 <br>
 <input name='buyM700' type='text' id='1234'>
 <input name='caller' type='button' value='click here' onClick='call()'>
 </form>

The following are my Javascript code:

var m700 =  document.purchaseform.buyM700.value;
function call() {
  confirm (m700);
};

Thank you for helping me in advance.

Phil
  • 128,310
  • 20
  • 201
  • 202

2 Answers2

1

Try following code, your variable declare before call the function when field is empty:

function call() {
  var m700 =  document.purchaseform.buyM700.value;
  confirm (m700);
};
Hanif
  • 3,469
  • 1
  • 9
  • 15
  • 1
    Not the cause of the error but this should fix it and also make the `call` function make **much** more sense :) – Phil Nov 16 '17 at 03:32
  • In my console I'm not getting this type or error. – Hanif Nov 16 '17 at 03:36
  • What I meant was the field being empty would not cause the error. It's highly probable OP's JS code runs **before** the element(s) exist. Moving the DOM code into the `call()` function as you have done solves this problem. – Phil Nov 16 '17 at 03:42
  • Yes @Phil you asked about this point but Vladimir dose not reply in above :) – Hanif Nov 16 '17 at 03:45
0

You can access the form via the forms HTMLCollection of the document

var m700 =  document.forms.purchaseform.buyM700.value;
function call() {
  confirm (m700);
};
Neil Anderson
  • 1,087
  • 10
  • 19
  • It's an [`HTMLCollection`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLCollection), not an array – Phil Nov 16 '17 at 03:27
  • corrected, thank you – Neil Anderson Nov 16 '17 at 03:28
  • Given `document.purchaseform` [*should work*](https://stackoverflow.com/questions/47321000/javascript-uncaught-type-error-property-cant-be-read-undefined-variable#comment81593186_47321000), I doubt this is the problem – Phil Nov 16 '17 at 03:31