Passing a value from one field to another

I want to pass the value 9112232453 one text field to another.

I know that I need Javascript for this, but I don’t know how to do it.

HTML

 <form method = "post" action=""> <input type="checkbox" name="phone" value="9112232453" onclick='some_func();' > <input type="text" name="phone" value="" id="phone"> <input type="submit" name="Go"> </form> 

Then later I want to use the value in my php.

+5
source share
4 answers

You can use JS. to accept the parameter (this.value) as:

 <script> var some_func = function (val){ var input = document.getElementById("phone"); input.value = val; } </script> <form method = "post" action=""> <input type="checkbox" name="phone" value="9112232453" onclick='some_func(this.value);' > <input type="text" name="phone" value="" id="phone"> <input type="submit" name="Go"> </form> 
+3
source

The best way not to enforce HTML with Javascript event handlers .

So, you can add a DOMContentLoaded event listener to the document, and as soon as the DOM is loaded:

  • You add a change event listener to input[type=checkbox] , and then:

    1.1. If checked , then you change input#phone value to its value

    1,2. If not, then you empty the input#phone value.

 document.addEventListener('DOMContentLoaded', function() { document.getElementById('cbphone').addEventListener('change', function(e) { var phone = document.getElementById('phone'); if (this.checked) { phone.value = this.value; // you can even enable/disable the input#phone field, if you want to, eg: // phone.disabled = false; } else { phone.value = ''; // phone.disabled = true; } }); }); 
 <form method="post" action=""> <input type="checkbox" name="cbphone" id="cbphone" value="9112232453"> <input type="text" name="phone" id="phone"> <input type="submit" name="Go" value="Go"> </form> 
+1
source

before submitting the form, use validation and check if the field value is filled or not. if so, get the value of the field.

 if(document.getElementBy("fieldIdfirst").value!="") { document.getElementBy("fieldIdSecond").value=document.getElementElementById("fieldIdfirst"); } 

Thanks..

0
source

Try the following: http://jsfiddle.net/yhuxy4e1/

HTML:

 <form method = "post" action=""> <input type="checkbox" name="phone" value="9112232453" onclick='some_func();' id="chk_phone"> <input type="text" name="phone" value="" id="txt_phone"> <input type="submit" name="Go"> </form> 

JavaScript:

 some_func = function() { var checkBox = document.getElementById('chk_phone'); var textBox = document.getElementById('txt_phone'); textBox.value = checkBox.value; } 
0
source

Source: https://habr.com/ru/post/1232299/


All Articles