Jump to content

validating selection in dropdown menu


peppericious

Recommended Posts

I have a dropdown menu in a form where users must select their instrument: here's the dropdown:

 

<label for="instrument"><span class='red'>*</span>Your main instrument</label>
                                <select name="instrument" id="instrument">
                                  <option value="select" selected="selected">Select your instrument…</option>
                                  <option value="bassoon">Bassoon</option>
                                  <option value="cello">Cello</option>
                                  <option value="clarinet">Clarinet</option>
                                  <option value="double_bass">Double Bass</option>
                                  <option value="flute">Flute</option>
                                  <option value="french_horn">French Horn</option>
                                  <option value="oboe">Oboe</option>
                                  <option value="percussion">Percussion</option>
                                  <option value="trombone">Trombone</option>
                                  <option value="trumpet">Trumpet</option>
                                  <option value="tuba">Tuba</option>
                                  <option value="viola">Viola</option>
                                  <option value="violin">Violin</option>
                                  <option value="other">Other</option>
                                </select>

 

 

I want to validate to ensure that the user has selected an instrument from the list. I was going to do something like this:

 

// validate for instrument selection
    if(!isset($_POST['instrument'])) {
      $serrors[] = 'Please select your instrument.';
    } else {
      $_SESSION['instrument'] = $_POST['instrument'];
    }

 

 

The problem is, the session variable gets set if the user bypasses the menu altogether, leaving the default 'Select your instrument...' option (at the top) as it is.

 

How can I ensure a selection other than the 'Select your instrument...' at the top of the list?

 

Thanks in advance.

Link to comment
Share on other sites

That doesn't validate that an actual, available option from the list has been selected. In order to do that, the easiest thing to do would be to construct an array containing the values, and use the array both to build the <option> list, and to validate that a proper value was selected via in_array.

 

$instruments = array('bassoon', 'cello', 'clarinet'); // etc.

echo "<select name=\"instrument\">\n";
echo "<option value=\"select\">Select One</option>\n";
foreach( $instruments as $v ) {
echo "<option value=\"$v\">" . ucfirst($v) . "</option>\n";
}
echo "</select>\n";

 

Then simply validate the field like so:

if( isset($_POST['instrument']) && in_array($_POST['instrument'], $instruments) ) {
// field is set and contains a valid value.
} else {
        // no selection made, or invalid value supplied
}

Link to comment
Share on other sites

That's very helpful and informative, Pikachu2000...

 

However, when I put this in my form....

 

<label for="instrument"><span class='red'>*</span>Your main instrument</label>
                                <?php
                                  $instruments = array(
                                              'bassoon',
                                              'cello',
                                              'clarinet',
                                              'double bass',
                                              'flute',
                                              'french horn',
                                              'oboe',
                                              'percussion',
                                              'trombone',
                                              'trumpet',
                                              'tuba',
                                              'viola',
                                              'violin',
                                              'other'
                                              );
                                  echo "<select name=\"instrument\">\n";
                                  echo "<option value=\"select\">Select One</option>\n";
                                  foreach( $instruments as $v ) {
                                    echo "<option value=\"$v\">" . ucfirst($v) . "</option>\n";
                                  }
                                  echo "</select>\n";
                                  ?>
                              </li>

 

.. and this at the top, with my other validations....

 

if(isset($_POST['instrument']) && in_array($_POST['instrument'], $instruments)) {
         $_SESSION['instrument'] = $_POST['instrument'];
        } else {
         $errors[] = 'Please select your instrument.';
        }

 

... I get a "Notice: Undefined variable: instruments..." message on line 62, that is this line...

if(isset($_POST['instrument']) && in_array($_POST['instrument'], $instruments)) {

 

...?

Link to comment
Share on other sites

Here's the whole script... be gentle, I'm an amateur... it's for a site I did up for my local orchestra...

 

 

<?php
session_start();
    // check to ensure user has come from select screen
    if(!isset($_SESSION['form_started'])) {
      header('Location: ar_select.php');
      exit();
    } 
  $formtype = $_SESSION['formtype'];
  $orch = $_SESSION['orch'];
  $page_title = "Register/Audition | Musical Experience";

// run validations on all input 
if(isset($_POST['submit'])) { 
  include('includes/mysqli_connect.php');
  $errors = array();
    // teacher first
    if (empty($_POST['mus_teacher_fname'])) {
        // $errors[] = '<strong>Music Teacher First Name</strong>: you forgot to enter this.';
      } else {
        if (get_magic_quotes_gpc()) {
          $_SESSION['mus_teacher_fname'] = ucwords(mysqli_real_escape_string($dbc, stripslashes(trim($_POST['mus_teacher_fname'])))); }
        else {
          $_SESSION['mus_teacher_fname'] = ucwords(mysqli_real_escape_string($dbc, trim($_POST['mus_teacher_fname'])));
          }
      }

    // teacher last
    if (empty($_POST['mus_teacher_lname'])) {
        // $errors[] = '<strong>Music Teacher Last Name</strong>: you forgot to enter this.';
      } else {
        if (get_magic_quotes_gpc()) {
          $_SESSION['mus_teacher_lname'] = ucwords(mysqli_real_escape_string($dbc, stripslashes(trim($_POST['mus_teacher_lname'])))); }
        else {
          $_SESSION['mus_teacher_lname'] = ucwords(mysqli_real_escape_string($dbc, trim($_POST['mus_teacher_lname'])));
          }
      }  

      // Examining Body

    if (empty($_POST['ex_body'])) {
        // $errors[] = '<strong>Examining Body</strong>: you forgot to enter this.';
      } else {
        if (get_magic_quotes_gpc()) {
          $_SESSION['ex_body'] = ucwords(mysqli_real_escape_string($dbc, stripslashes(trim($_POST['ex_body'])))); }
        else {
          $_SESSION['ex_body'] = ucwords(mysqli_real_escape_string($dbc, trim($_POST['ex_body'])));
          }
      }

      // Musical experience
    if (empty($_POST['mus_exp'])) {
            // $errors[] = '<strong>Musical experience</strong>: you forgot to enter this.';
          } else {
            if (get_magic_quotes_gpc()) {
              $_SESSION['mus_exp'] = ucwords(mysqli_real_escape_string($dbc, stripslashes(trim($_POST['mus_exp'])))); }
            else {
              $_SESSION['mus_exp'] = ucwords(mysqli_real_escape_string($dbc, trim($_POST['mus_exp'])));
              }
          }

      // instrument
    if(isset($_POST['instrument']) && in_array($_POST['instrument'], $instruments)) {
         $_SESSION['instrument'] = $_POST['instrument'];
        } else {
         $errors[] = 'Please select your instrument.';
        }
    // end validations


      if(empty($errors)) {
        // get all the session variables and write them to the db

        ////////////////////
      }

} // close IF submitted conditional

include('includes/header.php');
?>
  <p><img src="images/demo-images/art1.gif" alt="" width="170" height="220" /></p>
    </div> <!-- c1 content closer -->
</div> <!-- c1 closer -->
  <div id="c2">
    <div class="content">
      <p><img src="images/site/reg_banner_3.png" /><p>
      <h2><?php echo $formtype . " for " . $orch; ?></h2>
        <p>Fields marked with an asterisk (<span class='red'>*</span>) are required.</p>
          
<?php
      ////////////
      // if no errors, say post done
        if (!empty($errors)) { // If everything's OK.
                // errors, so report them
                echo "<div id='error_box'><h2>Oops!…</h2>
                <ul class='error'>Please fix the following error(s):" ;
                      foreach ($errors as $msg) { // display each error
                        echo "<li>" . $msg . "</li>";
                      }
                echo '</ul></div>';
              }
      ////////////
?>
          <div id='reg_form'>
            <form id="form1" name="form1" method="post" action="">
              <fieldset>
                        <legend>Music related information</legend>
                          <div class='col'>
                            <ul>
                              <li>
                                <label for="music_school">Music School</label>
                                  <select name="music_school" id="music_school">
                                    <option value="csm" selected="selected">CSM</option>
                                    <option value="abrsm">ABRSM</option>
                                    <option value="ccvec">CCVEC</option>
                                    <option value="ria">RIA</option>
                                    <option value="other">Other</option>
                                  </select>
                                  <label for="mus_teacher_fname">Music Teacher First Name</label>
                                  <input type="text" name="mus_teacher_fname" id="mus_teacher_fname" />
                                  <label for="mus_teacher_lname">Last Name</label>
                                  <input type="text" name="mus_teacher_lname" id="mus_teacher_lname" />
                              <label for="instrument"><span class='red'>*</span>Your main instrument</label>
                                <?php
                                  $instruments = array(
                                              'bassoon',
                                              'cello',
                                              'clarinet',
                                              'double bass',
                                              'flute',
                                              'french horn',
                                              'oboe',
                                              'percussion',
                                              'trombone',
                                              'trumpet',
                                              'tuba',
                                              'viola',
                                              'violin',
                                              'other'
                                              );
                                  echo "<select name=\"instrument\">\n";
                                  echo "<option value=\"select\">Select One</option>\n";
                                  foreach( $instruments as $v ) {
                                    echo "<option value=\"$v\">" . ucfirst($v) . "</option>\n";
                                  }
                                  echo "</select>\n";
                                  ?>
                              </li>
                            </ul>
                            </div>
                          <div class='col'>
                        <ul>
                          <li>
                            <p style='font-weight:bold'>Last music exam passed:</p>
                            <label for="grade">Grade</label>
                            <select name="grade" id="grade">
                              <option value="1" selected="selected">1</option>
                              <option value="2">2</option>
                              <option value="3">3</option>
                              <option value="4">4</option>
                              <option value="5">5</option>
                              <option value="6">6</option>
                              <option value="7">7</option>
                              <option value="8">8</option>
                            </select>
                            <label for="mus_ex_year">Year</label>
                            <select name="mus_ex_year" id="mus_ex_year">
                            <?php
                              for ($year = date("Y")-10; $year <= date("Y"); $year+= 1) {
                                  echo "<option value='" . $year . "'>" . $year . "</option>";
                                }
                            ?>
                            </select>
                            <label for="ex_body">Examining Body</label>
                            <input type="text" name="ex_body" id="ex_body" />
                          </li>
                          </ul>
                          </div>
                          <div class='clearfloat'></div>
                          <label for="mus_exp">Do you already have experience of playing in an orchestra or other ensemble?</label>
                          <textarea name="mus_exp" id="mus_exp" ></textarea>
              </fieldset>
              <fieldset>
                  <legend>Terms & Conditions</legend>
                  <input type="checkbox" name="t_and_c" id="t_and_c" />
                  <label for="t_and_c" style="display:inline;">I have read and agree to the <a href="#">Terms & Conditions</a> of Cork Youth Orchestra.</label>
              </fieldset>
              <input type="submit" name="submit" id="submit" value="Submit My Application" />
            </form>
          </div> <!-- reg form closer -->
    </div> <!-- c2 content closer -->
</div> <!-- c2 closer -->

<?php 
  include('includes/footer.php');
?>

Link to comment
Share on other sites

Looks like you just need to move the array definition up above the call to in_array(), and that should take care of it. Variables have to be defined before attempting to access them.

 

.. should've thought of that. Done now and working like a charm. Thanks a lot.... What a forum this is!

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.