Friday, May 10, 2024
 Popular · Latest · Hot · Upcoming
165
rated 0 times [  168] [ 3]  / answers: 1 / hits: 107896  / 10 Years ago, sat, july 12, 2014, 12:00:00

I am making a piece of code for a website that will have a list of names in an array and pick a random name, I want to add a feature that will let the user add or delete a name from the array. I have all of these features but when deleting a name, the user has to type the name to match the Case in the array. I tried to make the so it would be Case-Insensitive, what am I doing wrong?



<html>
<!--Other code uneeded for this question-->
<p id=canidates></p>
<body>
<input type=text id=delname /><button onclick=delName()>Remove Name from List</button>
<script>

//Array of names

var names = [];

//Other code uneeded for this question

//List of Canidates
document.getElementById('canidates').innerHTML =
<strong>List of Canidates:</strong> + names.join( | );

//Other code uneeded for this question

//Remove name from Array

function delName() {
var dnameVal = document.getElementById('delname').value;
var pos = names.indexOf(dnameVal);
var namepos = names[pos]
var posstr = namepos.toUpperCase();
var dup = dnameVal.toUpperCase();
if(dup != posstr) {
alert(Not a valid name);
}
else {
names.splice(pos, 1);
document.getElementById('canidates').innerHTML =
<strong>List of Canidates:</strong> + names.join( | );
}
}
</script>
</body>
</html>

More From » javascript

 Answers
19

Easy way would be to have a temporary array that contains all the names in uppercase. Then you can compare the user input. So your code could become somthing like this:



function delName() {
var dnameVal = document.getElementById('delname').value;
var upperCaseNames = names.map(function(value) {
return value.toUpperCase();
});
var pos = upperCaseNames.indexOf(dnameVal.toUpperCase());

if(pos === -1) {
alert(Not a valid name);
}
else {
names.splice(pos, 1);
document.getElementById('canidates').innerHTML =
<strong>List of Canidates:</strong> + names.join( | );
}
}


Hope this helps solve your problem.


[#70223] Thursday, July 10, 2014, 10 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
theron

Total Points: 168
Total Questions: 93
Total Answers: 94

Location: South Georgia
Member since Fri, Nov 13, 2020
4 Years ago
;