Pregunta

Estoy creando campos de formulario dinámicamente.


Si uso

<script>
$().ready(function() {

    $("input[name=salesPrice1]").blur(function() {

        var nameID = $("input[name=salesPrice1]").val();

        alert(nameID);

        //var newName = $("input#newName").val();

        $.ajax({
            type: "POST",
            url: "cashPrice.cfm",
            data: "salePrice=" + $("input[name=salesPrice1]").val(),
            cache: false,
            success: function(data) {
                $("#cashPrice1").html(data);
            }
        });
    });
});
</script>

Funcionará parcialmente. Ahora, tengo que obtener el ID / Nombre del formField dinámicamente. ¿Cómo hago esto?

¿Fue útil?

Solución

¿Prueba esto?

$("input[name^=salesPrice]").each(function(){
    var input = $(this); 
    var name = input.attr('name');
    var num = /\d+$/.exec(name)[0];

    $(this).blur(function() {

        var nameID = input.val();

        alert(nameID);

        //var newName = $("input#newName").val();

        $.ajax({
        type: "POST",
        url: "cashPrice.cfm",
        data: "salePrice=" + nameID,
        cache: false,
        success: function(data) {
            $("#cashPrice"+num).html(data);
        }
        });
    });
});

Otros consejos

Tu pregunta es vaga en el mejor de los casos. Pero, ¿es algo así como lo que quieres ?:

$("input").blur(function ()
{
    var that = $(this);

    var id = that.attr("id");
    var name = that.attr("name");
});



Update:

Puede hacer coincidir elementos en valores:

$("input[id^='hello']")

Coincidirá:

<input type="text" id="helloworld" />
<input type="text" id="helloearth" />

Pero no:

<input type="text" id="hiworld" />

Consulte la documentación del selector .

AVISO: estos selectores son lentos y solo los usaría como último recurso. Para acelerar el rendimiento, puede hacer consultas en un subconjunto de nodos DOM:

$("complex selector goes here", $("container node in which to query"))

esto también funciona:

<html>
<script type="text/javascript">
    $().ready(function() {
        alert('loaded');
        $('.salesPriceInput').blur(function ()
        {    
            alert($(this).attr("id"));
            var myID = $(this).attr("id").substr(10,1); 
            alert(myID);
            $.ajax({
                type: "get",
                url: "cashPrice.cfm",
                data: "salePrice=" + $('#salesPrice'+myID).val(),
                cache: false,
                success: function(data){
                   $('#cashPrice'+myID).html(data);
                }
            })
         }); 
    });
</script>


<form>
    <cfoutput>
        <cfloop from="1" to="3" index="i">
            <input type="text" name="salesPrice#i#" id="salesPrice#i#" class="salesPriceInput" value="" />
            <div id="cashPrice#i#"></div>
            <hr />
        </cfloop>
    </cfoutput>
</form>
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top