2014-09-09 4 views
-3

Я пытаюсь создать форму для отправки мне электронной почты, когда пользователь заполняет все поля, я следовал учебному курсу, чтобы собрать его, чтобы что там работает, но я хочу реализовать вариант, который позволяет людям выберите другой ... Вот как это:PHP и HTML-форма

У меня есть форму, которая запрашивает ваше имя, адрес электронной почты, тип и сообщение.

Тип имеет 4 варианта: Обратная связь, Отчет об ошибках, Запрос функций и прочее, я бы хотел, чтобы при нажатии на другой переключатель, текстовое поле имеет вход, поэтому они не могут просто пропустить, нажав другие, но если они выбрали что-то еще, что не является другим, тогда я не хочу, чтобы они вводили текстовое поле, но независимо от того, что я пробовал, он либо вообще не работает, либо имеет вход в текстовое поле, даже если я не выбираю другая радиокнопка ...

Проблема решена, я прошу, чтобы эта тема оставалась открытой, чтобы другие могли продолжать использовать эту страницу, или если я что-то сломаю ... Спасибо Rasclatt, вы были удивительной помощью:)

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script> 
<script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.10.4/jquery-ui.min.js"></script> 
<script src="https://ajax.aspnetcdn.com/ajax/jquery.validate/1.11.1/jquery.validate.js"></script> 
<link href="contact/css/contactForm.css" rel="stylesheet"> 
<title>Contact Us</title> 
<?php error_reporting(0); ?> 
<?php if(isset($_POST['Email'])): ?> 
    <?php 
    print_r($_POST); 
      // This is where you process the email and display the thank you page 
      $to  = '[email protected]'; 
      $subject = 'ALERT! Website Form Submission'; 
      $message = 'Users Email: '.strip_tags($_POST['Email'])."\n"; 
      $message .= 'Submitted Message: '.strip_tags($_POST['Comment'])."\n"; 
      $message .= 'Message Type: '.strip_tags($_POST['Type'])."\n"; 
      $headers = 'From: [email protected]' . "\r\n" . 
       'Reply-To: '.strip_tags($_POST['Email']) . "\r\n"; 
      // If the mail is successful, display thanks or display failed 
      ?> 
      <?php if(mail($to, $subject, $message, $headers)): ?> 
       // Display the thank you page } 
       <div id="comments_form"> 
        <h2 style="size:35px;">Thanks For Your Message!</h2>   
        <p style="font-size: 20px; font-family:Arial, Helvetica, sans-serif; color:#000; margin-left: 25px;">You Will Be Redirected Shortly!</p>   
        <p style="font-size: 15px; font-family:Arial, Helvetica, sans-serif; color:#000; margin-left: 25px;">Expect your message to be responded to within 2 working days</p> 
        <script type="text/javascript"> 
         setTimeout('redirectPage()', 3000) 
         function redirectPage() { 
          location.href="index.html" 
         }; 
       </script> 
      <?php else: ?> 
       <div id="comments_form"> 
       <h2 style="size:35px;">Uh Oh! Your Message Could Not Be Sent</h2>   
       <p style="font-size: 20px; font-family:Arial, Helvetica, sans-serif; color:#000; margin-left: 25px;">An Unexpected Error Occured While Trying To Send Your Message</p>   
       <p style="font-size: 15px; font-family:Arial, Helvetica, sans-serif; color:#000; margin-left: 25px;">You Are Being Redirected To The Home Page</p> 
        <script type="text/javascript"> 
        setTimeout('redirectPage()', 3000) 
         function redirectPage() { 
         location.href="index.html" 
         }; 
       </script> 
      <?php endif ?> 
    </div> 
<?php else: ?> 
<form method="post" id="comments_form"> 
    <div class="row"> 
     <div class="label"> 
      Your Name 
     </div> 
     <!--.label end--> 
     <div class="input"> 
      <input type="text" id="fullname" class="detail" name="Name" 
       value="<?php echo isset($_POST['Name'])? $_POST['Name'] : ''; ?>" /> 
      <?php if(in_array('Name', $validation)): ?> 
      <span class="error"><?php echo $error_messages['Name']; ?></span> 
      <?php endif; ?> 
     </div> 
     <!--.input end--> 
     <div class="context"> 
      e.g. John Smith or Jane Doe 
     </div> 
     <!--end .context--> 
    </div> 
    <!--.row end--> 

    <div class="row"> 
     <div class="label"> 
      Your Email 
     </div> 
     <!--.label end--> 
     <div class="input"> 
      <input type="text" id="email" class="detail" name="Email" value="<?php echo isset($_POST['Email'])? $_POST['Email'] : ''; ?>" /> 
      <?php if(in_array('Email', $validation)): ?> 
      <span class="error"><?php echo $error_messages['Email']; ?></span> 
      <?php endif; ?> 
     </div> 
     <!--.input end--> 
     <div class="context"> 
      We wont spam you! We only need this to reply to questions you might pose 
     </div> 
     <!--end .context--> 
    </div> 
    <!--.row end--> 

    <div class="row"> 
     <div class="label"> 
      Type Of Message 
     </div> 
     <!--.label end--> 
     <div class="input"> 
      <input type="radio" name="Type" onChange="GetValue(this)" value="Feedback" checked="checked" /> 
      Feedback <br /> 
      <input type="radio" name="Type" onChange="GetValue(this)" value="Feature Request" <?php echo (isset($_POST['Type']) && $_POST['Type'] == 'Feature Request')? 'checked="checked"' : ''; ?> /> 
      Feature Request<br> 
      <input type="radio" name="Type" onChange="GetValue(this)" value="Bug Report" <?php echo (isset($_POST['Type']) && $_POST['Type'] == 'Bug Report')? 'checked="checked"' : ''; ?> /> 
      Bug Report<br> 
      <input type="radio" name="Type" onChange="GetValue(this)" value="Other" id="other" <?php echo (isset($_POST['Type']) && $_POST['Type'] == 'Other')? 'checked="checked"' : ''; ?> /> 
      Other<br /> 
      <input type="text" style="display:none;" id="option" name="Type" <?php echo (isset($_POST['Type']) && $_POST['Type'] == 'option')? 'checked="checked"' : ''; ?> /> 
      <?php if(in_array('Type', $validation)): ?> 
      <span class="error"> <?php echo $error_messages['Type']; ?> </span> 
      <?php endif; ?> 
     </div> 
     <!--.input end--> 
     <div class="context"> 
      This is to help us better respond to your message 
     </div> 
     <!--end .context--> 
    </div> 
    <!--.row end--> 

    <div class="row"> 
     <div class="label"> 
      Your Message 
     </div> 
     <!--.label end--> 
     <div class="input2"> 
      <textarea id="Comment" name="Comment" class="mess"><?php echo isset($_POST['Comment'])? $_POST['Comment'] : ''; ?></textarea> 
      <?php if(in_array('Comment', $validation)): ?> 
      <span class="error"><?php echo $error_messages['Comment']; ?></span> 
      <?php endif; ?> 
     </div> 
     <!--.input end--> 
    </div> 
    <!--.row end--> 

    <div class="submit"> 
     <input type="submit" id="submit" name="Submit" value="Send Message" /> 
    </div> 
</form> 
<?php endif; ?> 
<script> 
    // This function just checks if the 'other' gets checked 
function GetValue(ThisVal) { 
    var Writing = $(ThisVal).val(); 
    // This just shows you what is happening via the feedback div 
    $('#feederback').html(Writing); 
    if (Writing == 'Other') { 
     // If other, disable the submit 
     $("#submit").prop("disabled", true); 
     // Fade in the message textarea 
     $('#option').fadeIn('fast'); 
     // Check the message area to see if there is text in it already. 
     // If there is text enable the submit button 
     CheckVal(); 
    } else { 
     // If not other, fade out the message 
     $('#option').fadeOut('fast'); 
     // Enable the submit button 
     $('#submit').prop("disabled", false); 
    } 
} 

function CheckVal() { 
    var SetMess = $('#option').val(); 
    $('#feedback').html(SetMess); 

    if (SetMess !== '') { 
      $('#submit').prop('disabled', false); 
     } 
    else { 
      $('#submit').prop('disabled', true); 
     } 
} 
// As one types, check that the message is not empty 
$('#option').keyup(function() { 
    CheckVal(); 
}); 
// As one clicks into the field, see if it has content 
$('#option').click(function() { 
    CheckVal(); 
}); 

     $(document).ready(function() { 
      // validate form 
      $("#comments_form").validate({ 
       // This will allow you to extend the validator functions 
       invalidHandler: 
         function(form, validator) { 
          // $("#get_online").val("CHECK"); 
        }, 
       rules: { 
        // For every named input that you want to validate, 
        // you create a little set of prefs 
        Name: { 
         required: true, 
        }, 
        Email: { 
           required: true, 
           email: true 
          }, 

        Type: { required: true }, 
        Comment: { required: true }, 
        }, 
       messages: { 
         // Here are just the custom messages you can modify per field 
         Name: { 
           required: 'Please Enter Your Name', 
          }, 
         Email: { 
           required: 'Please Enter An Email', 
           email: 'Email address not valid', 
          }, 
         Type: { required: 'Please Select A Type' }, 
         Comment: { required: 'Please Enter A Message'}, 
        }, 
      }); 
     }); 
</script> 

-Спасибо, harry

+0

Пожалуйста, поставьте код вы сделали – arunrc

+0

Есть ли способ добавить его в какой-то тег, так оно не так велика? Потому что, когда я добавляю его, теги кода не остаются – Harry

+0

Добавьте код после выбора '{}' в меню редактора. – arunrc

ответ

0

Хорошо, так что валидация находится на самом дне. У меня есть подтверждение основных вещей. Если вы посещаете или проверяете jQuery Google, вы можете увидеть, как проверять различные поля. Это довольно легко. Убедитесь, что на вашем PHP вы фильтруете (strip_tags()) входы, чтобы вы не взломали.

 <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script> 
<script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.10.4/jquery-ui.min.js"></script> 
<script src="https://ajax.aspnetcdn.com/ajax/jquery.validate/1.11.1/jquery.validate.js"></script> 
<link href="contact/css/contactForm.css" rel="stylesheet"> 
<title>Contact Us</title> 
<?php error_reporting(0); ?> 
<?php if(isset($_POST['Email'])): ?> 
    <?php 
    print_r($_POST); 
      // This is where you process the email and display the thank you page 
      $to  = '[email protected]'; 
      $subject = 'ALERT! Website Form Submission'; 
      $message = 'Users Email: '.strip_tags($_POST['Email'])."\n"; 
      $message .= 'Submitted Message: '.strip_tags($_POST['Comment'])."\n"; 
      $message .= 'Message Type: '; 
      $message .= ($_POST['Type'] !== 'Option')? $_POST['Type']."\n": strip_tags($_POST['option'])."\n"; 
      $headers = 'From: [email protected]' . "\r\n" . 
       'Reply-To: '.strip_tags($_POST['Email']) . "\r\n"; 
      // If the mail is successful, display thanks or display failed 
      ?> 
      <?php if(mail($to, $subject, $message, $headers)): ?> 
       // Display the thank you page } 
       <div id="comments_form"> 
        <h2 style="size:35px;">Thanks For Your Message!</h2>   
        <p style="font-size: 20px; font-family:Arial, Helvetica, sans-serif; color:#000; margin-left: 25px;">You Will Be Redirected Shortly!</p>   
        <p style="font-size: 15px; font-family:Arial, Helvetica, sans-serif; color:#000; margin-left: 25px;">Expect your message to be responded to within 2 working days</p> 
        <script type="text/javascript"> 
         setTimeout('redirectPage()', 3000) 
         function redirectPage() { 
          location.href="index.html" 
         }; 
       </script> 
      <?php else: ?> 
       <div id="comments_form"> 
       <h2 style="size:35px;">Uh Oh! Your Message Could Not Be Sent</h2>   
       <p style="font-size: 20px; font-family:Arial, Helvetica, sans-serif; color:#000; margin-left: 25px;">An Unexpected Error Occured While Trying To Send Your Message</p>   
       <p style="font-size: 15px; font-family:Arial, Helvetica, sans-serif; color:#000; margin-left: 25px;">You Are Being Redirected To The Home Page</p> 
        <script type="text/javascript"> 
        setTimeout('redirectPage()', 3000) 
         function redirectPage() { 
         location.href="index.html" 
         }; 
       </script> 
      <?php endif ?> 
    </div> 
<?php else: ?> 
<form method="post" id="comments_form"> 
    <div class="row"> 
     <div class="label"> 
      Your Name 
     </div> 
     <!--.label end--> 
     <div class="input"> 
      <input type="text" id="fullname" class="detail" name="Name" 
       value="<?php echo isset($_POST['Name'])? $_POST['Name'] : ''; ?>" /> 
      <?php if(in_array('Name', $validation)): ?> 
      <span class="error"><?php echo $error_messages['Name']; ?></span> 
      <?php endif; ?> 
     </div> 
     <!--.input end--> 
     <div class="context"> 
      e.g. John Smith or Jane Doe 
     </div> 
     <!--end .context--> 
    </div> 
    <!--.row end--> 

    <div class="row"> 
     <div class="label"> 
      Your Email 
     </div> 
     <!--.label end--> 
     <div class="input"> 
      <input type="text" id="email" class="detail" name="Email" value="<?php echo isset($_POST['Email'])? $_POST['Email'] : ''; ?>" /> 
      <?php if(in_array('Email', $validation)): ?> 
      <span class="error"><?php echo $error_messages['Email']; ?></span> 
      <?php endif; ?> 
     </div> 
     <!--.input end--> 
     <div class="context"> 
      We wont spam you! We only need this to reply to questions you might pose 
     </div> 
     <!--end .context--> 
    </div> 
    <!--.row end--> 

    <div class="row"> 
     <div class="label"> 
      Type Of Message 
     </div> 
     <!--.label end--> 
     <div class="input"> 
      <input type="radio" name="Type" onChange="GetValue(this)" value="Feedback" checked="checked" /> 
      Feedback <br /> 
      <input type="radio" name="Type" onChange="GetValue(this)" value="Feature Request" <?php echo (isset($_POST['Type']) && $_POST['Type'] == 'Feature Request')? 'checked="checked"' : ''; ?> /> 
      Feature Request<br> 
      <input type="radio" name="Type" onChange="GetValue(this)" value="Bug Report" <?php echo (isset($_POST['Type']) && $_POST['Type'] == 'Bug Report')? 'checked="checked"' : ''; ?> /> 
      Bug Report<br> 
      <input type="radio" name="Type" onChange="GetValue(this)" value="Other" id="other" <?php echo (isset($_POST['Type']) && $_POST['Type'] == 'Other')? 'checked="checked"' : ''; ?> /> 
      Other<br /> 
      <input type="text" style="display:none;" id="option" name="option" <?php echo (isset($_POST['option']))? $_POST['option']: ''; ?> /> 
      <?php if(in_array('Type', $validation)): ?> 
      <span class="error"> <?php echo $error_messages['Type']; ?> </span> 
      <?php endif; ?> 
     </div> 
     <!--.input end--> 
     <div class="context"> 
      This is to help us better respond to your message 
     </div> 
     <!--end .context--> 
    </div> 
    <!--.row end--> 

    <div class="row"> 
     <div class="label"> 
      Your Message 
     </div> 
     <!--.label end--> 
     <div class="input2"> 
      <textarea id="Comment" name="Comment" class="mess"><?php echo isset($_POST['Comment'])? $_POST['Comment'] : ''; ?></textarea> 
      <?php if(in_array('Comment', $validation)): ?> 
      <span class="error"><?php echo $error_messages['Comment']; ?></span> 
      <?php endif; ?> 
     </div> 
     <!--.input end--> 
    </div> 
    <!--.row end--> 

    <div class="submit"> 
     <input type="submit" id="submit" name="Submit" value="Send Message" /> 
    </div> 
</form> 
<?php endif; ?> 
<script> 
    // This function just checks if the 'other' gets checked 
function GetValue(ThisVal) { 
    var Writing = $(ThisVal).val(); 
    // This just shows you what is happening via the feedback div 
    $('#feederback').html(Writing); 
    if (Writing == 'Other') { 
     // If other, disable the submit 
     $("#submit").prop("disabled", true); 
     // Fade in the message textarea 
     $('#option').fadeIn('fast'); 
     // Check the message area to see if there is text in it already. 
     // If there is text enable the submit button 
     CheckVal(); 
    } else { 
     // If not other, fade out the message 
     $('#option').fadeOut('fast'); 
     // Enable the submit button 
     $('#submit').prop("disabled", false); 
    } 
} 

function CheckVal() { 
    var SetMess = $('#option').val(); 
    $('#feedback').html(SetMess); 

    if (SetMess !== '') { 
      $('#submit').prop('disabled', false); 
     } 
    else { 
      $('#submit').prop('disabled', true); 
     } 
} 
// As one types, check that the message is not empty 
$('#option').keyup(function() { 
    CheckVal(); 
}); 
// As one clicks into the field, see if it has content 
$('#option').click(function() { 
    CheckVal(); 
}); 

     $(document).ready(function() { 
      // validate form 
      $("#comments_form").validate({ 
       // This will allow you to extend the validator functions 
       invalidHandler: 
         function(form, validator) { 
          // $("#get_online").val("CHECK"); 
        }, 
       rules: { 
        // For every named input that you want to validate, 
        // you create a little set of prefs 
        Name: { 
         required: true, 
        }, 
        Email: { 
           required: true, 
           email: true 
          }, 

        Type: { required: true }, 
        Comment: { required: true }, 
        }, 
       messages: { 
         // Here are just the custom messages you can modify per field 
         Name: { 
           required: 'Please Enter Your Name', 
          }, 
         Email: { 
           required: 'Please Enter An Email', 
           email: 'Email address not valid', 
          }, 
         Type: { required: 'Please Select A Type' }, 
         Comment: { required: 'Please Enter A Message'}, 
        }, 
      }); 
     }); 
</script> 
+0

Я добавил сообщение об ошибке для окна комментариев, чтобы, если бы не было сообщения, вместо этого он перезагружает страницу, как бы говоря, что она прошла проверку ... Кроме того, как мне внедрить систему сообщений, чтобы она действительно отправляла сообщение, существует ли способ сделать таблицу отображаемой в письме со столбцом для имен ввода, а затем столбца для значения, которое они ввели, если это слишком сложно, тогда просто обычный текст хорош, пока отображается имя ввода, поэтому я знаю, что это такое ... Но просто объяснение или лучше но пример. – Harry

+0

На самом деле вы захотите использовать функцию 'mail()' 'php'. Вот отличный ресурс! [Http://www.w3schools.com/php/php_form_url_email.asp](http://www.w3schools.com/php/php_form_url_email.asp). – Rasclatt

+0

Этот сайт w3schools расскажет вам все, что вам нужно знать о проверке вашей электронной почты и отправке электронного письма. Три основные функции, необходимые для дезинфекции пользовательского ввода для смягчения взлома, - это основная функция php: 'htmlentities()', 'htmlspecialchars()' и 'strip_tags()'. Приветствия. – Rasclatt

Смежные вопросы