I tried to run the code but nothing is showing on my page.
i'm not sure where the mistakes are. I tried typing javaScript code to find the longest word in a html form/input,then showing the output on the html body.
function fnLongestWord(string){
var words = str.split(" ");
console.log(words);
var findlongest=document.forms["Longestword"],
var longest = "";
for(let i=0; i < findlongest.length; i++){
console.log(findlongest[i]);
}
if ( longest.length > findlongest.length) findlongest = longest;
}
console.log(longest);
document.getElementById("showResult1") = "Number of vowels: "+ longest;
<div id="LongWord" class="Tab">
<form id="Longestword">
<label>Enter text: <input name="text "></label>
<button type="button" onclick="fnLongestWord()"> Find longest word</button>
</form>
<!--here the output show-->
<p id="showResult1"></p>
</div>
Errors
;Here you are calling fnLongestWord but not passing any argument while fnLongestWord expects a value
var words = str.split(" "); str is no where defined inside the function
You need to put this line document.getElementById("showResult1") = "Number of vowels: "+ longest; inside the function and this is an invalid assingment. You need to use innerHTML and assign the value to it
function fnLongestWord(string) {
var str = document.getElementById('input').value || string
var words = str.split(" ");
var longest = words.sort((a, b) => {
return b.length - a.length;
})
document.getElementById("showResult1").innerHTML = "Number of vowels: " + longest[0];
}
<div id="LongWord" class="Tab">
<form id="Longestword">
<label>Enter text: <input id = 'input' name="text "></label>
<button type="button" onclick="fnLongestWord()"> Find longest word</button>
</form>
<!--here the output show-->
<p id="showResult1"></p>
</div>
You've got a few mistakes in your code that need fixing.
Firstly, you call fnLongestWord() when you click the button, thus you are not passing in the string from the form. You need to get the string from the form by using:
var str = document.getElementById('longestWord').value;
This will get the value (the text) of the element with the id longestWord. This will get the text from the textbox (as I've given it the id="longestWord")
Now you want to loop over your array of words. You can use words.length in the for loop to do this.
Next, you want to fix your if statement. Currently your syntax and logic are incorrect. Instead, you need to make it if(longest.length < words[i].length) longest = words[i]; which reads that if the longest word currently found is smaller than our current word, set the new longest word equal to the current word (word[i]).
Lastly, you're not adding the answer to the page correctly. Instead, you should do:
document.getElementById("showResult1").textContent += "Longest word is: " + longest;
To set the longest word into the showResult1 paragraph.
See working example below:
function fnLongestWord() {
var str = document.getElementById('longestWord').value;
var words = str.split(" ");
var longest = "";
for (let i = 0; i < words.length; i++) {
if (longest.length < words[i].length) longest = words[i];
}
document.getElementById("showResult1").textContent += "Longest word is: " + longest;
}
<div id="LongWord" class="Tab">
<form id="Longestword">
<label>Enter text: <input id="longestWord" name="text "></label>
<button type="button" onclick="fnLongestWord()"> Find longest word</button>
</form>
<!--here the output show-->
<p id="showResult1"></p>
</div>
Related
Here is my code but I can't display the other numbers because I have indexed [0] and I don't know how I can display the other numbers.
Example string: "Hello, you can contact me at 0744224422 or 0192234422."
Result code : "Hello, you can contact me at <span>0744224422</span> or <span>0744224422</span>."
On this example: my code will replace "0192234422" by 0744224422 "which is logical" but I would like it to display 0192234422... How can I do it ?
Thanks
let selector = document.querySelectorAll('.message > div > .chat');
for (let index = 0; index < selector.length; index++) {
if (selector[index].innerText) {
let text = selector[index].innerText;
const regex = /(\d[\s-]?)?[\(\[\s-]{0,2}?\d{3}[\)\]\s-]{0,2}?\d{3}[\s-]?\d{4}/gim;
if (text.match(regex).length) {
const newTexte = ` <span>${text.match(regex)[0].trim()}</span> `;
selector[index].innerHTML = text.replace(regex, newTexte);
};
}
}
If you use the $ replacement character of the replace function, it will put the right text in there. Rather than trim just put parentheses around the non-whitespace portion of your regular expression and effectively let the capturing group become the trim operation.
let selector = document.querySelectorAll('.message > div > .chat');
for (let index = 0; index < selector.length; index++) {
if (selector[index].innerText) {
let text = selector[index].innerText;
const regex = /(\d[\s-]?)?([\(\[\s-]{0,2}?\d{3}[\)\]\s-]{0,2}?\d{3}[\s-]?\d{4})/gim;
if (text.match(regex).length) {
const newTexte = ` <span class="red">$2</span> `;
selector[index].innerHTML = text.replace(regex, newTexte);
};
}
}
.red {
background: yellow
}
<div class="message">
<div>
<div class="chat">Hello, you can contact me at 0744224422 or 0192234422.</div>
</div>
</div>
I'm going to try to call attention to the difference in the regular expressions below: (because I added one set of parentheses)
/(\d[\s-]?)?[\(\[\s-]{0,2}?\d{3}[\)\]\s-]{0,2}?\d{3}[\s-]?\d{4}/gim
( )
/(\d[\s-]?)?([\(\[\s-]{0,2}?\d{3}[\)\]\s-]{0,2}?\d{3}[\s-]?\d{4})/gim;
Do you have two separate instances of the selector? If not then the selector.length is only 1 which is why only the first number is shown. You can edit the html to have more than one instance of the selector (and style with display: inline so that it doesn't line break onto a new line) EX:
let selector = document.querySelectorAll('.message > div > .chat');
for (let index = 0; index < selector.length; index++) {
if (selector[index].innerText) {
let text = selector[index].innerText;
const regex = /(\d[\s-]?)?[\(\[\s-]{0,2}?\d{3}[\)\]\s-]{0,2}?\d{3}[\s-]?\d{4}/gim;
if (text.match(regex).length) {
const newTexte = ` <span>${text.match(regex)[0].trim()}</span> `;
selector[index].innerHTML = text.replace(regex, newTexte);
};
}
}
<div class="message">
<div>
<p class="chat" style="display:inline">
Hello, you can contact me at 0744224422 or </p>
<p class="chat" style="display:inline">0192234422</p>
<!-- add more numbers as needed in another <p class="chat" style="display:inline" ></p>-->
</div>
</div>
Thank you for your answers, but I would just like to add a <span></span> (or more) when a phone number is written in the string..
I created a output document , in each Textarea and Textbox there is a line break i want to know how to remove it
Line break are usually "\n". So if you want to output or show it in a "div" tag, then you go with this code:
function formatData(){
var inpData = document.getElementById("textInput").value.split("\n");
var outputData = "";
for(var i = 0;i < inpData.length; i++){
outputData += inpData[i];
}
document.getElementById("textOutput").innerHTML = outputData;
}
<textarea rows="4" id="textInput"></textarea>
<button onclick="formatData()">Display Formatted Data</button>
<div id="textOutput"></div>
I am using a regex replace to <mark></mark> input text. The problem I am running into is that it takes all text from a holder div and replaces it into a variable and adds the mark tags. Then places it back into the div holder. When I do this, if I type in "<p>", it highlights the actual <p> and outputs it back into the div.
Is there anyway to get around this? Here is my marking code:
function Search() {
var Notes = document.getElementById("NoteHolder").innerHTML;
var i = document.getElementById("Bar").value;
var inputReOne = $.trim(i);
var inp = inputReOne.replace(".", "\.").replace("<", "").replace(">", "").replace(
"/", "").replace(/\\/, "");
document.getElementById("Bar").value = inp;
if ($.trim(inp) !== '') {
var InpComp = inp.toUpperCase();
var Ind = tags.indexOf(InpComp);
if (Ind === -1) {
var inpReg = new RegExp(inp, "im");
var WordCheck = Notes.match(inpReg);
if (WordCheck !== null) {
tags.push(InpComp);
var SearchReq = new RegExp("(" + inp + ")", "gim");
var after = Notes.replace(SearchReq, "<mark class=" +
ColorOptionReady + ">$1</mark>");
document.getElementById("NoteHolder").innerHTML = after;
}
HTML:
<body>
<div>
<p id="form">
<input class="SearchInp" autocomplete="off" id="Bar" name="Input" type="text" placeholder="Search for word or phrase">
<input class="SearchInp" type="submit" id="sea" onClick="Search ()" value="Search"> <div id="NoteHolder">
</p>
<p class="NoteOp" id="NoteOne">This is a test paragraph uses to TeSt filters.</p>
<p class="NoteOp" id="NoteTwo">Random words, I need to see if it will mess up mark</p>
</div>
<script src="Test.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"> </script>
</body>
Rather than searching and replacing in the #NoteHolder element, why not loop through each .NoteOp and replace in there?
function search() {
var notes = document.getElementsByClassName("NoteOp");
var s = document.getElementById("Bar").value.trim();
for (var i = 0; i < notes.length; i++) {
var n = notes[i];
n.innerHTML = n.textContent.replace(new RegExp("(" + s + ")", "gim"), "<mark>$1</mark>");
}
}
<input class="SearchInp" autocomplete="off" id="Bar" name="Input" type="text" placeholder="Search for word or phrase">
<input class="SearchInp" type="submit" id="sea" onClick="search()" value="Search">
<div id="NoteHolder">
<p class="NoteOp" id="NoteOne">This is a test paragraph uses to TeSt filters.</p>
<p class="NoteOp" id="NoteTwo">Random words, I need to see if it will mess up mark</p>
</div>
Note: Storing the contents of each .NoteOp in an object, working with the text in there and simply setting the content of each .NoteOp after every search would be easier and cleaner.
I have List<String> from Spring MVC which i want to split, slice and print on browser. The problem is that i need to enter a start and end argument of slice() method as a variable from text-field. This is my code, but it doesn't work. Can someone helps me with that? This is my code:
<body>
<form>First value:
<br/>
<input type="text" id="firstvalue" />Last value:
<br/>
<input type="text" id="lastvalue" />
<button onclick="myFunction()">Press</button>
<p id="demos"></p>
</form>
<script>
function myFunction() {
var str = "${first}";
var arr = str.split(",");
var first = document.getElementById('firstvalue');
var second = document.getElementById('lastvalue');
document.getElementById("demos").innerHTML = arr.slice('first', 'second');
}
</script>
</body>
Thank you in advance!
you got some issues in your code.
if ${first} is List<String>, then you need to convert it to a concatenated single comma separated String. Because by ${first} you are just printing list object.
slice expects index which is number, you are passing String
You are not doing .value after document.getElementById
You are not passing the user input variables first and second to slice, Instead you are passing hardcoded strings 'first' and 'second'.
Below is the fixed code
HTML
<form>First value:
<br/>
<input type="text" id="firstvalue" />Last value:
<br/>
<input type="text" id="lastvalue" />
<button onclick="myFunction(event)">Press</button>
<p id="demos"></p>
</form>
JS
var myFunction = function (e) {
var str = "${first}" // assuming this contains string like "1,2,3,4,5,6,7,8,9,10"; and not the List obect
var arr = str.split(",");
var first = document.getElementById('firstvalue').value;
var second = document.getElementById('lastvalue').value;
document.getElementById("demos").innerHTML = arr.slice(parseInt(first, 10), parseInt(second, 10)).toString();
e.preventDefault();
};
What do we want to achieve?
We have two input textfields: one holding a start value and one holding an end value. On a click we want to create a range from the start to the end value and output it into a container.
Solution
The solution is more simple than expected and we do not require split, slice and part. Also we do not really require a predefined list holding all values.
Example
<html>
<head>
<script>
function evalRange(){
var tS = parseInt(document.querySelector('#inFrom').value); //Our start value;
var tE = parseInt(document.querySelector('#inTo').value); //Our end value;
var tR = document.querySelector('#demos'); //Our output div
if (tE >= tS){
//We are using the Array.apply prototype to create a range
var tL = Array.apply(null, Array(tE - tS + 1)).map(function (a, i){return tS + i});
//We output the range into the demos div
tR.innerHTML = tL.join(',')
}
else tR.innerHTML = 'To has to be higher than from';
//Returning the range list
return tL
}
</script>
</head>
<body>
<input type = 'text' id = 'inFrom' value = '10' />
<input type = 'text' id = 'inTo' value = '20' />
<b onclick = 'evalRange()'>Range</b>
<div id = 'demos'></div>
</body>
</html>
And here is a fiddle for it: https://jsfiddle.net/91v3jg66/
I need to do the following (I'm a beginner in programming so please excuse me for my ignorance): I have to ask the user for three different pieces of information on three different text boxes on a form. Then the user has a button called "enter"and when he clicks on it the texts he entered on the three fields should be stored on three different arrays, at this stage I also want to see the user's input to check data is actually being stored in the array. I have beem trying unsuccessfully to get the application to store or show the data on just one of the arrays. I have 2 files: film.html and functions.js. Here's the code. Any help will be greatly appreciated!
<html>
<head>
<title>Film info</title>
<script src="jQuery.js" type="text/javascript"></script>
<script src="functions.js" type="text/javascript"></script>
</head>
<body>
<div id="form">
<h1><b>Please enter data</b></h1>
<hr size="3"/>
<br>
<label for="title">Title</label> <input id="title" type="text" >
<br>
<label for="name">Actor</label><input id="name" type="text">
<br>
<label for="tickets">tickets</label><input id="tickets" type="text">
<br>
<br>
<input type="button" value="Save" onclick="insert(this.form.title.value)">
<input type="button" value="Show data" onclick="show()"> <br>
<h2><b>Data:</b></h2>
<hr>
</div>
<div id= "display">
</div>
</body>
</html>
var title=new Array();
var name=new Array();
var tickets=new Array();
function insert(val){
title[title.length]=val;
}
function show() {
var string="<b>All Elements of the Array :</b><br>";
for(i = 0; i < title.length; i++) {
string =string+title[i]+"<br>";
}
if(title.length > 0)
document.getElementById('myDiv').innerHTML = string;
}
You're not actually going out after the values. You would need to gather them like this:
var title = document.getElementById("title").value;
var name = document.getElementById("name").value;
var tickets = document.getElementById("tickets").value;
You could put all of these in one array:
var myArray = [ title, name, tickets ];
Or many arrays:
var titleArr = [ title ];
var nameArr = [ name ];
var ticketsArr = [ tickets ];
Or, if the arrays already exist, you can use their .push() method to push new values onto it:
var titleArr = [];
function addTitle ( title ) {
titleArr.push( title );
console.log( "Titles: " + titleArr.join(", ") );
}
Your save button doesn't work because you refer to this.form, however you don't have a form on the page. In order for this to work you would need to have <form> tags wrapping your fields:
I've made several corrections, and placed the changes on jsbin: http://jsbin.com/ufanep/2/edit
The new form follows:
<form>
<h1>Please enter data</h1>
<input id="title" type="text" />
<input id="name" type="text" />
<input id="tickets" type="text" />
<input type="button" value="Save" onclick="insert()" />
<input type="button" value="Show data" onclick="show()" />
</form>
<div id="display"></div>
There is still some room for improvement, such as removing the onclick attributes (those bindings should be done via JavaScript, but that's beyond the scope of this question).
I've also made some changes to your JavaScript. I start by creating three empty arrays:
var titles = [];
var names = [];
var tickets = [];
Now that we have these, we'll need references to our input fields.
var titleInput = document.getElementById("title");
var nameInput = document.getElementById("name");
var ticketInput = document.getElementById("tickets");
I'm also getting a reference to our message display box.
var messageBox = document.getElementById("display");
The insert() function uses the references to each input field to get their value. It then uses the push() method on the respective arrays to put the current value into the array.
Once it's done, it cals the clearAndShow() function which is responsible for clearing these fields (making them ready for the next round of input), and showing the combined results of the three arrays.
function insert ( ) {
titles.push( titleInput.value );
names.push( nameInput.value );
tickets.push( ticketInput.value );
clearAndShow();
}
This function, as previously stated, starts by setting the .value property of each input to an empty string. It then clears out the .innerHTML of our message box. Lastly, it calls the join() method on all of our arrays to convert their values into a comma-separated list of values. This resulting string is then passed into the message box.
function clearAndShow () {
titleInput.value = "";
nameInput.value = "";
ticketInput.value = "";
messageBox.innerHTML = "";
messageBox.innerHTML += "Titles: " + titles.join(", ") + "<br/>";
messageBox.innerHTML += "Names: " + names.join(", ") + "<br/>";
messageBox.innerHTML += "Tickets: " + tickets.join(", ");
}
The final result can be used online at http://jsbin.com/ufanep/2/edit
You have at least these 3 issues:
you are not getting the element's value properly
The div that you are trying to use to display whether the values have been saved or not has id display yet in your javascript you attempt to get element myDiv which is not even defined in your markup.
Never name variables with reserved keywords in javascript. using "string" as a variable name is NOT a good thing to do on most of the languages I can think of. I renamed your string variable to "content" instead. See below.
You can save all three values at once by doing:
var title=new Array();
var names=new Array();//renamed to names -added an S-
//to avoid conflicts with the input named "name"
var tickets=new Array();
function insert(){
var titleValue = document.getElementById('title').value;
var actorValue = document.getElementById('name').value;
var ticketsValue = document.getElementById('tickets').value;
title[title.length]=titleValue;
names[names.length]=actorValue;
tickets[tickets.length]=ticketsValue;
}
And then change the show function to:
function show() {
var content="<b>All Elements of the Arrays :</b><br>";
for(var i = 0; i < title.length; i++) {
content +=title[i]+"<br>";
}
for(var i = 0; i < names.length; i++) {
content +=names[i]+"<br>";
}
for(var i = 0; i < tickets.length; i++) {
content +=tickets[i]+"<br>";
}
document.getElementById('display').innerHTML = content; //note that I changed
//to 'display' because that's
//what you have in your markup
}
Here's a jsfiddle for you to play around.