1

I'm creating multiple form retrieving data from jquery. after that i want to work with individual form without sending the form but, i'm having problems retrieving the value of the inputs. they are all undefined in the alert tag. paste my code. thanks for all

<script>
$("#select_idioma").bind('click',function(){
    cargatraducciones($("#select_idioma").val());
});
function cargatraducciones(idi){
    $('#listadopalabras').hide("fast");
    $('#cargando').fadeIn(1000);
        $.ajax({
            type: "POST",
            url: "../includes/ajax.php",
            dataType : "json",
            data: "opc=traducciones&idi="+idi,
            success: function(datos){
                crealistado(datos,idi);
            }
        });
    }

function crealistado(datos,idi){
    var html ="";
    if(datos.length ==0){
        html +="<div id='errors'>No hay datos disponibles para mostrar</div>";
    }else{
        html +="<h2>Listado de palabras a traducir</h2>";
        html += "<div class='nota'>Las palabras pendientes para traducir, aparecen con el texto traducir. Escriba la traducción y pulse en guardar.</div>";
        for(i=0; i < datos.length; i++){
            html += "<form style='background:";
            if(datos[i].valor == "traducir"){
                html += "red;";
            }else{
                html += "#f2f2f2;";
            }
            html+= "border-radius:5px; margin-top:5px;margin-bottom:5px; padding:5px 10px' action ='' method=''>";
            html += "<a href='eliminar.php?tipo=traduccion&id="+datos[i].id+"' onclick=\"return confirm('¿Desea elminiar la palabra "+datos[i].nombre+"?')\"><img src='../imatges/iconos/delete_24.png'/></a>";

            html += "<input style='display:none' type='text' name='idt' value='"+datos[i].id+"'/>";

            html += "<div style='width:700px'>"+datos[i].nombre+"</div>";
            html += "<input style='width:700px' type='text' name='valor"+i+"' id='valor"+i+"' value='"+datos[i].valor+"'/>";

            html += "<input style='margin-left:10px' type='button' class='button"+i+"' value='Modificar' />";
            html += "</form>";
            html += "<hr style='margin:0; margin-bottom:2px' />";
        }
    }
    $('#cargando').hide("fast");
    $('#listadopalabras').html(html);
    $("#listadopalabras").fadeIn(1000);
    var total = datos.length;
    procesa(total);
}
function procesa(total){
    for ( i=0; i<total; i++){
      $(".button"+i).click(function() {  
        alert($("input#valor"+i).val());  
        // validate and process form here  
        var valor = $("input#valor"+i).val();  
        if (valor == "") {  
            alert("debe escribir un texto para la traducción");
            $("input#valor"+i).focus();  
            return false;  
        }
        alert("clicado");
      });  
    }
}

</script>
3
  • 3
    You will probably get an answer, but the fastest way to get an answer is to post a working example on jsFiddle and then post the link here. Commented Feb 2, 2012 at 16:14
  • @gdoron - Looks like the HTML is generated dynamically in crealistado function. Commented Feb 2, 2012 at 16:18
  • @ShankarSangoli. I think the problem is with $("#select_idioma").val() like I answered. Commented Feb 2, 2012 at 16:21

4 Answers 4

1

It is not working because the value of i inside the button click handler will be equal to total i.e. the last incremented value of the for loop. So $("input#valor"+i) will return an empty object. Calling val() on empty jQuery object will return you undefined.

Try this.

function procesa(total){
    for ( i=0; i<total; i++){
      $(".button"+i).data('itemid', i).click(function() {  
        var $valor = $("#valor" + $(this).data('itemid'))
        alert($valor.val());  

        // validate and process form here  
        var valor = $valor.val();  
        if (valor == "") {  
            alert("debe escribir un texto para la traducción");
            $valor.focus();  
            return false;  
        }
        alert("clicado");
      });  
    }
}
Sign up to request clarification or add additional context in comments.

6 Comments

Is it a problem like an access to modified clouser in C#? this
This is the common problem of closures and loop.
thanks all. i'm going to try solve this but, Shankarsangli the class .button is increased every iteration.
@MiquelGabriel - I know it is incremented and my answer has taken care of that.
i dont understand the code you post, but it works!!! thanks a lot. can you explain it?
|
0

wrap up these lines with dom ready function,

$(function(){
   $("#select_idioma").bind('click',function(){
      cargatraducciones($("#select_idioma").val());
   });
});

Comments

0

Move this code to DOM ready:

$(document).ready(function (){
    $("#select_idioma").bind('click',function(){
        cargatraducciones($("#select_idioma").val());
    });
});

Or to :

$(function() {
     $("#select_idioma").bind('click',function(){
        cargatraducciones($("#select_idioma").val());
    });        
});

This line $("#select_idioma").val() is problematic before the DOM is ready because #select_idioma element is undifend before the DOM is ready.

Comments

0

Thanks ShankarSangoli. it works fine :) there are all code.

<?php include_once("../includes/inicialize.php"); 
if(isset($_POST['submit'])){
    if(!$nombre){
        missatge("ko","Ha de introducir un nombre para el nuevo idioma");
    }else{
        $sql="insert into idiomas (nombre) values ('{$nombre}')";
        if($resultado = $database->query($sql)){
            missatge("ok","El idioma se ha insertado correctamente");
        }else{
            missatge("ko","El idioma no ha podido ser insertado");  
        }
    }
}else{
    $nombre="";
}
?>

<?php include_once("../layouts/cabecera_admin.php"); ?>
<div id="pagina">
    <?php echo missatge(); ?>
    <div id="home_news">
        <form name="home_news" method="post" accept="<?php $_SERVER['PHP_SELF']; ?>">
            <h2>Insertar nuevo Idioma</h2>
            <label>Nombre:</label>
                <input type="text" name="nombre" value="<?php echo $nombre; ?>"/>
                <input type="submit" name="submit" value="Crear nuevo idioma"/>
        </form>
        <h2>Idiomas dados de alta</h2>
        <?php
        $sql="select * from idiomas";
        $resultado = $database->query($sql);
        while($lenguaje = $database->fetch_array($resultado)){
                //echo "<a href='eliminar.php?tipo=idioma&id={$lenguaje['id']}'  onclick=\"return confirm('¿Desea elminiar el idioma {$lenguaje['nombre']}?')\"><img src='../imatges/iconos/delete_24.png'/></a>";
                echo "<a href='edit_idioma.php?id={$lenguaje['id']}' title='Editar idioma' toptions='type = iframe, effect = fade, width = 400, height = 230, overlayClose = 1, shaded=1, onclose=vesapagina(\"idiomas.php\")'>";
                echo $lenguaje['nombre'];
                echo "</a>";
                echo "<hr style='margin:5px 0 5px 0;' />";
        }
        ?>
    </div><!-- fin home_news -->
    <div class="clear"></div>
    <div id="traducciones">
        <div id="home_news">
            <form>
                <h2>Traducciones</h2>
                <div class="nota">Para visualizar el listado de palabras a traducir, seleccione el idioma que desee de los disponibles a continuación:</div>
                <label>Idioma:</label>
                <select id="select_idioma" name="id_idioma">
                <option value="-1">Seleccione el idioma</option>
                <?php
                    $lang = get("idiomas");
                    while($lengua = $database->fetch_array($lang)){
                        echo "<option value='{$lengua['id']}'>{$lengua['nombre']}</option>";
                    }
                ?>
            </select>
            </form>
        </div><!-- fin div home news -->
        <div class="clear"></div>
            <div id="cargando" style="display:none"><img src="../imatges/ajax-loader.gif"/> Cargando el contenido ...</div>
            <div id="listadopalabras">

            </div><!-- fin lista palabras -->


    </div>
</div><!-- fin div pagina -->
<div class="clear"></div>
<?php include_once("../layouts/pie_admin.php"); ?>
<script>
$("#select_idioma").bind('click',function(){
    cargatraducciones($("#select_idioma").val());
});
function cargatraducciones(idi){
    $('#listadopalabras').hide("fast");
    $('#cargando').fadeIn(1000);
        $.ajax({
            type: "POST",
            url: "../includes/ajax.php",
            dataType : "json",
            data: "opc=traducciones&idi="+idi,
            success: function(datos){
                crealistado(datos,idi);
            }
        });
    }

function crealistado(datos,idi){
    var html ="";
    if(datos.length ==0){
        html +="<div id='errors'>No hay datos disponibles para mostrar</div>";
    }else{
        html +="<h2>Listado de palabras a traducir</h2>";
        html += "<div class='nota'>Las palabras pendientes para traducir, aparecen con el texto traducir. Escriba la traducción y pulse en guardar.</div>";
        for(i=0; i < datos.length; i++){
            html += "<form style='background:";
            if(datos[i].valor == "traducir"){
                html += "red;";
            }else{
                html += "#f2f2f2;";
            }
            html+= "border-radius:5px; margin-top:5px;margin-bottom:5px; padding:5px 10px' action ='' method='' id='form"+i+"'>";
            html += "<a href='eliminar.php?tipo=traduccion&id="+datos[i].id+"' onclick=\"return confirm('¿Desea elminiar la palabra "+datos[i].nombre+"?')\"><img src='../imatges/iconos/delete_24.png'/></a>";

            html += "<input style='display:none' type='text' name='idt"+i+"' id='idt"+i+"' value='"+datos[i].id+"'/>";

            html += "<div style='width:700px'>"+datos[i].nombre+"</div>";
            html += "<input style='width:700px' type='text' name='valor"+i+"' id='valor"+i+"' value='"+datos[i].valor+"'/>";

            html += "<input style='margin-left:10px' type='button' class='button"+i+"' value='Modificar' />";
            html += "</form>";
            html += "<hr style='margin:0; margin-bottom:2px' />";
        }
    }
    $('#cargando').hide("fast");
    $('#listadopalabras').html(html);
    $("#listadopalabras").fadeIn(1000);
    var total = datos.length;
    procesa(total);
}
function procesa(total){
    for ( i=0; i<total; i++){
      $(".button"+i).data('itemid', i).click(function() {  
        var $valor = $("#valor" + $(this).data('itemid'))
        var $idt = $("#idt" + $(this).data('itemid'))
        var $form = $("#form" + $(this).data('itemid'))
//       alert($idt.val());

        // validate and process form here  
        var valor = $valor.val();
        var idt = $idt.val();
        if (valor == "") {  
            alert("debe escribir un texto para la traducción");
            $valor.focus();  
            return false;  
        }
            //alert("clicado");

            var dataString = 'valor='+ valor + '&idt=' + idt;  
            //alert (dataString);return false;  
            $.ajax({  
              type: "POST",  
              url: "../includes/procesatraduccion.php",  
              data: dataString,  
              success: function() {
//              alert("proceso completo"+idt);
                $form.animate({backgroundColor:"green"},1000);  
              }  
            });
        return false;  
      });  
    }
}

</script>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.