Andrus
Andrus

Reputation: 27943

How to mark item as selected according to query string parameter

Query string parameter _layout may contain values from 0 to 9 and may also missing.

If query string parameter is not present, item 0 must marked as selected. Bootstrap 3 dropdown menu item should marked as selected according to its value. I tried code below but item is not marked probably since onload event is not supported in span element.

How to fix ?

<ul class="dropdown-menu" role="menu">
  <li>
     <a onclick="LaadiVorm(0)">
       <span onload="if(getParameterByName('_layout')=0)  $(this).css('glyphicon glyphicon-ok')" aria-hidden="true"></span>
        Vorm  0
     </a>
  </li>
  <li>
     <a onclick="LaadiVorm(1)">
        <span onload="if(getParameterByName('_layout')=1)  $(this).css('glyphicon glyphicon-ok')" aria-hidden="true"></span>
        Vorm  1
     </a>
  </li>
</ul>

getParameterByName is from How can I get query string values in JavaScript? :

function getParameterByName(name) {
    name = name.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]");
    var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"),
        results = regex.exec(location.search);
    return results === null ? "" : decodeURIComponent(results[1].replace(/\+/g, " "));
}

jquery, bootstrap 3, ASP.NET MVC4 are used.

Also using this style does not keep empty space before unselectedted item. Result is:

v Vorm 0
Vorm 1

How to aling all captions so that result is

v Vorm 0
  Vorm 1

Using glyphicons are not required, v character in some font or something other understandable can used to mark current item.

Upvotes: 0

Views: 142

Answers (1)

squaleLis
squaleLis

Reputation: 6484

I will try to explain you everithing.

ISSUES

  • onload has no sense on SPANs (it is used on body or img).

  • $(selector).css(rules) is used to set CSS rules, not classes.

  • you can compare values with a double equals sign (i.e. a == b).

SOLUTIONS

I think you should remove the onload and add this Javascript:

$(document).ready(function(){
  var layoutParam = getParameterByName('_layout');
  $('.dropdown-menu li span').get(layoutParam).addClass('glyphicon glyphicon-ok');
});

For your alignment issue, you should add left padding with CSS. Maybe the :not() pseudo-selector could be useful:

.dropdown-menu li span:not(.glyphicon.glyphicon-ok){
    padding-left: 30px; //or a different dimension :)
}

A LITTLE TIP

I suggest you to add an id to your <ul> and use it in your selectors.

Upvotes: 1

Related Questions