开发者

Javascript how to make an form based on another form

开发者 https://www.devze.com 2023-02-26 11:03 出处:网络
I am trying to make an form that is based on the myform checked checkboxes. The myform2 should have all the checked checkboxes of myform2 with the same input fields.

I am trying to make an form that is based on the myform checked checkboxes.

The myform2 should have all the checked checkboxes of myform2 with the same input fields.

How should I do this?

<h1>Heading 1</h1>
<form name="myform" method="POST" action="/cgi-bin/script.cgi">
<input name="box1" type="checkbox" value="Bike" />
<input name="box2" type="checkbox" value="Car" />
</form> 
<h2>Heading 2</h2>
<form name="myform2" method="POST" action="/cgi-bin/script.cgi">
<script type="text/javascript">
var i=5;
var b=0;
while (b<=i) {
    document.write('<br />' + '<input type="checkbox"' + 'value="Bike"' + '/>' + '<label for="male">'+ "Male" + '</label>' )
}
</script>
</form>
开发者_运维知识库


You can do something along these lines with jquery:

$('form:eq(0) input').clone().appendTo('form:eq(1)');

It should clone all the input dom elements under the first form element on the page and put them into the second form element on the page. Haven't tested this, but hopefully will do what you're looking for.

If you only wanted to copy the checked input elements, you can try something like this:

$('form:eq(0) input:checked').clone().appendTo('form:eq(1)');

However if you have checked radio buttons it will clone those too, if you want to prevent that you have to get fancier still, which will be something along the lines of:

$('form:eq(0) input:checkbox').filter(':checked').clone().appendTo('form:eq(1)');

This should copy across only the input elements that are of type checkbox and that are checked.


The way to go (in my view) is what you see in skorks' answer. But if you have no choice other than doing it without a library, here is the js to do it.

<h1>Heading 1</h1>
<form name="myform" method="POST" action="/cgi-bin/script.cgi">
<input name="box1" type="checkbox" value="Bike" checked />
<input name="box2" type="checkbox" value="Car" />
</form> 

<h2>Heading 2</h2>
<form name="myform2" method="POST" action="/cgi-bin/script.cgi">

<script type="text/javascript">

var my_form = document.forms[0];
var num_inp = my_form.elements.length;
var me, i;
for (i=0; i<num_inp; i++) {
    me = my_form.elements[i];
    if(me.type === "checkbox" && me.checked)
    document.write('<input type="checkbox" value="' + me.value + '" name="' + me.name + '" checked /> ' + me.value + '<br/>');
}

</script>
</form>

By the way, it is not clear where you get the data for the labels of the generated checkboxes, the best choice was the value of the checkbox and I used that.

0

精彩评论

暂无评论...
验证码 换一张
取 消