0

How can I set the ouput of this javascript function as the value for a hidden input on a html form?

document.write(states[i][1]);

works fine but I cannot get it to fill in the value with the code as shown below.

    if (to == 'abbr'){
        input = input.replace(/\w\S*/g, function(txt){return 
        txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase();});
        for(i = 0; i < states.length; i++){
            if(states[i][0] == input){
            document.getElementById("sid").value = (states[i][1]);
                 }
             }    
         } 
     }       

</script>
<form action="we2.php" method="post">
<input type="text" id="sid" name="s1"/>
<input type="submit" value="Verify">
</form>

What is wrong with this code / what is the right way to do this?

Thanks!

Carter Roeser
  • 360
  • 3
  • 23

5 Answers5

0

This should do it.

HTML:

<input type="hidden" id="HiddenInput" />

JavaScript:

document.getElementById("HiddenInput").value = someFunction();
Edison D'souza
  • 4,551
  • 5
  • 28
  • 39
  • I see that you are trying to assign values to input field using a loop. Have to really added so many input field's in your HTML before calling this function? – Edison D'souza Jun 22 '17 at 05:39
  • I'm not sure what you mean. The script is just state abbreviation conversion array from github so all the inputs above the form are only part of the function. – Carter Roeser Jun 22 '17 at 05:41
  • Your code looks fine to me except this part (states[i][1]). You are asking to set output of a funtion to the input field but states seems to be a var. Please rectify. – Edison D'souza Jun 22 '17 at 05:47
0

Have you checked if states[i][0] == input evaluates to true?

Jan Ciołek
  • 1,796
  • 3
  • 17
  • 32
0

Write JavaScript code after html code end in your page or at the end of page.

ShivamRajput
  • 146
  • 1
  • 5
0

I found a easier solution by just turning the entire function into a variable then the variable into the DOM:

var response = abbrState('<?php echo $_GET['state']; ?>', 'abbr');

document.getElementById("sid").value = response;
Carter Roeser
  • 360
  • 3
  • 23
0

The following should work.

HTML:

<div style="display:none" id="example"></div>

Javascript:

function addTextNode(text) {
  var newtext = document.createTextNode(text),
      element = document.getElementById('example');

  element.appendChild(newtext);
}

function yourFunctionDataHere(){
    return 'test1234';
}


addTextNode(yourFunctionDataHere());

Just make sure, that the return type of your function is of type string. If you want to see the output simply remove the style="display:none" from the div in the above example.

Try it online on jsfiddle.

Sotiris Kiritsis
  • 3,178
  • 3
  • 23
  • 31