Create buttons with jQuery and Javascript

2

If we want to create a button in HTML , we need a code similar to:

<input type="submit" value="Numero parrafos" id="num_parrafos" name="Numero Parrafos"/>

How would the code be moved to jQuery or Javascript? To avoid the need to modify the HTML code. Simply create it from an external .js file that will be called in the head of the HTML between the <script>...</script>

tags

Javascript code: Is the creation correct?

var boton = document.createElement("button");
boton.type = "button";
document.body.appendChild(boton);

What if we have the button inside a global tag <form> when a form should be: " document.body.form.appendChild(boton) " or should we always refer to the body with " document.body.appendChild(boton) "?

    
asked by omaza1990 03.06.2017 в 16:19
source

2 answers

2

It's very easy to see, what you do is save your button in a variable like this:

var button = '<input type="submit" value="Numero parrafos" id="num_parrafos" name="Numero Parrafos"/>';

Then what you do is that with Jquery you insert the button at the end of the form with the function append() like this:

$('form').append(button);

In the end your code will be like this:

var button = '<input type="submit" value="Numero parrafos" id="num_parrafos" name="Numero Parrafos"/>';
$('form').append(button);

You can also put some class or ID to your form to reference it in the following way:

$('#formID').append(button); or $('.formClass').append(button);

I leave the documentation here:

Append Jquery: Documentation

Greetings

    
answered by 03.06.2017 / 18:34
source
1
function crearElemento(elemento, identificador, clase, texto, ruta, valor) {
    item = document.createElement(elemento);
    if (identificador !=='__'){ item.id = identificador; }
    if (clase !=='__') { item.className = clase; }
    if (texto !=='__') { item.innerText = texto; }
    if (ruta !== '__') { item.dataset.cargarVista = ruta; }
    if (valor !== '__') { item.value = valor; }
    return item;
}
btn = crearElemento('button','num_parrafos','agrega tus clases','Numero parrafos','__','__');
body = document.body;
body.appendChild(btn);

I think this piece of code could help you. You can add more attributes to the function if you like.

    
answered by 03.06.2017 в 21:53