JavaScript - Crear elementos dinámicos

 
Vista:

Crear elementos dinámicos

Publicado por Susa (4 intervenciones) el 20/07/2009 13:07:24
Hola amigos!!!!
A ver si alguien puede echarme una mano:
Tengo que construir una lista estática y conseguir después copiar elementos de esa lista (vamos crear elementos de forma dinámica), el problema es que lo estoy intentando pero...se muy poco de JavaScript y no soy capaz.

Si me pudiérais decir un poco como va el código o explicarme por encima o lo agradecería un montón.

Saludos
Valora esta pregunta
Me gusta: Está pregunta es útil y esta claraNo me gusta: Está pregunta no esta clara o no es útil
0
Responder

RE:Crear elementos dinámicos

Publicado por m (1 intervención) el 22/07/2009 03:35:37
Hola,

aqui tienes un ejemplo:

http://javascripts.astalaweb.com/Formularios%20V/1_Formularios%20V.asp


saludos
Valora esta respuesta
Me gusta: Está respuesta es útil y esta claraNo me gusta: Está respuesta no esta clara o no es útil
0
Comentar

RE:Crear elementos dinámicos

Publicado por Susa (4 intervenciones) el 22/07/2009 10:01:33
hola de nuevo!!!
Muchas gracias por el enlace...lo he estado mirando y me ha servido para entenderlo un poco mejor, aunque no es exáctamente lo que necesito.
Mira, te cuento, tengo 2 listas, una estática (o si quieres un formulario) y otra dinámica, y lo que necesito es que seleccionando una opción de la lista estática, se me haga una copia (de la opción seleccionada) en la lista dinámica. El caso es que lo estoy intentando con herencia, document.createElement(); pero no hay manera. Y he llegado a pensar que puede que tenga que poner algo tras la función para que se muestre el objeto creado...pero..nose. Te mando la función que se encarga de crear la copia para que veas:

function crear() {
// Creamos un nuevo elemento LI
var li = document.createElement(“LI”);
// Añadimos el valor introducido al nuevo elemento
li.innerHTML ="Copiar";
// Añadimos el elemento LI a la lista UL
var ul = document.getElementById(“UL”);
ul.appendChild(li);
// Vaciamos la caja de texto
document.getElementById(“texto”).value = “”;
}

Ahhhh!!! y las listas están definidas así:

<div class="Listas">
<ul>
<!-- Creación de la botonera para las operaciones -->
<li class="Lista1"><div>Copiar ficheros</div></li>
<li class="Lista1"><div>Borrar ficheros</div></li>
<li class="Lista1"><div>Ejecutar programa</div></li>
<li class="Lista1"><div>Ejecutar Ant</div></li>
<li class="Lista1"><div>Ejecutar SQL</div></li>
<li class="Lista1"><div>Mostrar mensaje</div></li>

</ul>
</div>

<div class="Listas">
<ul id="ul2" class="draglp">
<li class="Lista2" id="li2_1">Dibujos</li>
</ul>
</div>

Un saludo y gracias de antemano.
Valora esta respuesta
Me gusta: Está respuesta es útil y esta claraNo me gusta: Está respuesta no esta clara o no es útil
0
Comentar
Imágen de perfil de Bet7o
Val: 4
Ha disminuido su posición en 44 puestos en JavaScript (en relación al último mes)
Gráfica de JavaScript

RE:Crear elementos dinámicos

Publicado por Bet7o (63 intervenciones) el 22/07/2009 19:28:24
Hola,

Podrias poner todo el codigo k tienes para darnos una mejor idea y es no parece dificil lo k intentas hacer.

Saludos!
Valora esta respuesta
Me gusta: Está respuesta es útil y esta claraNo me gusta: Está respuesta no esta clara o no es útil
0
Comentar

RE:Crear elementos dinámicos

Publicado por Susa (4 intervenciones) el 23/07/2009 08:26:37
Hola!!!!
Bueno, ante todo daros las gracias por responder. Creo que ya conseguí lo que os comentaba ayer, aunque estoy casi segura que dentro de poco volvereis a tener noticias mias, jeje!!!!
Cuelgo el código por si alguien lo quiere. Ahhhh!!!!si veis cosas extrañas (YAHOO.util....) es porque estoy trabajando con YUI Library (de Yahoo).

Un saludo!!!!

<html>
<head>
<title>Selección y adición de elementos a una lista</title>
<p align="center"><b>Selección y adición de elementos a una lista</b></p>

<style type="text/css">
body {
margin:10px;
padding:0;
}
</style>

<link rel="stylesheet" type="text/css" href="http://yui.yahooapis.com/2.7.0/build/fonts/fonts-min.css" />
<script type="text/javascript" src="http://yui.yahooapis.com/2.7.0/build/yahoo-dom-event/yahoo-dom-event.js"></script>
<script type="text/javascript" src="http://yui.yahooapis.com/2.7.0/build/animation/animation-min.js"></script>
<script type="text/javascript" src="http://yui.yahooapis.com/2.7.0/build/dragdrop/dragdrop-min.js"></script>

<style>
div.Workarea { border:1px solid #7EA6B2; width:700px; height:800px; margin:10px;}
div.Listas{padding:10px; float:left; border:1px solid #7EA6B2;margin:10px;}

<!-- Formulario-->
ul.Dragform {
position: relative;
list-style: none;
margin:10px;
}

ul.draglp {
position: relative;
width: 200px;
height:240px;
border: 1px solid gray;
background: #f7f7f7;
list-style: none;
margin:0;
padding:0;
}

ul.draglp li {
margin: 1px;
cursor: move;
zoom: 1;
}

ul.draglp_alt {
position: relative;
list-style: none;
margin:0;
padding:0;
padding-bottom:10px;
}
uldraglp_alt li {
margin: 1px;
cursor: move;
}


li.Lista1 {
width: 50px;
height: 20px;
background-color: #D1E6EC;
border:1px solid #7EA6B2;


}

#user_actions { float: right; }

form.select{
background-color:#D1E6EC;
margin:0;
padding:0;
}
</style>

</head>

<body style="font-family: Verdana">
<div class="Workarea">
<ul id="ul" class="Dragform">
<!-- Creación del formulario-->
<div class="db">
<form method="POST" action="assets/post.php">
<label for="nombre">Nombre:</label><input type="textbox" name="nombre" />

<label for="ejecucion">Ejecución:</label>
<select name="ejecucion[]">
<option value="Secuencial">Secuencial</option>
<option value="Paralela">Paralela</option>
</select>

<label for="retardo">Retardo:</label><input type="textbox" name="retardo" />

<div class="clear"></div>
</form>
</div>
</ul>
<div class="Listas">
<form name="selectform">
<select multiple name="form">
<option value="Copiar ficheros">Copiar ficheros</option>
<option value='Borrar ficheros'>Borrar ficheros</option>
<option value='Ejecutar programa'>Ejecutar programa</option>
<option value='Ejecutar Ant'>Ejecutar Ant</option>
<option value='Ejecutar SQL'>Ejecutar SQL</option>
<option value='Mostrar mensaje'>Mostrar mensaje</option>
</select>
<input type=button value="Añadir a la lista" onClick="passText(this.form.form.options[this.form.form.selectedIndex].value);">
</form>
</div>

<div class="Listas">
<ul id="ul1" class="draglp">
<li class="Lista1" id="li1_1">Dibujos</li>
</ul>
</div>
</div>

<script type="text/javascript">
i=1, j=4;
oldvalue = "";
function passText(passedvalue) {
var Dom = YAHOO.util.Dom;
var Event = YAHOO.util.Event;
var DDM = YAHOO.util.DragDropMgr;

if (passedvalue != "") {
var totalvalue = passedvalue+" "+oldvalue;
var li = document.createElement('li');
li.innerHTML = totalvalue;
li.id="id"+i+"_"+j;
var ul = document.getElementById('ul1');
ul.appendChild(li);
// oldvalue=li.innerHTML;

Dom.setStyle(li.id, "width", "50px");
Dom.setStyle(li.id, "height", "30px");
Dom.setStyle(li.id, "backgroundColor", "#D1E6EC");
Dom.setStyle(li.id, "border", "1px solid #7EA6B2");
new YAHOO.util.DDTarget("ul1");
new YAHOO.example.DDList(li.id);
j++;
}
}


//Funciones para el Drag&Drop
(function() {

var Dom = YAHOO.util.Dom;
var Event = YAHOO.util.Event;
var DDM = YAHOO.util.DragDropMgr;

//////////////////////////////////////////////////////////////////////////////
// example app
//////////////////////////////////////////////////////////////////////////////
YAHOO.example.DDApp = {
init: function() {

var rows=3,cols=1,i,j;
for (i=1;i<cols+1;i=i+1) {
new YAHOO.util.DDTarget("ul"+i);
}

for (i=1;i<cols+1;i=i+1) {
for (j=2;j<rows+1;j=j+1) {
new YAHOO.example.DDList("li" + i + "_" + j);
}
}

Event.on("switchButton", "click", this.switchStyles);
},

switchStyles: function() {
Dom.get("ul1").className = "draglist_alt";

}
};

//////////////////////////////////////////////////////////////////////////////
// custom drag and drop implementation
//////////////////////////////////////////////////////////////////////////////

YAHOO.example.DDList = function(id, sGroup, config) {

YAHOO.example.DDList.superclass.constructor.call(this, id, sGroup, config);

this.logger = this.logger || YAHOO;
var el = this.getDragEl();
Dom.setStyle(el, "opacity", 0.67); // The proxy is slightly transparent

this.goingUp = false;
this.lastY = 0;
};

YAHOO.extend(YAHOO.example.DDList, YAHOO.util.DDProxy, {

startDrag: function(x, y) {
this.logger.log(this.id + " startDrag");

// make the proxy look like the source element
var dragEl = this.getDragEl();
var clickEl = this.getEl();
Dom.setStyle(clickEl, "visibility", "hidden");

dragEl.innerHTML = clickEl.innerHTML;

Dom.setStyle(dragEl, "color", Dom.getStyle(clickEl, "color"));
Dom.setStyle(dragEl, "backgroundColor", Dom.getStyle(clickEl, "backgroundColor"));
Dom.setStyle(dragEl, "border", "2px solid gray");
},

endDrag: function(e) {

var srcEl = this.getEl();
var proxy = this.getDragEl();

// Show the proxy element and animate it to the src element's location
Dom.setStyle(proxy, "visibility", "");
var a = new YAHOO.util.Motion(
proxy, {
points: {
to: Dom.getXY(srcEl)
}
},
0.2,
YAHOO.util.Easing.easyOut
)
var proxyid = proxy.id;
var thisid = this.id;

// Hide the proxy and show the source element when finished with the animation
a.onComplete.subscribe(function() {
Dom.setStyle(proxyid, "visibility", "hidden");
Dom.setStyle(thisid, "visibility", "");
});
a.animate();
},

onDragDrop: function(e, id) {

// If there is one drop interaction, the li was dropped either on the list,
// or it was dropped on the current location of the source element.
if (DDM.interactionInfo.drop.length === 1) {

// The position of the cursor at the time of the drop (YAHOO.util.Point)
var pt = DDM.interactionInfo.point;

// The region occupied by the source element at the time of the drop
var region = DDM.interactionInfo.sourceRegion;

// Check to see if we are over the source element's location. We will
// append to the bottom of the list once we are sure it was a drop in
// the negative space (the area of the list without any list items)
if (!region.intersect(pt)) {
var destEl = Dom.get(id);
var destDD = DDM.getDDById(id);
destEl.appendChild(this.getEl());
destDD.isEmpty = false;
DDM.refreshCache();
}

}
},

onDrag: function(e) {

// Keep track of the direction of the drag for use during onDragOver
var y = Event.getPageY(e);

if (y < this.lastY) {
this.goingUp = true;
} else if (y > this.lastY) {
this.goingUp = false;
}

this.lastY = y;
},

onDragOver: function(e, id) {

var srcEl = this.getEl();
var destEl = Dom.get(id);

// We are only concerned with list items, we ignore the dragover
// notifications for the list.
if (destEl.nodeName.toLowerCase() == "li") {
var orig_p = srcEl.parentNode;
var p = destEl.parentNode;

if (this.goingUp) {
p.insertBefore(srcEl, destEl); // insert above
} else {
p.insertBefore(srcEl, destEl.nextSibling); // insert below
}

DDM.refreshCache();
}
}
});

Event.onDOMReady(YAHOO.example.DDApp.init, YAHOO.example.DDApp, true);

})();
</script>
</body>
</html>
Valora esta respuesta
Me gusta: Está respuesta es útil y esta claraNo me gusta: Está respuesta no esta clara o no es útil
0
Comentar

RE:Crear elementos dinámicos

Publicado por ???? (1 intervención) el 02/02/2010 21:13:52
quiero saber como passar informacion de una caja de texto a otra haciendo un click a un boton "button" en un formulario utilizando javascript. El ejercicio se llama DOM events.

Gracias!!!
Valora esta respuesta
Me gusta: Está respuesta es útil y esta claraNo me gusta: Está respuesta no esta clara o no es útil
0
Comentar