[英]how to Get the value of input type hidden in modal using ajax
美好的一天..
我有模態,在模態中我有div類
<div id="user-details-content" class="modal-body">
...
</div>
我使用ajax在模態內部提供內容。
這是提供的內容:
<div id="hidden" class="hidden">
<input type="hidden" name="id" class="id" id="id" value="1">
<input type="hidden" value="email@email.com" class="email">
</div>
現在,我嘗試使用此ajax來獲取輸入type =“ hidden”
var id = $(this).parents('#user-details-content').find('.id').val();
但它在我的console.log中返回undefined
有什么建議么 ? 關於如何獲取輸入type =“ hidden”和值?
編輯-這是我的ajax功能
function inquiryId(){
var id = $(this).parents('#user-details-content').find('.id').val();
console.log(id);
$.ajax({
url: 'php_file.php',
type: 'POST',
data: { id: id,
},
dataType: 'json',
success: function(result){
console.log(result);
}
});
}
可能會出現此問題,因為在加載DOM之后加載了html。 我猜你有某種事件監聽器嗎?
解決方法可能是在執行以下操作:
$(document).on('some_event', '#your_css_selector', function(e){
// do your stuff here
});
只想獲取輸入類型=隱藏值?
無論是隱藏還是顯示,JQuery都可以獲取該值。
$('#id').val(); $('.email').val();
還行吧。
從代碼行:
var id = $(this).parents('#user-details-content').find('.id').val();
如果您知道input[type="hidden"]
的確切id
和class
屬性,我建議使用$("#id").val()
和$(".email").val()
。 以下是演示我的建議的代碼段,希望對您有所幫助。
$(function(){ $("button").click(function(event) { buttonSubmit_OnClick(); }); }); function buttonSubmit_OnClick() { var message; message = "Hello " + $("#id").val() + "! "; message += $(".email").val(); $("p").html($("p").html() + "<br>" + message); /* $.ajax() code-block goes here */ }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div id="hidden" class="hidden"> <input type="hidden" name="id" class="id" id="id" value="1"> <input type="hidden" value="email@email.com" class="email"> <button>Click me!</button><!-- this is for demo! --> </div> <p></p><!-- this is for demo! -->
附帶說明 :
為了更好的客戶端代碼優化:
$(this)
功能強大 ,但也可以使用通配符 。 jQuery始終在更新this
,因此, this
可能並不總是您期望的那樣。 最好僅在確實需要將其引用存儲在變量中時使用。 請記住, 強大的力量帶來巨大的責任 。
基於ID的選擇器要快得多,因為它們是使用瀏覽器固有的document.getElementById()
處理的,而不是通過jQuery的繁瑣選擇引擎進行處理。
.children()
或.parents()
這是關於優化jQuery選擇器的更雄辯的讀物。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.