I'm a fresher in JS, so I have the following task: Some text is given on a page and when a user wants to find a set of characters or string by adding this string in a window and then clicking "search", this string should be marked as bold in our text each time it is met. Looking through my code I'm almost sure that the function is working, but after the function has finished, the bold strings just blink for a moment and the text returns to its initial status.
Please help me to find out my mistake. Here's the code.
function look(a) {
var str = document.getElementById("original").innerHTML;
var len = a.text.value.length;
var begin = str.indexOf(a.text.value);
var final = str;
if (begin == -1) {
alert("No matches");
return false;
}
if (begin > -1) {
var count = 0;
final = str.substring(count, begin) + "<b>" + a.text.value + "</b>" + str.substring(begin + len + 1, str.length);
while (begin != -1) {
begin = str.indexOf(a.text.value, begin + len);
if (begin == -1) break;
final = final.substring(count, begin) + "<b>" + a.text.value + "</b>" + str.substring(begin + len + 1, str.length);
}
document.getElementById("original").innerHTML = final;
return true;
}
}
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
<span id="original" type="text">Some given text</span>
<br/>
<form name="search" onsubmit="return look(this)">
<p>Enter text to search<input type="text" name="text"></p>
<p><input type="submit" value="search"></p>
</form>
</body>
Returning true
on successfully finding the text span makes the form to be submitted. You need to return false
to make the form invalidate the submission. This is the updated code, I have changed the return statement out of the if-else
block and returned false
either way. Another way is to make submit button as input[type='button']
and register an onclick
event listener to it.
function look(a)
{
var str=document.getElementById("original").innerHTML;
var len=a.text.value.length;
var begin=str.indexOf(a.text.value);
var final=str;
if (begin==-1){
alert("No matches");
}
if (begin>-1){
var count=0;
final=str.substring(count,begin)+"<b>"+a.text.value+"</b>"+str.substring(begin+len+1, str.length);
while(begin!=-1){
begin=str.indexOf(a.text.value,begin+len);
if(begin==-1) break;
final=final.substring(count, begin)+"<b>"+a.text.value+"</b>"+str.substring(begin+len+1, str.length);
}
document.getElementById("original").innerHTML=final;
}
return false;
}