Home > Software design >  how to call an alert after an option is clicked
how to call an alert after an option is clicked

Time:06-24

I am trying to make a username, ID and password linking form but i need to make sure that the program recognises that a username has been selected. This is what I have done;

var usernameBox = document.getElementsByName("uop");
    usernameBox.onclick = function(){
        if (usernameBox.options[usernameBox.selectedIndex].value == false){
        alert("Please choose your username");
    }
    }

this does not work for me and I am a beginner to javascript so I'm not very familiar with a lot of the concepts but that's what learning is for right.

CodePudding user response:

You could update a variable everytime the 'select' element is changed, then show the alert. You can use the username variable wherever you would like. Here is how you could do this...

var usernameBox = document.getElementById("uop");
let username = usernameBox.value;

usernameBox.onchange = (e) => {
  username = e.target.value;
  alert(username);
}

CodePudding user response:

You could add the onchange attribute in the HTML itself, which calls a function in the JavaScript. Heres a example

<input type="text" onchange="inputOnChange()" id="input-username"/>
<script> 
function inputOnChange() {
   let usernameinput = document.getElementById("input-username");
   let username = usernameinput.value;
   // do whatever u want with the username now
   console.log(username);
}
</script>

  • Related