Reputation: 69
I have an add user and a remove user button. I have functions that take whatever is in a text-input and add or remove it from a select. This is my js code:
var addedUsers = [];
function add(){
var form = document.getElementById('form')
var emailInput = form.elements.typer
let email = emailInput.value
emailInput.value = ""
var select = document.getElementById('users')
var option = document.createElement("option")
option.text = email
emailInput.focus()
if (addedUsers.indexOf(email) == -1){
addedUsers.push(email)
select.add(option)
} else {
alert("This user is already one of your recipients!");
}
}
function rem(){
var form = document.getElementById('form')
var emailInput = form.elements.typer
let email = emailInput.value
emailInput.value = ""
var select = document.getElementById('users')
var options = select.options
emailInput.focus()
if (addedUsers.indexOf(email) != -1){
for (var i = 2; i < options.length; i++){
if(email === options[i].innerHTML){
select.remove(i)
addedUsers.splice(email, 1)
break
}
}
} else {
alert("This user is not already one of your recipients!")
}
}
<form id="form">
<div class="recipients">
<input type="text" class="typer" name="typer">
<br><br>
<button onclick="add()" type="button" class="ar">Add User</button>
<button onclick="rem()" type="button" class="ur">Remove User</button>
<br><br><br>
<select id="users" name="users" class="userlist" size="24">
<option class="listhead">__________*Recipents*__________</option>
<option class="listhead">-------------------------------</option>
</select>
</div>
<div class="content">
<button onclick="mail()" class="send">Send</button>
<br><br>
<textarea type:"content" name="content" class="typec" cols="113" rows="12"></textarea>
</div>
</form>
I noticed that I can add nothing at all and remove nothing at all, until an alert comes up. How can I prevent this? Also, if I hit one of the added options in the select, how do I make it show up in the text-input? Thanks!
Upvotes: 2
Views: 85
Reputation: 76464
As Chocolord correctly pointed out, you need to use valid methods, like appendChild
and removeChild
, respectively, instead of add
and remove
, respectively.
The reason why your program mistakenly thought the users were correctly added was that you actually added them to the array before the actual DOM operation:
addedUsers.push(email)
select.add(option)
respectively. Make sure you you invert the operation to
select.add(option)
addedUsers.push(email)
Upvotes: 0
Reputation: 493
I would say that you don't use the good methods to add and remove options to the select.
You should use appendChild
to add the option to the select and removeChild
to remove an option to the select.
example:
// in the add() function
select.appendChild(option)
// in the rem() function
select.removeChild(options[i])
Documentation:
Upvotes: 1