Javascript: How to add a hidden entry tag in a form when the submit button is clicked?

advertisements

I have variable name and value for hidden input tag that I want to append into form right when submit button is clicked. How do I go about coding it?

Here's my code:

<script type="text/javascript">

hname="reference";
hvalue="1";

function insertInput(){
document.write( "<input type='hidden' name='" + hname + " ' value=' " + hvalue + " '/><br/>");
}

</script>

<form id="form1">
    <p><label>Username:</label> <input type="text" name="username" size="10"/></p>
    <p><label>Password:</label> <input type="password" name="password" size="10"/></p>

    <p id="hidden"><!-- Insert Hidden input tag here --></p>

    <button type="submit' onClick="insertInput();">Log In</button>
</form>

I can't seem to get it work. Please help! Thanks in advanced!


Try this:

<form id="form1">
        <p><label>Username:</label> <input type="text" name="username" size="10" /></p>
        <p><label>Password:</label> <input type="password" name="password" size="10" /></p>

        <p id="hidden"><!-- Insert Hidden input tag here --></p>

        <button type="submit" onclick="return insertInput();">Log In</button>
</form>

<script type="text/javascript">

    hname="reference";
    hvalue="1";

    function insertInput(){
        var para, hiddenInput, br;
        para = document.getElementById('hidden');
        hiddenInput = document.createElement('input');
        hiddenInput.type = 'hidden';
        hiddenInput.name = hname;
        hiddenInput.value = hvalue;
        para.appendChild(hiddenInput);
        br = document.createElement('br'); //Not sure why you needed this <br> tag but here it is
        para.appendChild(br);

        return false; //Have this function return true if you want to post right away after adding the hidden value, otherwise leave it to false
    }

</script>