redshot redshot - 4 months ago 15
CSS Question

How to check if url has no query string in jQuery?

I am editing a form in WordPress. I want my jquery script to execute when the url has no query string.

The url should not have a query string like this: http://127.0.0.1/mybetabizopi/login/?action=lostpassword

I only want my script to run when the url is like this or has no query string:
http://127.0.0.1/mybetabizopi/login/

This is my current script:

var j = jQuery.noConflict();
j(function() {


j('#login #user_login').attr('placeholder', 'Username');
j('#login #user_pass').attr('placeholder', 'Password');

j('#login #user_login').addClass('form-control');
j('#login #user_pass').addClass('form-control');

j('#login #loginform label').wrap( "<div class='input-group'></div>" );


j('#login .form-control').each(function() {
j(this).insertAfter(j(this).parent());
});

j('#loginform .input-group > label').remove();

j('<span class="input-group-addon" id="basic-addon1"><span class="glyphicon glyphicon-user" aria-hidden="true"></span></span>').insertBefore('#user_login');

j('<span class="input-group-addon" id="basic-addon1"><span class="glyphicon glyphicon-lock" aria-hidden="true"></span></span>').insertBefore('#user_pass');


});


Any help is appreciated.

Answer

You can use indexOf on the window.location.href to check if there is a ? character.

Note that you can name the jQuery instance provided to the document.ready handler as you need, so you can still use the $ variable within that function scope, even through the global $ no longer points to jQuery. Also, you can make your jQuery code more efficient by caching and re-using your selectors. Try this:

jQuery(function($) {
  if (window.location.href.indexOf('?') == -1) { // no querystring exists
    $('#login #user_login').attr('placeholder', 'Username').addClass('form-control');
    $('#login #user_pass').attr('placeholder', 'Password').addClass('form-control');

    $('#login #loginform label').wrap("<div class='input-group'></div>");

    $('#login .form-control').each(function() {
      $(this).insertAfter($(this).parent());
    });

    $('#loginform .input-group > label').remove();

    $('<span class="input-group-addon" id="basic-addon1"><span class="glyphicon glyphicon-user" aria-hidden="true"></span></span>').insertBefore('#user_login');
    $('<span class="input-group-addon" id="basic-addon1"><span class="glyphicon glyphicon-lock" aria-hidden="true"></span></span>').insertBefore('#user_pass');
  }
});
Comments