JQuery – 获取select值

我试图通过jQuery从下拉列表中select的值。 我有一点点的JavaScriptvalidation表单,当我点击发送,以确保没有空白,代码如下:

function formCheckDancer(formobj){ // Enter name of mandatory fields var fieldRequired = Array("dancerStageName", "dancerFullName", "dancerPhone", "dancerEmail", "dancerCountry", "dancerAvailableDate"); // Enter field description to appear in the dialog box var fieldDescription = Array("Stage Name", "Full Name", "Phone Number", "Email Address", "Nationality", "Availability"); // dialog message var alertMsg = "Please complete the following fields:\n"; var l_Msg = alertMsg.length; for (var i = 0; i < fieldRequired.length; i++){ var obj = formobj.elements[fieldRequired[i]]; if (obj){ switch(obj.type){ case "select-one": if (obj.selectedIndex == -1 || obj.options[obj.selectedIndex].text == "" || obj.options[obj.selectedIndex].text == "..."){ alertMsg += " - " + fieldDescription[i] + "\n"; } break; case "select-multiple": if (obj.selectedIndex == -1){ alertMsg += " - " + fieldDescription[i] + "\n"; } break; case "text": case "textarea": if (obj.value == "" || obj.value == null){ alertMsg += " - " + fieldDescription[i] + "\n"; } break; case "checkbox": if (obj.checked == false){ alertMsg += " - " + fieldDescription[i] + "\n"; } break; default: } if (obj.type == undefined){ var blnchecked = false; for (var j = 0; j < obj.length; j++){ if (obj[j].checked){ blnchecked = true; } } if (!blnchecked){ alertMsg += " - " + fieldDescription[i] + "\n"; } } } } if (alertMsg.length == l_Msg){ return sendDetailsDancer(); //Send email if all field are populated. return true; }else{ alert(alertMsg); return false; } } function sendDetailsDancer(){ var stagename = $("input[name=dancerStageName]").val(); var fullname = $("input[name=dancerFullName]").val(); var phone = $("input[name=dancerPhone]").val(); var email = $("input[name=dancerEmail]").val(); var nationality = $("#dancerCountry").val(); var availability = $("input[name=dancerAvailableDate]").val(); $("#contact_form_result_dancer").html('<center><img src="loading.gif" width="32" height="32" /></center>'); $("#contact_form_result_dancer").show(); $.post("http://localhost/lapello/wp-content/themes/lapello/sendMailDancer.php", {stagename: stagename, fullname: fullname, phone: phone, email: email, nationality: nationality, availability: availability}, function (data){ $("#contact_form_result_dancer").html(data); }); setTimeout("contactReturnDancer()", 4000); return false; } 

在这种情况下,国籍是我想要的价值。 正如你所看到的我已经尝试过:

 var nationality = $("#dancerCountry").val(); 

这似乎不工作。

如果我把下面的alert语句:alert(obj.options [obj.selectedIndex] .text); 在“select-one”的情况下输出正确的值,所以我知道它被正确地传递。

我只是不知道如何捕获它在sendDetailsDancer函数。

任何帮助赞赏。

问候,斯蒂芬

var nationality = $("#dancerCountry").val(); 应该pipe用。 你确定元素select器工作正常吗? 也许你应该尝试:

 var nationality = $('select[name="dancerCountry"]').val(); 

val()返回<select>元素的value ,即所选<option>元素的value属性。

既然你真的想要所选的<option>元素的内部文本 ,你应该匹配该元素,并使用text()来代替:

 var nationality = $("#dancerCountry option:selected").text();