2016-10-03 73 views
1

我有2個jQuery事件發生在form內部。 form內有一個select元素:如何在函數-2中使用jquery函數-1變量值?

事件1處於選定更改狀態。它的存儲選擇的選項值的變量:

$('#sm_name').change(function(){ 
    var option_value = $('#sm_name option:selected').val(); 
    console.log(option_value); 
}); 

事件2是在表單提交使用$.ajax()

$("#fb_form").on('submit', function (e) { 
    e.preventDefault(); 
    $("#message").empty(); 
    $("#loading").show(); 

    $.ajax({ 
     url: "submit.php", 
     type: "POST",     // Type of request to be send, called as method 
     data: new FormData(this),  // Data sent to server, a set of key/value pairs (i.e. form fields and values) 
     contentType: false,   // The content type used when sending data to the server. 
     cache: false,     // To unable request pages to be cached 
     processData: false,   // To send DOMDocument or non processed data file it is set to false 
     success: function (data) { // A function to be called if request succeeds 
     } 
    }); 
}); 

我怎樣才能動態地改變AJAX URL從select下拉列表中每個選定的價值?事情是這樣的:

url: "submit.php?id=" + option_value, 
+0

網址: 「submit.php ID =?」 + $( '#sm_name' ).val() – Majid

+0

declare var option_value;全球。或使用url:「submit.php?id =」+ $('#sm_name option:selected')。val() –

+0

@DeepakSharma雖然它會起作用,但應避免使用全局變量 –

回答

0

您可以直接得到dropdownsubmit form到在dropdown

url: "submit.php?id="+$('#sm_name').val() 
1

選擇您只需在submit處理程序中讀取select值的網址:

$("#fb_form").on('submit', function (e) { 
    e.preventDefault(); 
    $("#message").empty(); 
    $("#loading").show(); 

    $.ajax({ 
     url: "submit.php?id=" + $('#sm_name').val(), 
     type: "POST", 
     data: new FormData(this), 
     contentType: false, 
     cache: false, 
     processData: false, 
     success: function (data) { 
      // do something on request success... 
     } 
    }); 
}); 

請注意直接使用val()select元素 - 您無需訪問選定的選項即可獲取該值。

+0

沒問題。如果有幫助,不要忘記加註/接受答案。 –

0

這是不特定的jQuery,在JavaScript中你可以使用一個功能叫做閉包使用變量從外部範圍:

var outerScopeVariable = null; 

function a() { 
    outerScopeVariable = 'hello world'; 
} 

function b() { 
    console.log(outerScopeVariable); // will output 'hello world' if 
            // function a() has previously been called. 
} 
+0

謝謝。工作。 –

相關問題