Krishna Krishna - 21 days ago 5
Javascript Question

javascript Map object delete not working

This is not the actual scenario but I have to use the check function as follows with conjunction with map object.

<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<form action="" method="post" onsubmit="return check()">
<input type="text" name="name" id="one" oninput="change(this)" />
<input type="text" name="password" id="two" oninput="change(this)" />
<input type="submit" name="submit" value="submit" />
</form>
<script type="text/javascript">
var map = new Map();
function change(obj){
var id = obj.id;
if(obj.value != ""){
map.set(id,obj.value);
console.log("added key "+obj.id+" value "+obj.value+" size "+map.size);
}else{
map.delete[id];
console.log("removed key "+obj.id+" value "+obj.value+" size "+map.size);
}
}

function check(){
if(map.size != 2){
alert("enter all values");
return false;
}
}
</script>
</body>
</html>


The action in form tag is intentionally empty here

With the above code, when I enter values in any one text box, the value is added to the map but when I clear it again, the value pair is not deleting from the map. Size of the map is not decreasing on deleting it (or may be the object is not getting deleted). So once I clear the fields after entering something, the size of the map remains will be 2 and submit happens without any alert. Help me. The logic, I have to use it somewhere else to make it work. Thanks in advance.

Answer

Map.prototype.delete() is a function which needs to be called by passing its parameters in round brackets (), not square brackets []:

map.delete(id);