无法从动态创建的隐藏输入字段中获取值

时间:2022-12-07 22:08:06

I got an element, dynamically added on the page after an ajax call, that has an hidden input field within:

我有一个元素,在ajax调用后在页面上动态添加,其中有一个隐藏的输入字段:

<div id='added_title'>
<b>Title</b> 
<input type='hidden' id='title_n' name='title_n' value='TITLE_NAME'/>
</div>

After the ajax call i need to get input field value to show it in another div but without any event or click, just after the ajax call finish.

在ajax调用之后我需要获取输入字段值以在另一个div中显示它但没有任何事件或单击,就在ajax调用完成之后。

i tried:

$("input[name='title_n']").val();
$("input[id='title_n']").val();
$("#title_n").val()
$("#added_title input[name='title_n']").val();

I also tried to use data-attribute like this:

我也尝试使用这样的数据属性:

<div id='added_title' data-title = 'TITLE_NAME'>
    <b>Title</b> 
    </div>

accessing the data with:

访问数据:

$('#added_title').data('title');

But i always get "undefined" value.

但我总是得到“未定义”的价值。

Any suggestion?

EDIT

Ajax call:

$.ajax({
    type: 'POST',
    url: '/tools/get_title.php',
    data:  { title: title},
        success: function (response) {
            $("#title_div").html(response);
        }
});

where "title_div" is the ID of "added_title" parent.

其中“title_div”是“added_title”父级的ID。

1 个解决方案

#1


1  

$("#title_n").val() is the fastest and easiest way to get the value that you are after.

$(“#title_n”)。val()是获取你所追求的价值的最快,最简单的方法。

The problem with the code you have above, is that the $.ajax call is fired, then code continues to execute, including, presumably the call to the hidden input.

你上面的代码的问题是,$ .ajax调用被触发,然后代码继续执行,包括,可能是对隐藏输入的调用。

Then the $.ajax call completes and fires the success event, which puts said element on the page.

然后$ .ajax调用完成并触发成功事件,该事件将所述元素放在页面上。

You can't do anything with the hidden element until after the $.ajax call is finished, so you should have your code dealing with that element in a function that is called in the success function of the $.ajax call.

在$ .ajax调用完成之前,您无法对隐藏元素执行任何操作,因此您应该让代码在$ .ajax调用的success函数中调用的函数中处理该元素。

#1


1  

$("#title_n").val() is the fastest and easiest way to get the value that you are after.

$(“#title_n”)。val()是获取你所追求的价值的最快,最简单的方法。

The problem with the code you have above, is that the $.ajax call is fired, then code continues to execute, including, presumably the call to the hidden input.

你上面的代码的问题是,$ .ajax调用被触发,然后代码继续执行,包括,可能是对隐藏输入的调用。

Then the $.ajax call completes and fires the success event, which puts said element on the page.

然后$ .ajax调用完成并触发成功事件,该事件将所述元素放在页面上。

You can't do anything with the hidden element until after the $.ajax call is finished, so you should have your code dealing with that element in a function that is called in the success function of the $.ajax call.

在$ .ajax调用完成之前,您无法对隐藏元素执行任何操作,因此您应该让代码在$ .ajax调用的success函数中调用的函数中处理该元素。