/    Sign up×
Community /Pin to ProfileBookmark

Problem filling Select dinamicaly created with JS using Ajax

Hey Guys

Using some peoples codes i manage to create a form that out add some product lines as user requested on the page, at the same time to add the values. Im just putting the related code.

The problem is that when created the select and loading it with the options and trying to select the index in the form it stops working.

If anyone has some sugestions please let me know

Thanks

Here is the used code.


_________________________________________________________________

Form.php


_________________________________________________________________
[code=php]<?php
echo ”
<form method=’post’ action=’?do=add’ onsubmit=’return validate(this);’ name=’megacompra’>

<table width=’592′ border=’0′ cellspacing=’2′ cellpadding=’3′ align=’left’>
<tr>
<td class=’form_text’ width=’118′>
<div align=’center’>
Producto</div></td>
<td class=’form_text’ width=’118′>
<div align=’center’>
Cantidad</div></td>
<td class=’form_text’ width=’118′>
<div align=’center’>
Precio</div></td>
<td class=’form_text’ width=’118′>
<div align=’center’>
IVA</div></td>
<td class=’form_text’ width=’118′>
<div align=’center’>
Total</div></td>
</tr>
<tr>
<td class=’form_text’ width=’118′>
<div align=’center’>
<select name=’producto_’ size=’1′ onChange=’javascript:addInput(0)’>
<OPTION value=’0′>–Opcion–</OPTION>
“;
DB_LlenaCombo (‘SELECT idProducto, nombre FROM Producto’,$Producto_1);
echo ”
</select></div></td>
<td class=’form_text’ width=’118′>
<div align=’center’>
<input type=’text’ name=’cantidad_’ size=’6′ value=’$Cantidad’ onFocus=’javascript:startCalc()’ onBlur=’javascript:stopCalc()’ ></div></td>
<td class=’form_text’ width=’118′>
<div align=’center’>
<input type=’text’ name=’precio_’ size=’6′ value=’$Precio’ onFocus=’javascript:startCalc()’ onBlur=’javascript:stopCalc()’></div></td>
<td class=’form_text’ width=’118′>
<div align=’center’>
<input type=’text’ name=’iva_’ size=’6′ value=’$Iva’ onFocus=’javascript:startCalc()’ onBlur=’javascript:stopCalc()’>%</div></td>
<td class=’form_text’ width=’118′>
<div align=’center’>
<input type=’text’ name=’total_’ size=’8′ value=’$Total’ ></div></td>
</tr>
</table>
<div id=’parah’></div>

<table width=’592′ border=’0′ cellspacing=’2′ cellpadding=’3′ align=’left’>
<tr>
<td colspan=’3′>
<table width=’100%’ border=’0′ cellspacing=’2′ cellpadding=’0′></td>
<tr>
<td class=’form_button’>
<div align=’center’>
</div>
</td>
<td class=’form_button’>
<div align=’center’>
<input type=’submit’ value=’Ingresar’></div>
</td>
<td>
<input type=’text’ name=’final’ size=’6′ value=’$final[1]’>
<input type=’text’ name=’productoXX’ size=’6′ value=’$final[1]’>
</td>
</tr>
</table>
</form>
“;
?>[/code]


_________________________________________________________________

Ajax.js


_________________________________________________________________
[code=php]function sack(file) {
this.xmlhttp = null;

this.resetData = function() {
this.method = “POST”;
this.queryStringSeparator = “?”;
this.argumentSeparator = “&”;
this.URLString = “”;
this.encodeURIString = true;
this.execute = false;
this.element = null;
this.elementObj = null;
this.requestFile = file;
this.vars = new Object();
this.responseStatus = new Array(2);
};

this.resetFunctions = function() {
this.onLoading = function() { };
this.onLoaded = function() { };
this.onInteractive = function() { };
this.onCompletion = function() { };
this.onError = function() { };
this.onFail = function() { };
};

this.reset = function() {
this.resetFunctions();
this.resetData();
};

this.createAJAX = function() {
try {
this.xmlhttp = new ActiveXObject(“Msxml2.XMLHTTP”);
} catch (e1) {
try {
this.xmlhttp = new ActiveXObject(“Microsoft.XMLHTTP”);
} catch (e2) {
this.xmlhttp = null;
}
}

if (! this.xmlhttp) {
if (typeof XMLHttpRequest != “undefined”) {
this.xmlhttp = new XMLHttpRequest();
} else {
this.failed = true;
}
}
};

this.setVar = function(name, value){
this.vars[name] = Array(value, false);
};

this.encVar = function(name, value, returnvars) {
if (true == returnvars) {
return Array(encodeURIComponent(name), encodeURIComponent(value));
} else {
this.vars[encodeURIComponent(name)] = Array(encodeURIComponent(value), true);
}
}

this.processURLString = function(string, encode) {
encoded = encodeURIComponent(this.argumentSeparator);
regexp = new RegExp(this.argumentSeparator + “|” + encoded);
varArray = string.split(regexp);
for (i = 0; i < varArray.length; i++){
urlVars = varArray[i].split(“=”);
if (true == encode){
this.encVar(urlVars[0], urlVars[1]);
} else {
this.setVar(urlVars[0], urlVars[1]);
}
}
}

this.createURLString = function(urlstring) {
if (this.encodeURIString && this.URLString.length) {
this.processURLString(this.URLString, true);
}

if (urlstring) {
if (this.URLString.length) {
this.URLString += this.argumentSeparator + urlstring;
} else {
this.URLString = urlstring;
}
}

// prevents caching of URLString
this.setVar(“rndval”, new Date().getTime());

urlstringtemp = new Array();
for (key in this.vars) {
if (false == this.vars[key][1] && true == this.encodeURIString) {
encoded = this.encVar(key, this.vars[key][0], true);
delete this.vars[key];
this.vars[encoded[0]] = Array(encoded[1], true);
key = encoded[0];
}

urlstringtemp[urlstringtemp.length] = key + “=” + this.vars[key][0];
}
if (urlstring){
this.URLString += this.argumentSeparator + urlstringtemp.join(this.argumentSeparator);
} else {
this.URLString += urlstringtemp.join(this.argumentSeparator);
}
}

this.runResponse = function() {
eval(this.response);
}

this.runAJAX = function(urlstring) {
if (this.failed) {
this.onFail();
} else {
this.createURLString(urlstring);
if (this.element) {
this.elementObj = document.getElementById(this.element);
}
if (this.xmlhttp) {
var self = this;
if (this.method == “GET”) {
totalurlstring = this.requestFile + this.queryStringSeparator + this.URLString;
this.xmlhttp.open(this.method, totalurlstring, true);
} else {
this.xmlhttp.open(this.method, this.requestFile, true);
try {
this.xmlhttp.setRequestHeader(“Content-Type”, “application/x-www-form-urlencoded”)
} catch (e) { }
}

this.xmlhttp.onreadystatechange = function() {
switch (self.xmlhttp.readyState) {
case 1:
self.onLoading();
break;
case 2:
self.onLoaded();
break;
case 3:
self.onInteractive();
break;
case 4:
self.response = self.xmlhttp.responseText;
self.responseXML = self.xmlhttp.responseXML;
self.responseStatus[0] = self.xmlhttp.status;
self.responseStatus[1] = self.xmlhttp.statusText;

if (self.execute) {
self.runResponse();
}

if (self.elementObj) {
elemNodeName = self.elementObj.nodeName;
elemNodeName.toLowerCase();
if (elemNodeName == “input”
|| elemNodeName == “select”
|| elemNodeName == “option”
|| elemNodeName == “textarea”) {
self.elementObj.value = self.response;
} else {
self.elementObj.innerHTML = self.response;
}
}
if (self.responseStatus[0] == “200”) {
self.onCompletion();
} else {
self.onError();
}

self.URLString = “”;
break;
}
};

this.xmlhttp.send(this.URLString);
}
}
};

this.reset();
this.createAJAX();
}
[/code]

to post a comment
JavaScript

3 Comments(s)

Copy linkTweet thisAlerts:
@Angry_Black_ManNov 12.2007 — this problem would be easier to troubleshoot perhaps with a live web page. because you have PHP code, you are referencing server side things that no one using your posted could could reproduce, specifically the database interaction.

if you can post a link to a webpage, this may be troubleshoot-able as that webpage would likely produce errors that can be tracked down.
Copy linkTweet thisAlerts:
@celhyaauthorNov 12.2007 — cheking the code also i missed some files... ill try to get a working test on the web.. The problem part of the code are this 2 functions that are giving the problems, the rest works fine, this is in JS,

function llenaCombo(id){

var afinal = eval("document.megacompra.productoXX");

// var combo = document.megacompra.producto_0;

//document.megacompra.producto_0.options.length = 0;

var obj = eval("document.megacompra.producto_"+ id);

// var countryCode = id;

// var countryCode = sel.options[sel.selectedIndex].value;

obj.options.length = 0;

//obj.options[obj.options.length] = new Option('--OpcionX--','5');

//obj.options[obj.options.length] = new Option('--OpcionXX--','6');

afinal.value = "Mando Llamar getSub";

ajax.requestFile = 'getSub.php?Producto='+id;

afinal.value = "Acabo getSub";

ajax.onCompletion = CreateProducto1(id);

afinal.value = "Termino la segunda";

obj.options[obj.selectedIndex].value = arrInputValue[id];

afinal.value = "Asigno Valor";

ajax.runAJAX();

afinal.value = "Termino Ajax";



}


function CreateProducto1(id)

{

var afinal = eval("document.megacompra.productoXX");

afinal.value = "entro a la segunda";

var obj = eval("document.megacompra.producto_"+ id);

// alert("ajax.response");

eval(ajax.response); // Executing the response from Ajax as Javascript code

afinal.value = "Ejecuto Val";

}




Here is the remaining code



_________________________________________________________________
getSub.php

_________________________________________________________________
[code=php]
if(isset($_GET['Producto'])){

$ABuscar=$_GET['Producto'];

$QueryStr = "SELECT idProducto, nombre FROM Producto";
$Query = @mysql_query($QueryStr);

echo "obj.options[obj.options.length] = new Option('--Opcion--','0');n";

while ($row = mysql_fetch_row($Query)){
echo "obj.options[obj.options.length] = new Option('$row[1]','$row[0]');n";
}

}[/code]


_________________________________________________________________
addHTMLControls.js

_________________________________________________________________

[code=php]var arrInput = new Array(0);
var arrInputValue = new Array(0);
var arrInputCantidad = new Array(0);
var arrInputPrecio = new Array(0);
var arrInputIva = new Array(0);
var arrInputTotal = new Array(0);



function addInput(Valor) {
var ValorY = Valor * 1;
if (ValorY > 0){
ValorX = ValorY - 1;
var producto = eval("document.megacompra.producto_"+ ValorX);


arrInputValue[ValorX]=producto.options[producto.selectedIndex].value;
}

// var ValorX = Valor - 1;
// arrInputValue[ValorX]=strValue;
if (arrInput.length <= 5){
if (Valor == arrInput.length){
arrInput.push(arrInput.length);
arrInputValue.push("");
arrInputCantidad.push("");
arrInputPrecio.push("");
arrInputIva.push(15);
arrInputTotal.push("");
display();
}
}
}

function display() {
document.getElementById('parah').innerHTML="";
for (intI=0;intI<arrInput.length;intI++) {
document.getElementById('parah').innerHTML+=createInput(arrInput[intI], arrInputValue[intI],arrInputCantidad[intI],arrInputPrecio[intI],arrInputIva[intI],arrInputTotal[intI]);
llenaCombo(intI);
}

}

function saveValue(intId,strValue,num) {
if (num == 1){
arrInputValue[intId]=strValue;
}
if (num == 2){
arrInputCantidad[intId]=strValue;
}
if (num == 3){
arrInputPrecio[intId]=strValue;
}
if (num == 4){
arrInputIva[intId]=strValue;
}
if (num == 5){
arrInputTotal[intId]=strValue;
}

}

function createInput(id,value1,value2,value3,value4,value5) {
// return "<input type='text' id='test"+ id +"' onChange='javascript:saveValue("+ id +",this.value,1)' value='"+ value +"'><br>";
return"<table width='592' border='0' cellspacing='2' cellpadding='3' align='left'><tr><td class='form_text' width='118'><div align='center'><select name='producto_"+ id +"' size='1' onChange='javascript:addInput("+(id + 1) +")'><OPTION value='0'>--Opcion--</OPTION><OPTION value='1'>--Numero"+ id +"--</OPTION></select></div></td><td class='form_text' width='118'><div align='center'><input type='text' name='cantidad_"+ id +"' size='6' value='"+ value2 +"' onChange='javascript:saveValue("+ id +",this.value,2)' onFocus='javascript:startCalc2("+ id +")' onBlur='javascript:stopCalc2("+ id +")'></div></td><td class='form_text' width='118'><div align='center'><input type='text' name='precio_"+ id +"' size='6' value='"+ value3 +"' onChange='javascript:saveValue("+ id +",this.value,3)' onFocus='javascript:startCalc2("+ id +")' onBlur='javascript:stopCalc2("+ id +")'></div></td><td class='form_text' width='118'><div align='center'><input type='text' name='iva_"+ id +"' size='6' value='"+ value4 +"' onChange='javascript:saveValue("+ id +",this.value,4)' onFocus='javascript:startCalc2("+ id +")' onBlur='javascript:stopCalc2("+ id +")'>%</div></td><td class='form_text' width='118'><div align='center'><input type='text' name='total_"+ id +"' size='8' value='"+ value5 +"' onChange='javascript:saveValue("+ id +",this.value,5)'></div></td></tr></table><br>";

}

function llenaCombo(id){
var afinal = eval("document.megacompra.productoXX");
// var combo = document.megacompra.producto_0;
//document.megacompra.producto_0.options.length = 0;
var obj = eval("document.megacompra.producto_"+ id);
// var countryCode = id;
// var countryCode = sel.options[sel.selectedIndex].value;
obj.options.length = 0;
obj.options[obj.options.length] = new Option('--OpcionX--','5');
obj.options[obj.options.length] = new Option('--OpcionXX--','6');
afinal.value = "Mando Llamar getSub";
ajax.requestFile = 'getSub.php?Producto='+id;
afinal.value = "Acabo getSub";
ajax.onCompletion = CreateProducto1(id);
afinal.value = "Termino la segunda";
afinal.value = "Asigno Valor";
ajax.runAJAX();
afinal.value = "Termino Ajax";



}


function CreateProducto1(id)
{
var afinal = eval("document.megacompra.productoXX");
afinal.value = "entro a la segunda";
var obj = eval("document.megacompra.producto_"+ id);
// alert("ajax.response");
eval(ajax.response); // Executing the response from Ajax as Javascript code
afinal.value = "Ejecuto Val";
}



function deleteInput() {
if (arrInput.length > 0) {
arrInput.pop();
arrInputValue.pop();
}
display();
}

function startCalc(){
interval = setInterval("calc()",1);
}
function calc(){
cantidad = document.megacompra.cantidad_.value;
precio = document.megacompra.precio_.value;
iva = document.megacompra.iva_.value;

document.megacompra.total_.value = (cantidad*precio)+(cantidad*((iva/100)*precio));
sumaTotal();
}
function stopCalc(){
clearInterval(interval);
}



function startCalc2(val){
interval = setInterval("calc2("+val+")",1);
}
function calc2(val){
var cantidad2 = eval("document.megacompra.cantidad_"+ val);
var cantidad3 = cantidad2.value;
var precio2 = eval("document.megacompra.precio_"+ val);
var precio3 = precio2.value;
var iva2 = eval("document.megacompra.iva_"+ val);
var iva3 = iva2.value;
var total2 = eval("document.megacompra.total_"+ val);


total2.value = (cantidad3*precio3)+(cantidad3*((iva3/100)*precio3));
arrInputTotal[val]=(cantidad3*precio3)+(cantidad3*((iva3/100)*precio3));

sumaTotal();
}

function sumaTotal(){

var suma;

suma = document.megacompra.total_.value * 1;

for (intI=0;intI<arrInput.length;intI++) {

asumar = eval("document.megacompra.total_"+ intI);
nuevo = asumar.value * 1;
suma = suma + nuevo;

}

var afinal = eval("document.megacompra.final");
afinal.value = suma;


}

function stopCalc2(){
clearInterval(interval);
}
[/code]


_________________________________________________________________
getSub.php

_________________________________________________________________
[code=php]
if(isset($_GET['Producto'])){

$ABuscar=$_GET['Producto'];

$QueryStr = "SELECT idProducto, nombre FROM Producto";
$Query = @mysql_query($QueryStr);

echo "obj.options[obj.options.length] = new Option('--Opcion--','0');n";

while ($row = mysql_fetch_row($Query)){
echo "obj.options[obj.options.length] = new Option('$row[1]','$row[0]');n";
}

}[/code]
Copy linkTweet thisAlerts:
@Angry_Black_ManNov 12.2007 — theres too much stuff happening on your server for your code to help me troubleshoot this. ill need a web link.
×

Success!

Help @celhya spread the word by sharing this article on Twitter...

Tweet This
Sign in
Forgot password?
Sign in with TwitchSign in with GithubCreate Account
about: ({
version: 0.1.9 BETA 5.18,
whats_new: community page,
up_next: more Davinci•003 tasks,
coming_soon: events calendar,
social: @webDeveloperHQ
});

legal: ({
terms: of use,
privacy: policy
});
changelog: (
version: 0.1.9,
notes: added community page

version: 0.1.8,
notes: added Davinci•003

version: 0.1.7,
notes: upvote answers to bounties

version: 0.1.6,
notes: article editor refresh
)...
recent_tips: (
tipper: @AriseFacilitySolutions09,
tipped: article
amount: 1000 SATS,

tipper: @Yussuf4331,
tipped: article
amount: 1000 SATS,

tipper: @darkwebsites540,
tipped: article
amount: 10 SATS,
)...