skip to Main Content

I searched so much here but I didn’t find the solution to my problem, I found the solution with the select option field but I can’t use that.

So, I would like to click on one of these two links and open the link just on the button submit, I suppose it requires some jquery? Is anyone that could help?

<ul>
  <li class="link-a"><a href="https://google.com">LINK A</a></li>
  <li class="link-b"><a href="https://yahoo.com">LINK B</a></li>
</ul>

<button type="submit">Open clicked link</button>

2

Answers


  1. Am not sure why you would like to do that, but here is a way to achieve your desired result, no need to jQuery in this example,

    Approach:

    1. select all links and add click event on each one of them
    2. prevent the default behaviour on links click
    3. add a css class (or custom attribute) to label the clicked link
    4. remove the css class from other links to prevent confuses
    5. add click event to your submit button and go to the URL in the selected link
    const links = document.querySelectorAll('ul li a'),
          submitBtn = document.querySelector('button');
    
    links.forEach(link => {
        link.addEventListener('click', (e)=> {
            e.preventDefault();
            links.forEach(i => i != link ? i.classList.remove('clicked') : i.classList.add('clicked'));
        });
    });
    
    submitBtn.addEventListener('click', ()=> {
        location.href = document.querySelector('.clicked').href
    });
    .clicked {
      color: red;
    }
    <ul>
      <li class="link-a"><a href="https://google.com">LINK A</a></li>
      <li class="link-b"><a href="https://yahoo.com">LINK B</a></li>
    </ul>
    
    <button type="submit">Open clicked link</button>
    Login or Signup to reply.
  2. You can achieve your desired behavior like below:

    a) on click of link prevent its default behavior and then add a class to it.

    b) On click of a button get the href of the newly added class link and open it.

    $(document).ready(function() {
      $('a').click(function(e) {
        e.preventDefault();//prevent the default behaviour
        $('a').removeClass('clicked');//remove class first from all links
        $(this).addClass('clicked');//add class to currently clicked link
      });
      $('button').click(function() {
        window.location.href = $('a.clicked').attr('href');//get the current clicked link URL and open it
      });
    });
    .clicked {
      color: red;
    }
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <ul>
      <li class="link-a">
        <a href="https://google.com">LINK A</a>
      </li>
      <li class="link-b">
        <a href="https://yahoo.com">LINK B</a>
      </li>
    </ul>
    
    <button type="submit">Open clicked link</button>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search