How to strike string in an html table using javascript? - javascript

Everytime i search for the word "Javascript" as specified in my code, I can't seem to get that word to be striked out in the table. I don't see why my input is not finding my word i'm searching through the ID.
<script type = "text/javascript">
<!--
function findWord(){
var str = document.getElementById("word").value;
var text = document.getElementById("search").innerHTML;
text = text.toLowerCase();
str = str.trim();
var n = str.indexOf(str.toLowerCase());
if( n != -1 )
{
text = text.replace( str , "<u>"+str+"</u>" );
}
text = text.toUpperCase();
document.getElementById("search").innerHTML = text;
}
<table>
<tr>
<td class="wordSearch" id="search">
QMGLUTKVRDIYKSA<br />
GKMTWRITELNXDYP <br />
MGETELEMENTBYID <br />
TTOLOWERCASEBRD <br />
NYRTOUPPERCASEI <br />
CJDYOFUNCTIONPN <br />
WEMSFZTJZJOMFTV <br />
BCBCCXSURWHILEE <br />
PPRETURNXATLJOU <br />
OIFYGTVFXHAAVIN <br />
FZRXADXETWINDOW <br />
DWNIZKHIVFXPIDL <br />
IFRSTRINGVCQQLP <br />
DOCUMENTULELSEN <br />
JYBOOLEANFAXAJH
</td>
</tr>
</table>
<form action="">
<p>
<label>Enter the word you've found and press Enter:
<input type="text" id="word" />
</label>
<input type="button" value="Enter" onclick= "findWord();" />
</p>
</form>
<div id="scoreArea"></div>

use a Jquery plug-in for filter and search in a table like jQuery.FilterTable
jQuery.FilterTable

this code may help you
function findWord(str) {
var tdText=document.getElementById("search").textContent.trim();
return tdText.search(str);
}

You've got a few errors here. The first one you'll find on debugging is:
Uncaught ReferenceError: str is not defined
This means you're trying to call the strike() function on a variable that hasn't been defined. You'll first need to get the search value and store it in a variable.
You're html has the input as id="word", so we need to get that from the html.
The command to do this is:
document.getElementById("word")
And we specifically want the value of what they typed in, which is:
var str = document.getElementById("word").value
Now if they type in "hello" or "javascript", it will be stored in the str variable. Problem number 1 fixed! Onto the second problem.
var inputVal = document.getElementById( "search" );
Remember, when you get an Element, it's returning the entire node, not the value stored within it. Before, we had to use the value command to get the actual text, but if you try that here, it won't work because search is a <td> element, not an input. I've never had to get text from a <td> before, so I had to look it up using the debugger tools. (If you're not familiar with them, here's a guide on how to use chrome's dev tools. As it turns out, for a td, what you want is either a innerText or innerHTML. Looking at what is stored in each, innerHTML is the one we would want to use as it gets just the entire html, which will be important later on (innerText doesn't get html elements like <br\>).
var wordSearch = document.getElementById("search").innerHTML;
I also, changed the name of the variable you were storing this in from inputVal to wordSearch as I feel like naming it inputVal is a bit confusing as I would presume by that name it was the value inputted by the user, not the value of the wordSearch document.
Ok, now we have the input from the user and the wordSearch, the next troublesome line is this one:
wordSearch.elements.value = words.indexOf( inputVal.value=result );
I believe you're trying to see if the value the user provided existed somewhere in the wordSearch, which would be the next logical step to take. So, there's a couple things here. Firstly, again you're referencing variables that haven't been defined, in this case: wordSearch. Based on your comment above, you were using wordSearch was from the class name. Unfortunately, in JavaScript, you can't directly call an element based on it's class like that. You would need to do something like:
document.getElementsByClassName("wordSearch")
However, I wouldn't recommend this method, because (as a canny observer may have guessed from the name) getElementsByClassName returns a list of elements, not a specific element (hence the name using "elements" not "element"). That's because multiple elements can have the same class name. That is why I used the id, instead of the class name to find it earlier. Only a single element can have a particular id.
Secondly, we have the following snippet of code:
words.indexOf( inputVal.value=result )
This is doing two things. First, it is assigning the results variable to inputVal.value because you have a single equals sign. If you wanted to compare them, you would need two (==) or three(===). The second thing it's doing is checking words for the first index of that value. indexOf return an integer indicating where it was found, and -1 if it wasn't found. Let's fix this.
var locationFound = wordSearch.indexOf(str.toUpperCase());
This will give us the location where the search value provided is found in the word search or -1 if it isn't found. Then you could do something like:
if (locationFound === -1) {
alert(str + " wasn't found");
} else {
// strike through code goes here
}
Now, we'd need to code up the strike through section.
var locationEnd = locationFound + str.length;
str = str.strike();
document.getElementById("search").innerHTML =
wordSearch.slice(0, locationFound) +
str +
wordSearch.slice(locationEnd);
Ok, this may look a bit confusing, but let's walk through it one line at a time.
var locationEnd = locationFound + str.length;
This is getting the end point of where the search value was found, which we'll need in a bit.
str = str.strike();
This is where we do the strike through, replacing the original text.
document.getElementById("search").innerHTML =
wordSearch.slice(0, locationFound) +
str +
wordSearch.slice(locationEnd);
What this is doing is removing the original word in the document, and replacing it with the struck through version. It's then setting that value to the innerHTML of the element with the id of search.
The final code:
<table>
<tr>
<td class="wordSearch" id="search">
QMGLUTKVRDIYKSA <br />
GKMTWRITELNXDYP <br />
MGETELEMENTBYID <br />
TTOLOWERCASEBRD <br />
NYRTOUPPERCASEI <br />
CJDYOFUNCTIONPN <br />
WEMSFZTJZJOMFTV <br />
BCBCCXSURWHILEE <br />
PPRETURNXATLJOU <br />
OIFYGTVFXHAAVIN <br />
FZRXADXETWINDOW <br />
DWNIZKHIVFXPIDL <br />
IFRSTRINGVCQQLP <br />
DOCUMENTULELSEN <br />
JYBOOLEANFAXAJH
</td>
</tr>
</table>
<form action="">
<p>
<label>Enter the word you've found and press Enter:
<input type="text" id="word" />
</label>
<input type="button" value="Enter" onclick= "findWord();" />
</p>
</form>
<div id="scoreArea"></div>
<script type="text/JavaScript">
var words = "Javascript";
function findWord() {
var str = document.getElementById("word").value.toUpperCase();
var wordSearch = document.getElementById("search").innerHTML;
var locationFound = wordSearch.indexOf(str);
if (locationFound === -1) {
alert(str + " wasn't found");
} else {
var locationEnd = locationFound + str.length;
str = str.strike();
document.getElementById("search").innerHTML =
wordSearch.slice(0, locationFound) +
str +
wordSearch.slice(locationEnd);
}
}
</script>

Related

how to get two word from a input field and make url based on another field

here i have two input field as like
$(document).ready(function() {
$("#business_name").keyup(function() {
var Text = $(this).val();
Text = Text.toLowerCase();
Text = Text.replace(/[^a-zA-Z0-9]+/g,'-');
$("#business_url").val(Text);
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" id="business_name" name="business_name" placeholder="Business Name" />
<br><br>
<input type="text" id="business_url" name="business_url" placeholder="Business URL" />
now I want if someone wrote : My Business Name on first input field then 2nd field it will be write mybusiness thats it but now it showed my-business-name i dont want this (I need only two word if it will take longer name then it only shows first two word thats it )
To get only the first two words you can split() the string in to an array by spaces and then use slice() to get the first two elements of the resulting array. Then you can join it back together before displaying in the input.
Also note I added trim() and a regex to replace multiple whitespace with a single one, otherwise it would affect how split() builds the array and could end up missing words.
jQuery($ => {
$("#business_name").on('input', e => {
var text = $(e.target).val().trim().replace(/\s+/, ' ').toLowerCase().split(' ').slice(0, 2).join('');
$("#business_url").val(text);
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" id="business_name" name="business_name" placeholder="Business Name" /><br /><br />
<input type="text" id="business_url" name="business_url" placeholder="Business URL" />
After replacing certain characters with ' ' count the number of ' ' in the string. If the count is 2 stop replacing or you can return from the function.
Look at the modified code below:
$(document).ready(function() {
var count = 0;
$("#business_name").keyup(function() {
var Text = $(this).val();
Text = Text.toLowerCase();
Text = Text.replace(/[^a-zA-Z0-9]+/g,' ');
count = (Text.split("-")).length - 1;
if (count == 2) {
return;
}
$("#business_url").val(Text);
});
});

Javascript find and replace function using while loop

I have this simple function to find and replace text in my textarea message. User will be able to type into the textarea and also be able to find and replace words from the text area they just entered. Currently I'm trying to use a while loop to replace multiple same words found in the textarea that the user keyed in. But every time I run it it seems to freeze the entire html page any idea why this is happening?
find and replace are textbox for user to key in the word they want to find and replace the user is able to key in multiple words to replace as well.
function findText() {
let find = document.getElementById('find').value;
let replace = document.getElementById('replace').value;
let message = document.getElementById('message').value;
var lmao = message.indexOf(find);
while (message.indexOf(find) != -1) {
document.getElementById("message").value = message.replace(find, replace);
}
}
Replace while loop with a replaceAll.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replaceAll
function findText() {
let find = document.getElementById('find').value;
let replace = document.getElementById('replace').value;
let message = document.getElementById('message').value;
var lmao = message.indexOf(find);
document.getElementById("message").value = message.replaceAll(find, replace);
}
<div>Find <input id="find" value="find" /></div>
<div>Replace <input id="replace" value="replace" /></div>
<div>
<textarea id="message" style="height: 100px">you can find and replace every words just by .replaceAll, example: find 1 find 2 find 3</textarea>
</div>
<div>
<button onclick="findText()">Submit</button>
</div>
Just a addition in other answer you can use g for global search and to replace where you find that word .
Read more about regex and //g here
Also you can let the search case-insensitivity using i along with g like this :
message.replace(/find/g, replace)
This way it will also replace Find finD FIND
And instead of using while you can use if loop
function findText() {
let find = document.getElementById('find').value;
let replace = document.getElementById('replace').value;
let message = document.getElementById('message').value;
var lmao = message.indexOf(find);
if(message.indexOf(find) != -1) {
document.getElementById("message").value = message.replace(/find/g, replace);
}
}
<div>Find <input id="find" value="find" /></div>
<div>Replace <input id="replace" value="replace" /></div>
<div>
<textarea id="message" style="height: 100px">you can find and replace every words just by .replaceAll, example: find 1 find 2 find 3</textarea>
</div>
<div>
<button onclick="findText()">Submit</button>
</div>
The issue is with your while condition. When all input fields are empty your while condition is true. So inside the while condition the input value keeps on updating to empty string again, which makes loop an infinite loop. Thats why your ui is breaking.
Issue Scenario
console.log(("").indexOf("") !== -1);
To fix this, you have to make sure that your find and replace values are not same. Or else, it will be an infinite loop again.
Fixed Solution
function findText() {
let find = document.getElementById('find').value;
let replace = document.getElementById('replace').value;
let message = document.getElementById('message');
while (find !== replace && message.value.indexOf(find) != -1) {
message.value = message.value.replace(find, replace);
}
}
<input type="text" id="find">
<input type="text" id="replace">
<textarea name="" id="message" cols="30" rows="10"></textarea>
<button onclick="findText()">Check</button>

Javascript Error: 'document' is not defined. [no-undef]

I'm an absolute beginner in JS.
following is the Javascript code:
var blank = document.getElementsByClassName("my-input");
var go = document.getElementById("go-button");
console.log(blank);
go.innerHTML = "Hello" + blank[0].value;
I use the IDE Brackets, whereas, I'm learning from a online course in which the teacher uses IDE Sublime text (he is not getting any errors)
I dont think IDE's make much of a difference, but mentioning.
What I want to achieve is:
A blank input box(with placeholder as "Your name") and a button (go button)
After typing the name, when we click the go button, text is displayed below the button as: Hello {name}
This works, but you need to be sure to add an event listener, so the code can grab the input value after it has been entered by the user:
var go = document.getElementById("go-button");
go.addEventListener("click", doFunc);
function doFunc() {
var blank = document.getElementsByClassName("my-input");
go.innerHTML = "Hello " + blank[0].value;
}
<input class="my-input" /><br />
<input class="my-input" /><br />
<input class="my-input" /><br />
<button id="go-button">Go</button>
If you want to display the text below the button you need an element to select (or inject it right after the button element).
var blank = document.getElementsByClassName("my-input");
var go = document.getElementById("go-button");
go.addEventListener('click', function() {
document.querySelector('.result').innerHTML = "Hello" + blank[0].value;
});
<input class="my-input" />
<button id="go-button">click me</button>
<p class="result"></p>

how to get the current values of an input on button click event

I have a bunch of div's that have the same functionality and I'm trying to write a function for them.
Basically they have a predetermined value and a user input value and those need to be multiplied.
I've looked through a bunch of other questions and this is the closest one I could find. Almost exactly, but none of those answers work.
Any help would be great. Thanks in advance!
<div>
<label>enter value for multiple here</label>
<input type="text" class="multiple" factor="foo1"/>
<button type="button" class="multiplyBtn">Click here to multiply these numbers</button>
<label>enter value for multiple here</label>
<input type="text" class="multiple" factor="foo2"/>
<button type="button" class="multiplyBtn">Click here to multiply these numbers</button>
</div>
Here's the JS:
$('.mulitplyBtn').click(function() {
var factor = $(this).closest('attr.factor').val();
var multiple = $(this)closest('.multiple').val();
answer = (factor * multiple);
};
This would work:
$('.multiplyBtn').click(function() { // you had multiplyBtn spelled wrong here
var cur = $('.multiplyBtn').index($(this)); // get index of clicked btn
var factor = $('.multiple').eq(cur).data('factor'); // get factor from matching input
var multiple = $('.multiple').eq(cur).val(); // get value from matching input
answer = (Number(factor) * Number(multiple)); // make sure both are numbers then multiply
alert(answer);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
<label>enter value for multiple here</label>
<input type="text" class="multiple" data-factor="4" />
<button type="button" class="multiplyBtn">Click here to multiply these numbers</button>
<br>
<label>enter value for multiple here</label>
<input type="text" class="multiple" data-factor="7" />
<button type="button" class="multiplyBtn">Click here to multiply these numbers</button>
</div>
In the first line you used " and ' try using the same quotes (I mean using ".multiplyBtn" or '.multiplyBtn' )
Second time, 3rd line you didn't use any quote when calling .multiple. So turn it in that format : var multiple = $(this)closest('.multiple').val()
let me know the result
You have at least two typos and are using the wrong jQuery function.
Typos:
$('.mulitplyBtn') should be $('.mulitplyBtn')
$(this)closest should be $(this).closest
Wrong function:
closest() searches the parents, and the only parent here is the DIV with no class. What you probably want is to use parent() to go up to the DIV, then find() to search the parent's children for a specific element:
$(this).parent().find('.multiple').val()
attr.factor does not work like this.
try it like this:
$('.multiplyBtn').click(function() {
var container = $(this).prev('.multiple'); //don't forget the "dot"
var multiple = container.val();
var factor = container.attr('factor'); //since it is the same container.
var answer = (factor * multiple); //what exactly are you tryin to multiply?
};

How to pass input variable from HTML Form

I'm trying to create a code which will take ask the user how many items of X, Y, etc and use Javascript to calculate the total owed and also to print a summary (receipt) of all items purchased. Sorry for noob question, trying to learn code without any formal training. Thanks for all of the help!
<html>
<head>
<title>Cost Calculator</title>
<script language="javascript" type="text/javascript">
function packageTotal(){
//Enter in prices here
var applePrice = 1;
var bookPrice = 2;
x = Number(document.calculator.books.value);
y = Number(document.calculator.apples.value);
var b = applePrice*x + bookPrice*y;
var p = applePrice*x + bookPrice*y + .5;
if (document.getElementById('noBag').checked) {
//Basic package is checked
document.calculator.total.value = b;
} else if (document.getElementById('yesBag').checked) {
//Pro package is checked
document.calculator.total.value = p;
}
//Want to add summary of purchase
//document.write("You want " + x " books and " y " apples.");
}
</head>
<body>
<!-- Opening a HTML Form. -->
<form name="calculator">
<!-- Here user will enter the number of Books and Apples -->
Enter Number of Books: <input type="text" name="books">
<br />
Enter the Number of Apples: <input type="text" name="apples">
<br />
<br />
<input type="radio" name="item" id="noBag" value="No" /> noBag
<input type="radio" name="item" id="yesBag" value="Yes" checked /> yesBag
<!-- Here result will be displayed. -->
<input type="button" value="Submit" onclick="packageTotal();">
Your Total Price is: <input type="text" name="total">
</form>
</body>
</html>
It's not clear from the question, but if this is the problem:
//Want to add summary of purchase
//document.write("You want " + x " books and " y " apples.");
then that would certainly break. document.write only adds to the current document when the document is still loading. If you call it afterwards it will implicitly open a new document to write to, destroying the current page. Generally document.write is a bad thing.
(also there are trivial syntax errors due to missing + concatenation operators)
If you want to write arbitrary text to the page, create a placeholder element:
<div id="message"></div>
and then set its text content:
function setTextContent(element, text) {
element.innerHTML = ''; // remove current content
element.appendChild(document.createTextNode(text));
}
var message = document.getElementById('message');
setTextContent(message, 'You want '+x+' books and '+y+' apples.');
(There is a textContent property on elements which you can also use instead of the function, but it's not supported on IE<9 which use innerText instead. Simply writing the message directly to innerHTML would also work in this case, but it is a bad habit because it leads to HTML-injection security holes when used with user input.)

Categories