如何从一个表单获取价值并使用javascript发布到另一个表单?

时间:2016-09-18 10:29:54

标签: javascript html forms

我在同一页面中有两种形式, 表格1 ID:主页/ 表格2 ID:联系方式 单击发送按钮后,我需要在form2(联系人)的文本框中填写表单(home)中填写的值。

<form id="home" method="get" action="#portfolio" role="form"> 
  <select class="form-control" id="pd_howmuch">
         <option>HOW MUCH ?</option>
         <option>$100</option>
         <option>$200</option>
        </select>
        <input id="pd_fname" type="text" name="name">
        <input id="pd_lname" type="text" name="surname">
        <input id="pd_zipcode" type="tel" name="zipcode">
        <input id="pd_applynowbt" type="submit" value="Send">
    </form>
<section id="portfolio">
<form id="contact" method="post" action="contact.php" role="form">
       <select class="form-control" id="howmuch1">
         <option>HOW MUCH ?</option>
         <option>$100</option>
         <option>$200</option>
        </select>
        <input id="fname1" type="text" name="name">
        <input id="lname2" type="text" name="surname">
        <input id="zipcode2" type="tel" name="zipcode">
        <input id="applynowbt" type="submit" value="Submit">
    </form>
</section>

3 个答案:

答案 0 :(得分:0)

好的如果我理解正确,您希望将信息从第一个表单填充到第二个表单。

因此要完成此任务,您需要将事件处理程序附加到第二个表单并防止默认行为

工作demo希望能帮到你

vhost

答案 1 :(得分:0)

var sourceForm = document.getElementById("source-form");
var targetForm = document.getElementById("target-form");

function findTargetNode(nodeName, name) {
	
	var targetElems = targetForm.elements;
	
	for (var i = 0; i < targetElems.length; i++) {
		
		var elem = targetElems.item(i);
		
		if (elem.nodeName.toLowerCase() === nodeName && elem.name === name) {
			return elem;
		}
	}
}

function setNodeValue(node, type, value) {
	
	if (type === 'select')
	{
		for (var i = 0, options = node.options; i < options.length; i++) {
			
			if (options[i].value === value) {
				options[i].setAttribute('selected', 'true');
			}
			else {
				options[i].removeAttribute('selected');
			}
		}
	}
	// else if (type === 'checkbox' || type === 'radio') { /* ... */ }
	else {
		node.value = value;
	}
}


sourceForm.addEventListener("submit", function(e) {
    
	for (var i = 0, elems = sourceForm.elements; i < elems.length; i++) {
		
		var elem = elems.item(i);
		
		if (!elem.name) {
			continue;
		}
		
		var type = elem.nodeName.toLowerCase();
		var targetNode = findTargetNode(type, elem.name);
		
		if (!targetNode) {
			continue;
		}
		
		setNodeValue(targetNode, type, elem.value);
	}
	
	e.preventDefault();
	// targetForm.submit();
	
}, false);
    <form id="source-form" action="javascript:void(0)" role="form">
		<select class="form-control" id="my-select" name="my-select">
			<option value="-1">HOW MUCH ?</option>
			<option value="1">1</option>
			<option value="2">2</option>
		</select>
		<input id="my-text" type="text" name="my-text">
		<input id="submit-source-form" type="submit" value="Fill the following form">
	</form>
	
    <section style="margin-top: 15px;">
		<form id="target-form" method="post" action="contact.php" role="form">
			<select class="form-control" id="my-select-2" name="my-select">
				<option value="-1">HOW MUCH ?</option>
				<option value="1">1</option>
				<option value="2">2</option>
			</select>
			<input id="my-text-2" type="text" name="my-text" value="this will change">
			
			<input id="additional-value" type="text" name="additional" placeholder="this value will not change">
			<input id="submit-target-form" type="submit" value="Send form">
		</form>
    </section>

https://jsfiddle.net/cremugnt/

注意:“发送表单”操作在此处不起作用,因为“阻止表单提交到'http://stacksnippets.net/contact.php”因为表单的框架是沙箱并且未设置“允许表单”权限。“

注意:此代码段只能复制“选择”和“输入”字段,因此,如果您想使用“复选框”或“收音机”等其他字段,您就会明白这一点。

答案 2 :(得分:0)

这是一种更全局的方法,使用OODK-JS和jQuery兼容任何类型的字段(注意,字段匹配基于name属性):

          $.noConflict();

          OODK.config({
            'path': {
              'oodk': '../src',
              'workspace': 'workspace'
            }
          });

          OODK(function($, _){

            // POO approach to solve this problem
            // define a FormHelper class
            var FormHelper = $.class(function($, µ, _){

              $.protected('form');

              $.public(function __initialize(form){
                  µ.form = form;
              });

              $.public(function exportToLiteral(){

                var exprt = {};

                jQuery(µ.form).find(":input, [textarea]").each(function(){

                  var val;

                  if(this.type === 'radio'){

                    val = µ.exportRadioField(this, exprt);

                  }else if(this.type === 'checkbox'){

                    val = µ.exportCheckboxField(this, exprt);

                  }else{

                    val = µ.exportField(this, exprt);
                  }

                  if(typeof val !== "undefined" &&
                    typeof jQuery(this).attr("name") !== "undefined"){

                      exprt[jQuery(this).attr("name")] = val;
                  }
                });

                return exprt;
            });

            // export argument html field fld to object literal exprt
            $.protected(function exportField(fld, exprt){

              return jQuery(fld).val();
            });

            // export argument checkbox html field fld to object literal exprt
            $.protected(function exportCheckboxField(fld, exprt){

              var val;

              if(jQuery(fld).is(':checked')){

                if(typeof exprt[jQuery(this).attr("name")] !== "undefined"){
                  val = exprt[jQuery(this).attr("name")];
                }else{
                  val = [];
                }

                val.push(jQuery(this).val());
              };

              return val;
            });

            // export argument html radio field fld to object literal exprt
            $.protected(function exportRadioField(fld, exprt){

              var val;

              if(jQuery(fld).is(':checked')){
                val = jQuery(this).val();
              }

              return val;
            });

            // copy all values of the source form to the destination form passed 
            // as argument
            $.public(function copyToForm(destForm){

              var oSrcForm = this.exportToLiteral();

              jQuery(destForm).find(":input, [textarea]").each(function(){

                if(typeof oSrcForm[jQuery(this).attr("name")] !== "undefined"){

                  var srcVal = oSrcForm[jQuery(this).attr("name")];

                  if(this.type == 'checkbox'){

                    µ.copyToCheckboxField(this, srcVal, oSrcForm);

                  }else if(this.type == 'radio'){

                    µ.copyToRadioField(this, srcVal, oSrcForm);

                  }else{

                    µ.copyToField(this, srcVal, oSrcForm);
                  }

                }
              });
            });

            $.protected(function copyToField(fld, val, exprt){

              jQuery(fld).val(val);
            });

            $.protected(function copyToCheckboxField(fld, val, exprt){

              if(Array.isArray(srcVal) && srcVal.indexOf(jQuery(fld).val()) !== -1){

                jQuery(fld).prop('checked', true);
              }
            });

            $.protected(function copyToRadioField(fld, val, exprt){

              if(exprt[jQuery(fld).attr("name")] == jQuery(fld).val()){

                jQuery(fld).prop('checked', true);
              }
            });
          });

          jQuery(document).ready(function(){

            jQuery('#pd_applynowbt').bind('click', function(evt){

              // prevent the source form to be submitted
              evt.preventDefault();

              var formHelper = $.new(FormHelper, jQuery('#home'));

              // copy all fields from form #home to form #contact
              formHelper.copyToForm(jQuery('#contact'));
            });
          });
          });