Best way to insert an element with JavaScript

I have an HTML form consisting of several fields (each has the same fields). I want users to be able to add additional fields by clicking the (jQuery) button. I can imagine two approaches:

  • Create a dummy hidden set of fields and clone it when you click the add button.

  • Create a function that displays HTML code in a field from a string when you click the add button. (The function knows the set of fields as a long string.)

Are there any significant advantages or disadvantages that can be applied? Is there another way?

I don’t like the idea that the dangling widget is around, even if it is hidden, but encodes the entire set of fields as a string, it seems a little unthinkable, although I know that this is a fairly standard practice.

+3
source share
7 answers

Even if the existing field sets are identical to the ones you want to insert, you can clone the existing field set and clear the inputs. Now you do not need to have additional code in HTML or Javascript :)

+3
source

() , , JavaScript, "" . , .

, HTML, , - JavaScript.

, .

+3

, DOM:

function createFieldset(legendText, prefix) {
    var fieldset = document.createElement("fieldset");
    var legend = fieldset.appendChild( document.createElement("legend") );
    legend.appendChild( document.createTextNode(legendText) );

    var input = document.createElement("input");
    input.type = "text";
    input.name = prefix + "_some_text_field";

    return fieldset;
}

var fieldset = createFieldset("Test fields", "test");
document.forms[0].appendChild(fieldset);

, , DOM.

+2

node, , (, ) .

, .

+1

, , name. , .

+1

async. , , .

, . , , . , , .

# 1 - , HTML, JS.

0

jQuery, , clone().

$( 'form' ).append( $('fieldset:eq(0)').clone() );

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

0

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


All Articles