tbowden
tbowden

Reputation: 1058

IF OR Function in jQuery on a PHP site

Can anyone tell me what's wrong and how to fix this bit of code...

I am trying to bring up a message and not go to the next page, if the #send_country box has either nothing in it or says "Send From..." (as its the placeholder).

This is the bit of code I am having issues with:

if (country == '0' || country == "Send From...") {
    error = 1;
    jQuery('.msg').text("Please Select A Country.");
}

I think I have an issue with the OR function as it works without the || country == "Send From...".

<script>
    jQuery(document).ready(function(){
        jQuery('.submit').click(function() {

            var error = 0;
            var country = jQuery('#send_country').val();
            var countrys = jQuery('#delv_country').val();
            var idsa = jQuery('.size').val();

            if (country == '0' || country == "Send From...") {
                error = 1;
                jQuery('.msg').text("Select A Country.");
            }
            if (countrys == '0') {
                error = 1;
                jQuery('.msg').text("Select A Country.");
            }

            if (error) {
                return false;
            } else {
                return true;
            }

        });

    });
</script>

Upvotes: 1

Views: 133

Answers (1)

Zakaria Acharki
Zakaria Acharki

Reputation: 67505

if the #send_country box has either nothing in it or says "Send From..." (as its the placeholder).

The placeholder attribute is different than the value, you couldn't get the placeholder using .val(); instead you should use .prop('placeholder') :

var country_placeholder = jQuery('#send_country').prop('placeholder');

So the condition will be :

if (country == '0' || country_placeholder == "Send From...") {

But like this the condition will always return true since the placeholder will not change if you're filling the field, so i suggest just to check if the value is empty or '0' :

if (country == '0' || country == "") {

Hope this helps.

jQuery('.submit').click(function() {
  var error = 0;
  var country = jQuery('#send_country option:selected').val();

  if (country == '') {
    error = 1;
    jQuery('.msg').text("Select A Country.");
  }

  if (error) {
    console.log('EROOR');
  } else {
    console.log('SUBMIT');
  }

});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
  <select type="text" id='send_country'>
    <option value="" disabled selected>Send From...</option>
    <option value="1">1</option>
    <option value="2">2</option>
  </select>

  <button class='submit'>Submit</button>
</form>

<span class='msg'></span>

Upvotes: 1

Related Questions