[英]How to insert Bootstrap drop-down values in database
我正在使用引導程序制作用戶表單。 現在,我需要在數據庫中插入選定的下拉值。 但是我面臨兩個問題。
1)當我從下拉列表中選擇任何項目時,由於href =“#”,它會跳到url中屏幕的頂部。 當我刪除“#”時,它開始在選擇項上刷新頁面。
2)我如何針對我的下拉列表,以使用PHP在數據庫中插入任何選定的值。
我的代碼是
<div class="dropdown">
<button class="btn btn-default dropdown-toggle" type="button" data-toggle="dropdown">Select City
<span class="caret"></span></button>
<ul class="dropdown-menu">
<li><a href="#">Lahore</a></li>
<li><a href="#">Islamabad</a></li>
<li><a href="#">karachi</a></li>
</ul>
</div>
JavaScript代碼
$(document).ready(function() {
$(".dropdown-menu li a").click(function(){
$(this).parents(".dropdown").find('.btn').html($(this).text() + ' <span class="caret"></span>');
$(this).parents(".dropdown").find('.btn').val($(this).data('value'));
});
對於要點1 :由於href中有#
,因此頁面會向上滾動(即導航到鏈接目標)。 您可以通過在代碼中添加event.preventDefault()
來防止此事件。
對於第2點 :由於您說過如果您能夠將值獲取到服務器端php代碼,則可以繼續進行操作,可以使用AJAX Post方法 。 最終的代碼是
$(document).ready(function() {
$(".dropdown-menu li a").click(function(e){
e.preventDefault(); //this is the line which prevents the event
$(this).parents(".dropdown").find('.btn').html($(this).text() + ' <span class="caret"></span>');
$(this).parents(".dropdown").find('.btn').val($(this).data('value'));
//this is the code to post the value to server
$.post("YourPHPMethod.php",{name: $(this).text()} ,function(response){
alert("Response from server: "+response);
});
});
您必須將其發布到php。 我用這樣的ajax來做。
外觀: http : //www.codesheet.org/codesheet/wOHDXFju
function postContent(cv) {
$("#myDiv").html('L O A D I N G ...').show();
var url = "/post.php";
$.post(url, {id: cv} ,function(data) { //contentVar is the variable in post.php
$("#myDiv").html(data).show();
});
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.