【问题标题】:HTML form with multiple select to Javascript多选到 Javascript 的 HTML 表单
【发布时间】:2020-09-06 04:20:31
【问题描述】:

我是 javascript 的新手,我可以在这里提供一些帮助。

我有一个包含多选字段的表单,如下所示:

        <select name="services[]" class="required" multiple="multiple" >
        <option style="padding:5px;" value="">Pleae Select </option>
        <option style="padding:5px;" value="TAX CREDITS">TAX CREDITS </option>
         <option style="padding:5px;" value="CHILD BENEFIT">CHILD BENEFIT</option>
        <option style="padding:5px;" value="SELF EMPLOYMENT & CIS ISSUES">SELF EMPLOYMENT & CIS 
            ISSUES </option>
         <option style="padding:5px;" value="THE EMPLOYED (PAYE)">THE EMPLOYED (PAYE)</option>
        <option style="padding:5px;" value="OTHER SERVICES">OTHER SERVICES</option>
        </select>

提交时的表单在使用 ajax 提交到 php 引擎之前使用 javascript 进行验证。以下是适用于除服务字段之外的所有字段的 javascript。我知道服务返回一个值数组,但 .val() 似乎不适用于数组字段并返回空白。请问我应该如何设置 "services":$('select[name="services"]').val(), 行返回一个值?

<script>
$(document).ready(function (e){
    $("#frmContact").on('submit',(function(e){
        e.preventDefault();
        $("#mail-status").hide();
        $('#send-message').hide();
        $('#loader-icon').show();
        $.ajax({
            url: "contact.php",
            type: "POST",
            dataType:'json',
            data: {
            "name":$('input[name="name"]').val(),
            "email":$('input[name="email"]').val(),
            "phone":$('input[name="phone"]').val(),
            "services":$('select[name="services"]').val(),
            "content":$('textarea[name="content"]').val(),
            },              
            success: function(response){
            $("#mail-status").show();
            $('#loader-icon').hide();
            if(response.type == "error") {
                $('#send-message').show();
                $("#mail-status").attr("class","error");                
            } else if(response.type == "message"){
                $('#send-message').hide();
                $("#mail-status").attr("class","success");                          
            }
            $("#mail-status").html(response.text);  
            },
            error: function(){} 
        });
    }));
});
</script>

【问题讨论】:

  • 这个“php”有什么关系?

标签: javascript php html json ajax


【解决方案1】:

尝试类似:

$("select[name='services'] option:selected").val();

对于多个选择器

var multiple = [];
$.each($("select[name='services'] option:selected"), function(){            
        multiple.push($(this).val());
});
alert("Select values - " + multiple.join(", "));

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-04-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-02-13
    • 2016-12-28
    • 2011-03-22
    相关资源
    最近更新 更多