Alexander Norton Alexander Norton - 5 months ago 13
Javascript Question

JavaScript keypressed only working when text field contains ';'

I want the textbox to disappear when I type in text and press enter. But it for some reason only disappears when I type in ';'. Any other characters seem to not work.



function enterPressed(e, field) {
if (e.keyCode == 13) {
var tb = document.getElementById("searchbox");
eval(tb.value);
if (field.value.length > 0) {
document.getElementById('searchdisappear').style.display='none';
}
}
}

<!DOCTYPE html>

<html lang = "en">

<head>
<link rel="stylesheet" type="text/css" href="./css/main.css">
<script src ="./js/search.js"></script>
</head>

<body>

<!-- SEARCH BAR AND BUTTON -->
<div id="searchdisappear" style="display:block;">
<input id="searchbox" class="search" maxlength="200" type="text" onkeypress="enterPressed(event, searchbox)" placeholder="Search.."/>
<p class="searchtext" onclick="buttonClicked(searchbox)"

</div>
</html>




Answer

Just remove unnecessary eval function.

function enterPressed(e, field) {
    if (e.keyCode == 13) {
        var tb = document.getElementById("searchbox");
		if (field.value.length > 0) {
	document.getElementById('searchdisappear').style.display='none';
		}
	}
}
<!DOCTYPE html>

<html lang = "en">

	<head>
		<link rel="stylesheet" type="text/css" href="./css/main.css">
		<script src ="./js/search.js"></script>
	</head>
	
	<body>

<!-- SEARCH BAR AND BUTTON -->
	<div id="searchdisappear" style="display:block;">
		<input id="searchbox" class="search" maxlength="200" type="text" onkeypress="enterPressed(event, searchbox)" placeholder="Search.."/>
		<p class="searchtext" onclick="buttonClicked(searchbox)"

	</div>
</html>