Вопрос

Я создаю поля формы динамически.


Если я использую

<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>

Частично это сработает.Теперь мне нужно динамически получить идентификатор/имя formField.Как мне это сделать?

Это было полезно?

Решение

Попробуйте это?

$("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);
        }
        });
    });
});

Другие советы

Ваш вопрос в лучшем случае расплывчатый.Но соответствует ли это тому, что вы хотите?:

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

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



Обновлять:

Вы можете сопоставить элементы по значениям:

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

Будет соответствовать:

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

Но нет:

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

См. документация по выбору.

УВЕДОМЛЕНИЕ: эти селекторы работают медленно, и я бы использовал их только в крайнем случае.Чтобы повысить производительность, вы можете выполнять запросы к подмножеству узлов DOM:

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

это тоже работает:

<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>
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top