Check Select and input value and alert

If I use alert( mv + " " + uv); in this function the values are outputted correctly to the dialog but if I use the ‘if’ statement shown below I am not getting alerted when mv = ‘URL’ and uv is empty.

What have I done wrong?


$('#media').change( function() {
      var mv = $('#media :selected').text();
      var uv = $('#url').val();

       if ((mv=='URL') && (uv=="")) {
         alert('Please enter a valid URL');
         $('#url').focus();
        }
 });

Could you post a link to a page where I can see your problem?
Otherwise can you post enough code that we I can recreate your problem.
You can use this template.

I assume you:

  • use a select element and an input text
  • when media select control option value=“URL” is selected you expect to read the value from the input text uv
  • you check if the user inputs something
  • if not, alert and focus on the input text

If you don’t get the alert when option value=“URL” is selected then, according to if test condition, you should also test the length of the “URL” option entry of the select element and the length of the input text value. It may be that “URL” is more than three chars and/or that the input text already has some spaces in there, which will make " URL " not equal to “URL” for example and " " not equal to “” for another example.

In this case, trimming before testing should solve the problem:


if !$.trim(uv).length {}

meaning that if after trimming the length is zero, the expression will evaluate to false, so we use the not operator(!) to check for a truthy value i.e. not empty strings.

As far as the “URL” option value is concerned, it may also be that the value has additional spaces or that the case is wrong, i.e. “uRL”. So you should cast both sides to a single case, upper or lower, besides checking against trimmed values:


$.trim(mv).toUpperCase() == "URL"

This is the html for the file. Select ‘New Catalogue’ change the media control to ‘URL’

catalogues.html (17 KB)

You’re checking against a space not an empty string:


if ((mv=='URL') && (uv==" "))

Change it to


if ((mv=='URL') && (uv==""))

The above will not work if there is nothing but spaces in “Catalogue URL” field. You need to trim it while checking for user input, as I previously suggested:


if (($.trim(mv).toUpperCase() == "URL") && (!$.trim(uv).length)) {

The last code blocked worked. Thanks.