0

I have a PHP form, which has a drop down menu for employment status with the options as "employed", "self employed" and "unemployed".

I'd like to show a validation message if someone selects unemployed when they try to submit the form.

My code is below

var employment = $("#employment").val().length; 

if( employment == 0 )
{
    $("#employment").parent().css('background-color', '#B2E120');
    error = true;
}
else{
    $("#employment").parent().css('background-color', '#fff');
}

and my drop down code is as below.

<option value="unemployed" title="Your tooltip here">Unemployed</option>

1 Answer 1

0

Let's assume your markup more thoroughly looks like this:

<select name="employment">
  <option value="unemployed" title="Unemployed title">Unemployed</option>
  <option value="selfemployed" title="Self-Employed title">Self-Employed</option>
  <option value="employed" title="Employed title">Employed</option>
</select>

Then, you could bind the change event to the select element, and execute a function that conditionally adds a background color:

<script>
// Wait until jQuery has loaded
$(function(){
  // Bind change event
  $('[name="employment"]').change(function(){
    var val = $('[name="employment"] :selected').val();
    if(val == 'unemployed') {
      $('[name="employment"]').css('background-color', '#b2e120');
    } else {
      $('[name="employment"]').css('background-color', '#fff');
    }
  });
});
</script>

You can see this in action here: http://jsfiddle.net/yMPHV/1/

Notice that this only fires when the selection changes. So, if you want the same code to execute upon page load, add this after binding to the change event:

$('[name="employment"]').change();

This will trigger the change event of the select element, thereby executing the same logic.

2
  • Hi Thanks for replying. What I would like to achieve is when someone submits button. it checks if the employment drop down is "unemployed" or not. If it isnt unemployed then it just goes processing the formmail script otherwise, it just shows tooltip for employment selection option (saying we cant serve unemployed enquiries) Is this possible? Feb 20, 2014 at 2:27
  • Yes, you did say that in your original post, I'm sorry. Instead of binding to the change event of the select element, bind to the submit event of the form, as follows: $('#employment-form').submit(function(){ var val = $('[name="employment"] :selected').val(); if(val == 'unemployed') { $('[name="employment"]').css('background-color', '#b2e120'); return false; // prevents form from being submitted } return true; // will now process form's 'action' }); Feb 20, 2014 at 3:47

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.