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>
Matt Ball
  • 354,903
  • 100
  • 647
  • 710

4 Answers4

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");
      });  
    }
}
ShankarSangoli
  • 69,612
  • 13
  • 93
  • 124
0

wrap up these lines with dom ready function,

$(function(){
   $("#select_idioma").bind('click',function(){
      cargatraducciones($("#select_idioma").val());
   });
});
Muthu Kumaran
  • 17,682
  • 5
  • 47
  • 70
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.

gdoron
  • 147,333
  • 58
  • 291
  • 367
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>