Problem with tag select in form

Asked

Viewed 594 times

1

I developed a contact form in my website but on that form you have a select unde the person will be able to choose a service but I have no idea how to insert this into my code I would like to know if it is possible. At first my code works I just can’t capture the services option. follow my codes and error image on the console inserir a descrição da imagem aqui note that in the image the only field that appears nothing and the service

Html:

<form id="form-elements" onSubmit="return false">
                <div class="row">
                    <div class="col-md-12 center">
                        <div id="result"></div>
                    </div>
                </div>

                <div class="row">
                    <div class="col-sm-4">
                        <div class="form-group">
                            <input type="text" class="form-control input-border" placeholder="Nome" name="name"
                                   id="name" required></div>
                    </div>
                    <div class="col-sm-4">
                        <div class="form-group">
                            <input type="email" class="form-control input-border" placeholder="E-mail" name="email"
                                   id="email" required></div>
                    </div>
                    <div class="col-sm-4">
                        <div class="form-group">
                            <input type="text" class="form-control input-border" placeholder="Telefone" name="phone"
                                   id="phone" required>
                        </div>
                    </div>
                    <div class="col-sm-12">
                        <div class="form-group">
                            <select class="form-control input-border" name="service" id="service" required>
                                <option disabled selected>Escolha um serviço</option>
                                <option value="comediante">Comediante</option>
                                <option value="apresentador">Apresentador</option>
                                <option value="ator">Ator</option>
                                <option value="reporter">Repórter</option>
                                <option value="cerimonialista">Cerimonialista</option>
                                <option value="roteirista">Roteirista</option>
                            </select>
                        </div>
                    </div>
                    <div class="col-xs-12">
                            <textarea id="input" class="form-control message-input" rows="7" required="required"
                                      placeholder="Mensagem" name="message" id="message"></textarea>
                    </div>
                    <button type="submit" class="btn btn-default buttons button-send" id="submit_btn">Quero Contratar</button>
                </div>
            </form>

JS:

$("#submit_btn").click(function() {
    //get input field values
    var user_name       = $('input[name=name]').val();
    var user_email      = $('input[name=email]').val();
    var user_telephone      = $('input[name=phone]').val();
    var user_service      = $('input[name=service]').val();
    var user_message    = $('textarea[name=message]').val();

    //simple validation at client's end
    var post_data, output;
    var proceed = true;
    if(user_name==""){
        proceed = false;
    }
    if(user_email==""){
        proceed = false;
    }
    if(user_message=="") {
        proceed = false;
    }

    //everything looks good! proceed...
    if(proceed)
    {
        //data to be sent to server
        post_data = {'userName':user_name, 'userEmail':user_email, 'userTelephone':user_telephone, 'userService':user_service, 'userMessage':user_message};

        //Ajax post data to server
        $.post('contact.php', post_data, function(response){

            //load json data from server and output message
            if(response.type == 'error')
            {
                output = '<div class="alert-danger" style="padding:10px; margin-bottom:25px;">'+response.text+'</div>';
            }else{
                output = '<div class="alert-success" style="padding:10px; margin-bottom:25px;">'+response.text+'</div>';

                //reset values in all input fields
                $('#form-elements input').val('');
                $('#form-elements textarea').val('');
            }

            $("#result").hide().html(output).slideDown();
        }, 'json');

    }
});

//reset previously set border colors and hide all message on .keyup()
$("#form-elements input, #form-elements textarea").keyup(function() {
    $("#result").slideUp();
});

PHP:

<?php
if($_POST)
{
    $to_Email       = "[email protected]"; //Replace with recipient email address
    $subject        = 'Contato para contratação de serviços'; //Subject line for emails


    //check if its an ajax request, exit if not
    if(!isset($_SERVER['HTTP_X_REQUESTED_WITH']) AND strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) != 'xmlhttprequest') {

        //exit script outputting json data
        $output = json_encode(
        array(
            'type'=>'error',
            'text' => 'Request must come from Ajax'
        ));

        die($output);
    }

    //check $_POST vars are set, exit if any missing
    if(!isset($_POST["userName"]) || !isset($_POST["userEmail"]) || !isset($_POST["userMessage"]))
    {
        $output = json_encode(array('type'=>'error', 'text' => 'Os campos de entrada estão vazios!  '));
        die($output);
    }

    //Sanitize input data using PHP filter_var().
    $user_Name        = filter_var($_POST["userName"], FILTER_SANITIZE_STRING);
    $user_Email       = filter_var($_POST["userEmail"], FILTER_SANITIZE_EMAIL);
    $user_Phone =                  $_POST["userTelephone"];
    $user_Service       = filter_var($_POST["userService"], FILTER_SANITIZE_EMAIL);
    $user_Message     = filter_var($_POST["userMessage"], FILTER_SANITIZE_STRING);

    //additional php validation
    if(strlen($user_Name)<3) // If length is less than 3 it will throw an HTTP error.
    {
        $output = json_encode(array('type'=>'error', 'text' => 'O campo nome não pode ficar vazio'));
        die($output);
    }
    if(!filter_var($user_Email, FILTER_VALIDATE_EMAIL)) //email validation
    {
        $output = json_encode(array('type'=>'error', 'text' => 'Por favor ultilize um e-mail válido'));
        die($output);
    }

    if(strlen($user_Message)<5) //check emtpy message
    {
        $output = json_encode(array('type'=>'error', 'text' => 'Por favor insira uma mensagem'));
        die($output);
    }


    $message_Body = "<strong>Name: </strong>". $user_Name ."<br>";
    $message_Body .= "<strong>Email: </strong>". $user_Email ."<br>";
    $message_Body .= "<strong>Phone: </strong>". $user_Phone ."<br>";
    $message_Body .= "<strong>Serviço: </strong>". $user_Service ."<br>";
    $message_Body .= "<strong>Message: </strong>". $user_Message ."<br>";



    $headers = "From: " . strip_tags($user_Email) . "\r\n";
    $headers .= "Reply-To: ". strip_tags($user_Email) . "\r\n";
    $headers .= "MIME-Version: 1.0\r\n";
    $headers .= "Content-Type: text/html; charset=UTF-8\r\n";



    //proceed with PHP email.
    $headers = 'From: '.$user_Email.'' . "\r\n" .
    'Reply-To: '.$user_Email.'' . "\r\n" .
    'X-Mailer: PHP/' . phpversion(). "\r\n" .
    'Content-type: text/html;charset=UTF-8';



    $sentMail = @mail($to_Email, $subject, $message_Body, $headers);

    if(!$sentMail)
    {
        $output = json_encode(array('type'=>'error', 'text' => 'Ocorreu um erro tente novamente'));
        die($output);
    }else{
        $output = json_encode(array('type'=>'message', 'text' => 'Olá '. $user_Name .' Obrigado pelo seu contato retornaremos em breve.'));
        die($output);
    }
}
?>
  • 1

    You are not getting the value of the selected item in select?

  • @Well that friend actually my form doesn’t even want to work and I don’t know why I added the error that is giving on the console in question.

  • 1

    so by the error of the console is not finding this path ai, relative to select puts the HTML there to parse the code

  • http://agenciafront.com.br/fabiorabin/contact.php not found. I think it’s pretty clear what the problem is. (Sorry, the page you are Looking for could not be found.)

  • @Lennons.Bueno I added the HTML again I must have removed it at the time of editing and did not notice

  • @Lennons.Bueno Cara had made that mistake because he had forgotten to raise contact.php take a look at the question there the only part I can’t capture is the part where the person chooses a service

  • 1

    @Kirito I think I understand your mistake, I answered below if that’s right mark as answer.

  • @Lennons.Bueno guy I traveled malz ended up who didn’t even give a reply I made a comment on his reply later if I can take a look vlw

Show 3 more comments

1 answer

1


Observing your code what is missing is the attribute value us option's tag select.

A basic example of how to get the value selected with javascript is this:

var el = document.getElementById("meses");

var valor = el.value;

console.log(valor);
<select id="meses">
    <option value="Janeiro">Janeiro</option>
    <option value="Fevereiro">Fevereiro</option>
    <option value="Março">Março</option>
    <option value="Abril">Abril</option>
    <option value="Maio">Maio</option>
    <option value="Junho">Junho</option>
    <option value="Julho">Julho</option>
    <option value="Agosto">Agosto</option>
    <option value="Setembro">Setembro</option>
    <option value="Outubro">Outubro</option>
    <option value="Novembro">Novembro</option>
    <option value="Dezembro">Dezembro</option>
</select>

Or with Jquery:

$('#meses').val();

Reinforcing the selected value is always what is in the attribute value of option's.

  • Hello friend sorry for the delay I traveled and there was no way to check your answer I analyzed here and really was missing the values in my <select> only that so I’m too lay in jQuery to implement this in my js file there would look like ? would I call only id="service" in my code? or would have to put all values one by one I will update my code with what I have changed for you to take a look

  • 1

    no js would look like $('#service'). val(); and don’t forget to put the value us option's

Browser other questions tagged

You are not signed in. Login or sign up in order to post.