简体   繁体   中英

I have changed dropdown menu created from select and option tag to a Hoverable Dropdown menu. How should i pass values in it

I want to create a Hoverable Dropdown to sort my results by name or date dynamically. Previously i had a dropdown created by using and tag in which everything was working fine

My code was:

<select name="sort-by" id="sort">
      <option value="name" <?php if($orderby == 'name') echo "selected='selected'";?>>name</option>
      <option value="date" <?php if($orderby == 'date') echo "selected='selected'";?>>date</option>
    </select>

which i have changed to

    <div class="sort">
    <ul>
    <li><a href="#">name</a></li>
    <li><a href="#">date</a></li>
    </ul>
    </div>

which has converted to a Hoverable Dropdown. But now the problem is how would the code know that i have clicked on a link and hence pass a value $orderby which i am fetching on another page by using if(isset($_POST[order_by])) to use in a sql query ?

You can use JavaScript or jQuery to achieve that. First you create a hidden input field

<input type="hidden" id="order_by" name="order_by" value="" />

Then you use jQuery to update the value of the input field when the user clicks any option like this

$('ul li a').click(function(){
    newValue = $(this).html();
    $('input#order_by').val(newValue);
});

Note: Don't forget to include the jQuery library to your script. And also remember that your input field have to be within the form tag that you are submitting.

Here is a jsFiddle to display the result

Sorry @kanayo, but this isn't working or maybe i am not keeping it in correct way. Is this the right way to keep it

    <div class="sort">
    <script>
    $('ul li a').click(function(){
    newValue = $(this).html();
    $('input#order_by').val(newValue);
    });
    </script>
    </div>
    <ul>
    <input type="hidden" id="order_by" name="order_by" value=""/>
    <li><a href="#" >Name</a></li>
    <li><a href="#" >Date</a></li>
    </ul>
    </div>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM