Using result of javascript query as input for HTML form

631 views Asked by At

Is it possible to directly use the result of a Javascript function as an input value for an HTML form?

<form class="my-form" action="fileUpload.php" method="POST" enctype="multipart/form-data">
    <input type="hidden" name="User_id" value="getValue();">
    <input type="submit" value="Submit"/>
</form>

This is clearly not correct, but I hope it communicates what I am trying to do. I would like the returned result of JS function getValue(); to act as the input value.

2

There are 2 answers

2
dariru On

In that implementation, no it is not possible to equate the value attribute inside the input tag to a JavaScript function.

According to w3.org, the value attribute can only equal

String without line breaks

Any string that contains no line feed (U+000A, “LF”) or carriage return (U+000D, “CR”) characters.

I am not sure what is inside the getValue() function, but you can call a click event handler when the submit button is clicked and run that getValue() function.

Ex.

<form class="my-form" action="fileUpload.php" method="POST" enctype="multipart/form-data">
    <input type="hidden" name="User_id">
    <input type="submit" value="Submit" onclick="getValue();"/>
</form>

I hope it guides you well.

4
JonSG On

While it is technically possible to do something like this:

<script>
  function getValue(){ return "foo"; }
  document.write("<input type='hidden' name='User_id' value='" + getValue() + "' />");
</script>

That is typically frowned upon as there are scoping issues and page rendering implications. The more accepted way would be to do something more like this..

function getValue(){ return "bar"; }

window.addEventListener("load", function(event){
    document.querySelector("input[name='User_id']").value = getValue();
});

or potentially at form submit or submit button click with something like:

function getValue(){ return "bar"; }

document.querySelector("input[type='submit']").addEventListener("click", function(){
    document.querySelector("input[name='User_id']").value = getValue();
});

Though I am not keen on it myself, it would be possible to do the same as above with:

<input type="submit" value="Submit" onclick="setUserId();"/>

Then later in say a end of body script block do:

function getValue(){ return "bar"; }

function setUserId(){
    document.querySelector("input[name='User_id']").value = getValue();
}