简体   繁体   中英

NAV-LINK - test for user input before redirect?

I want to make sure that the user has made a selection from a dropdown before they are able to redirect to another page via a NAV-LINK in an <li> . Is it possible to test for the users selection first and prevent the redirection by keeping them on the page?

I'm able to fire the onclick event but I'm failing to stop the re-direction. Can any please help me?

<script>
function testInput(){ 
    alert("please make a selection..");
}
</script>

.

  <li class="nav-item" onclick="testInput()">
      <a class="nav-link" href="adduser.php">
          <span data-feather="Add User"></span>
          Add User
    </a>
</li>

You can do that by checking whether the dropdown has been changed or not;

document.getElementById('id_of_your_dropdown').addEventListener('change', () => {
     place your code here which redirects to the other page
})

Here is an example which prints some text to the console when some option is selected from the dropdown;

 document.getElementById('dd').addEventListener('change', () => { console.log('some value selected'); })
 <select id='dd'> <option>first</option> <option>second</option> <option>third</option> <option>forth</option> </select>

Do you want this?

<li class="nav-item">
    <a class="nav-link" href="adduser.php" onclick="testInput(event)">
      <span data-feather="Add User"></span>
      Add User
    </a>
  </li>

<select id = "drop-down">
    <option value ="none" disabled selected>Select an option</option>
    <option value = "1">1</option>
    <option value = "2">2</option>
    <option value = "3">3</option>
</select>

<script>
function testInput(e){
    if (document.getElementById("drop-down").value == "none") {
        e.preventDefault();
        alert("please make a selection..");
    }}
</script>

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