Search code examples
javascriptphpjquery

how to append hidden field value to input text field before submitting?


<form id="contactForm">
    <input type="text" value="100" id="number" name="number" />
    <input type="hidden" value="00" id="decimal" name="decimal" />
    <input type="submit" name="submit-form" />
</form>
<script>
     var form = document.getElementById('contactForm');
        form.addEventListener("submit", function() {
          var input = document.createElement('number');
          input.type = 'text';
          input.name = 'decimal';
          input.value = '00';
          this.appendChild(input);
        }, true);
</script>

// I want it to append the decimal '00' to the input number before submitting the form.

// I want the result as = 10000


Solution

  • try this

    <html>
    <head></head>
    <title></title>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
    <body>
    
    
    <form id="contact-form">
        <input type="text" value="100" id="number" name="number" />
        <input type="hidden" value="00" id="decimal" name="decimal" />
        <input type="submit" name="submit-form" id="clickme" />
    </form>
    
    </body>
    
    <script type="text/javascript">
        
       $(document).ready(function(){
    
            //in here ,first check the existing value with an alert when document is ready
       		var hiddenValue = $("#decimal").val();
       		alert("before value :" + hiddenValue);
    
    
            //in this part you can assign the new value
    
       		$("#clickme").click(function(){
       			var newhiddenVal = "new decimal";
       			$("#decimal").val(newhiddenVal);
       			var displaynewHiddenvalue = $("#decimal").val();
       			alert(displaynewHiddenvalue);
       		});
       });
    
    
    </script>
    
    </html>

    note : to understand, first it shows the existing value, then in the button click , assign your new value , then display.(display with alsert, because then you can understand easily)

    to assign the values in button click

    var newhiddenVal = "new decimal";
    $("#decimal").val(newhiddenVal);
    

    do above in button click. hope this will help.

    to get 10000 as the new value, in your button click

     $("#clickme").click(function(){
                var newhiddenVal = $("#number").val() +hiddenValue;
                $("#decimal").val(newhiddenVal);
                var displaynewHiddenvalue = $("#decimal").val();
                alert(displaynewHiddenvalue);
            });