Javascript联系表单未从下拉列表中返回选定的值

时间:2016-08-31 15:52:55

标签: javascript contact-form

我有一个未在生成的电子邮件中返回所选选项的联系表单,它一直说“未定义”。

这是我目前所拥有的(我从表格上的其他一个工作问题中复制过来)。

var topic = $("select#topic").val();
    if (topic == "") {
        $("label#topic_error").show();
        $("select#topic").focus();
        return false;
    }

  var dataString = 'name=' + name + '&email=' + email +  '&message=' + message + '&topic=' + topic + '&phone=' + phone + '&address=' + address;
    //alert (dataString);return false;

    $.ajax({
        type:"POST",
        url:"process.php",
        data:dataString,
        success:function () {
            $('#af-form').prepend("<div class=\"alert alert-success fade in\"><button class=\"close\" data-dismiss=\"alert\" type=\"button\">&times;</button><strong>Contact Form Submitted!</strong> We will be in touch soon.</div>");
            $('#af-form')[0].reset();
        }
    });
    return false;
});

});

相关项目的html格式为:

     <select name="topic" id="topic">
        <option value=""></option>
        <option value="General">General Information</option>
        <option value="Sessions">Signing up for Support Sessions</option>
        <option value="facilitator">Becoming a Facilitator</option>
      </select>

我不知道我在用javascript做什么,所以我甚至无法查找答案。谁能告诉我我的错误?

1 个答案:

答案 0 :(得分:0)

You can see the select value onclick like this

$(document).ready(function(){ 
  $('#button1').click(function(){ 
    alert($('#combo :selected').text());
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="combo">
  <option value="1">Test 1</option>
  <option value="2">Test 2</option>
</select>
<input id="button1" type="button" value="Click!" />

If you want to send it these values to your email you can try a POST request like this.

<form method="post" action="process.php">
  <select name="taskOption">
    <option value="first">First</option>
    <option value="second">Second</option>
    <option value="third">Third</option>
  </select>
  <input type="submit" value="Submit the form"/>
</form>

PHP

<?php
   $option = isset($_POST['taskOption']) ? $_POST['taskOption'] : false;
   if ($option) {
      echo htmlentities($_POST['taskOption'], ENT_QUOTES, "UTF-8");
   } else {
     echo "task option is required";
     exit; 
   }