简体   繁体   中英

Passing value from a function into a input field

Problem: I'm trying to pass a return value from a function into a input field.

I get no errors the field is just blank.

Question: Why is my code not working?

HTML

<tr>
<td>Quantity to be dredged</td>
<td><input type="number"  class="" id="shorePipe"></input></td>
</tr>

JavaScript

var shorePipe = function() {
  var val = 100;
  var val2 = 100;
  var total = val * val2 / 100;
  // return total;
  document.getElementById('shorePipe').value = total;
};

Thanks in advance!

Since your code works perfectly fine (beside </input> ), the only issue I see here is that you're probably not calling shorePipe(); once the DOM is read and ready .

jsBin demo

So put your JS right before the closing </body> tag

<script>
var shorePipe = function() {
  var val = 100;
  var val2 = 100;
  var total = val * val2 / 100;
  // return total;
  document.getElementById('shorePipe').value = total;
};
shorePipe();
</script>

</body>

notice also that </input> is invalid. <input> is in the group of void elements and should not have a closing tag.

You have to call the function

shorePipe();

Here's a fiddle: https://jsfiddle.net/2vxdyvgz/

  1. Input doesn't need to close itself.
  2. Make sure you actually call your JS function somewhere.

I created this JSFiddle for you: https://jsfiddle.net/pd12edbp/2/

<input type="number"  class="" id="shorePipe" readyonly>

JS:

var shorePipe = function() {
   var val = 100;
   var val2 = 100;
   var total = val * val2 / 100;
   // return total;
   document.getElementById('shorePipe').value = total;
};

$(document).ready(function(){
    shorePipe();
});

in your original post, you were passing the value to the element with ID shorePipe, and your input had ID avgSubPipe

element ID's have to match. ANd, you have to fire the function

the HTML

<tr>
<td>Quantity to be dredged</td>
<td><input type="number"  class="" id="avgSubPipe" readonly ></td>
</tr>

and the Javascript:

var shorePipe = function() {
  var val = 100;
  var val2 = 100;
  var total = val * val2 / 100;
  // return total;
  document.getElementById('shorePipe').value = total;
};

// calling function
shorePipe();

https://jsfiddle.net/yhz7syhs/1/

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