将值从一个字段传递到另一个字段

时间:2015-09-25 18:45:47

标签: javascript php html

我想将一个文本字段的值9112232453传递给另一个文本字段。

我知道我需要Javascript,但我不知道该怎么做。

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> 

然后,我想在我的php中使用该值。

4 个答案:

答案 0 :(得分:3)

你可以使用JS。函数以param (this.value)为例:

<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> 

答案 1 :(得分:1)

最好的方法是to not obtrude the HTML code with Javascript event handlers

因此,您可以向文档添加DOMContentLoaded事件侦听器,并在加载DOM后立即执行:

  1. 您向change添加input[type=checkbox]事件监听器,然后:

    1.1。如果该复选框为checked,则您将input#phone&#39; s value更改为其值

    1.2。如果没有,则清空input#phone的值。

  2. &#13;
    &#13;
    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, e.g:
          // phone.disabled = false; 
        }
        else {
          phone.value = '';
          // phone.disabled = true; 
        }
      });
    });
    &#13;
    <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>
    &#13;
    &#13;
    &#13;

答案 2 :(得分:0)

在提交表单之前使用验证并检查字段值是否已填满。如果是,则获得该领域的价值。

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

谢谢..

答案 3 :(得分:0)

试试这个: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;
}