I am trying to get something that looks through a div with an id of 'Holder' and searches for a string. Preferably this string would be case-insensitive. This string would be have an input connected (variable is 'Terms'). Once the code has found all the paragraphs that have the string, add a class to them called 'Found'. I do not have that much knowledge with Jquery (just the very basics) so if anyone could help me, that would be fantastic!
Code so far:
<!DOCTYPE html>
</html>
<body>
<p id="header">Searcher</p>
<hr>
<p id="form">
<input autocomplete="off" id="Bar" name="Input" type="text" placeholder="Search for word or phrase">
<button type="button" id="sea" onClick="Search ()">Search</button>
<br>
</p>
<div id="Holder">
<p id="Note">This is a test paragraph uses to test.</p>
<p id="Note">For jquery. I want to search for this paragraph using "for jquery".</p>
</div>
<script> src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
<script src="test.js">
</script>
</body>
Here is a working code sample. You should read the comments because I made a few changes to how you were doing things in order to improve code quality. There is still more that could be done (like using a real form), but this should get you pointed in the right direction. If my comments aren't clear, feel free to ask why I made the changes that I did and I'll try to provide a better explanation.
<html>
<style>
.match-found {
background: yellow;
}
</style>
<body>
<p id="header">Searcher</p>
<hr>
<p id="form">
<!--
You should use a real form and attach to the submit handler, but I
feel the need to leave something as an exercise for the reader
-->
<input autocomplete="off" id="bar" name="input" type="text" placeholder="Search for word or phrase">
<button type="button" class="search-text" data-search-target="#holder">Search</button>
<br>
</p>
<div id="holder">
<p id="note">This is a test paragraph uses to test.</p>
<p id="note">For jquery. I want to search for this paragraph using "for jquery".</p>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
<script>
function search(searchTarget, term) {
// lowercase terms because uppercase should be reserved for constructors
// also made it singular because we're looking for an exact match, not
// a list several separate terms.
// (if I understand your problem description correctly)
term = term.toLowerCase();
// If you're searching for simple terms, regex would be better,
// but since I'm not sure how you'll actually be using this,
// lowercasing the string and searching for a containing string will
// provide more consistent results because we won't have to worry about
// escaping special characters and the like.
$(searchTarget).find('p').each(function() {
var searchText = $(this).text().toLowerCase();
if (searchText.indexOf(term) !== -1) $(this).addClass('match-found');
// match-found is more descriptive that 'found'.
// Also avoiding caps again because capitilization has specific meaning
});
}
// A better way to attach event listeners
$(document).ready(function() {
$('.search-text').click(function() {
var searchTarget = $(this).attr('data-search-target');
var searchText = $('#bar').val();
search(searchTarget, searchText);
});
});
</script>
</body>
</html>
$("#sea").on("click", function() {
$("#Holder > p:contains('" + $("#Bar").val() + "')").addClass("found");
});
The above code attaches a click event to the search button #sea. Using the :contains() selector it searches all <p> tags which are direct children of #Holder for the value of #Bar and adds the class "found".
https://jsfiddle.net/mz0ge2w8/1/
Related
I need to display boilerplate text on a web page and give visitors the ability to update the text by submitting a value in a text box. I have two issues:
I can only use the text box value once but I want to use it multiple. I understand this is due to using document.getElementById. I should be using document.getElementByClassName however I am having troubles making this work.
I would like to include a default value within the boilerplate text that would then be replaced by the value from the text box. For example "your company" would be replaced with "XYZ Company" (or whatever the user submits in the text box).
I have the following code:
<!DOCTYPE html>
<html>
<body style="text-align:center;">
Company Name:
<input type="text"
id="myText"
value="">
<button type="button"
onclick="myFunction()">
Submit
</button>
<p>I would like to use the name, <strong><span id="demo"></span></strong>, multiple times in this text. I'd like to use it <strong><span id="demo"></span></strong> and again <strong><span id="demo"></span></strong>.</p>
<script>
// Here the value is stored in new variable x
function myFunction() {
var x =
document.getElementById("myText").value;
document.getElementById(
"demo").innerHTML = x;
}
</script>
</body>
</html>
What am I missing? Any direction is appreciated. Thanks in advance.
First of all, you should be using the classes, since ids are meant to be unique. Second, when calling getElementById() (or even querySelector()), you are only getting the first element that matches the query. You should give all of the the elements a shared class, select them all with querySelectorAll(), then loop over them all, as in the following:
<!DOCTYPE html>
<html>
<body style="text-align:center;">
Company Name:
<input type="text"
id="myText"
value="">
<button type="button"
onclick="myFunction()">
Submit
</button>
<p>I would like to use the name, <strong><span class="demo"></span></strong>, multiple times in this text. I'd like to use it <strong><span class="demo"></span></strong> and again <strong><span class="demo"></span></strong>.</p>
<script>
// Here the value is stored in new variable x
function myFunction() {
var x =
document.getElementById("myText").value;
// select all elements with class ('.') of 'demo'
const allDemoElements = document.querySelectorAll(".demo");
// loop over each element, and alter innerHTML
allDemoElements.forEach(el => {
el.innerHTML = x;
});
}
</script>
</body>
</html>
My user wants an input field where he can enter a message, which I will then have displayed as a scrolling marquee across the page. He wants to be able to include empty spaces, for example,
"Employees please look up."
My textarea, when I get the text, doesn't notice the space. Any way to get that?
I know this is an odd request - google only tells me how to remove whitespace, not include it.
var text = $('textarea').val();
<textarea class='messageInput'></textarea>
I am pretty sure that you are getting the value with all the white-spaces right, the problem is in the displaying of the value in your (probably) custom div. The best way would be to set white-space: pre on that element which (as the option suggests) will preserve white-space. ;) Example:
<div id="foo" style="white-space: pre"><!-- insert text here --></div>
And ignore all the &nbps; suggestions which are essentially modifying the text content. CSS is the right way to do this!
You need to convert space characters into non-breaking spaces, which can be done using String.prototype.replace() with a regular expression:
$('#text').html($('textarea').val().replace(/ /g, ' '));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<textarea class='messageInput'>employees hello</textarea>
<p id="text"></p>
You need / /g so that it will match all spaces, not just the first one, which .replace(' '...) would do.
Note that smajl's suggestion is less invasive and probably better, but I'll leave this for posterity.
The spaces in the value are not ignored. It's that the browser by default "compresses" duplicate spaces. Use white-space:pre;
<input type="text" id="input">
<button id="button">
TEST
</button>
<div id="result"></div>
document.getElementById("button").onclick = function() {
var content = document.getElementById("input").value;
console.log(content);
document.getElementById("result").innerHTML = content;
}
#result {
white-space:pre;
}
<input type="text" id="input">
<button id="button">
TEST
</button>
<div id="result"></div>
EDIT: too late ;)
What I want to do is allow the user to input a string then display that string in the web page inside a div element, but I don't want the user to be able to add a bold tag or anything that would actually make the HTML text bold. How could I make it so the text entered by the user does not get converted into HTML code, if the text has an HTML tag in it?
Use createTextNode(value) and append it to your element(Standard solution) or innerText(Non standard solution) instead of innerHTML.
For a JQuery solution look at Dan Weber's answer.
here's a neat little function to sanitize untrusted text:
function sanitize(ht){ // tested in ff, ch, ie9+
return new Option(ht).innerHTML;
}
example input/output:
sanitize(" Hello <img src=data:image/png, onmouseover=alert(666) onerror=alert(666)> World");
// == " Hello <img src=data:image/png, onmouseover=alert(666) onerror=alert(666)> World"
It will achieve the same results as setting elm.textContent=str;, but as a function, you can use it easier inline, like to run markdown after you sanitize() so that you can pretty-format input (eg. linking URLs) without running arbitrary HTML from the user.
use .text() when setting the text in the div rather than .HTML. This will render it as text instead of html.
$(document).ready(function() {
// Handler for .ready() called.
$("#change-it").click(function() {
var userLink = $('#usr-input').val().replace(/.*?:\/\//g, "");
$('#users-text').text(userLink);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input type="text" class="form-control" id="usr-input">
<br>
<button id="change-it" type="button">Update Text</button>
<br>
<div id="users-text"></div>
Why not simply use .text() ?
$('#in').on('keyup', function(e) {
$('#out').text($(this).val());
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input id="in">
<br>
<div id="out"></div>
How do I add a space every three characters in a form in JavaScript and have a replace function? I've seen the question, but I'm still unclear and new at this and I'm not sure where the code would go into the script. This is what I have so far. Please be specific.
<script type="text/javascript">
function var myfunction()
{
}
</script>
</head>
<body>
<FORM ACTION="rules.html" NAME="form">
<INPUT TYPE=TEXT NAME="inp" SIZE=40 onkeyup="this.value=this.value.replace('t','A').replace('a','U')">
</FORM>
</script>
It looks to me like your trying to enter in RNA and have it automatically split out into triplets on entry. But even if that's not what you're doing, this should get you what you need.
First, remove the extra closing </script> tag you have below your form.
Then, replace the input in your form with the following:
<input type="text" name="inp" size="40" onkeyup="this.value=myfunction(this.value);">
and in the myfunction function use this:
function myfunction(val) {
val = val.replace('t','A').replace('a','U');
val = val.replace(/(\w{3})$/, '$1 ');
return val;
}
Granted this could all be cleaner if you pulled your javascript out of your markup and cleaned up your HTML a little, but this should get you going.
This code changes whatever the user types in the box to uppercase, and displays the result in the box.
<html>
<head>
<script type="text/javascript">
function upperCase(x)
{
var y=document.getElementById(x).value;
document.getElementById(x).value=y.toUpperCase();
document.getElementById("mySpan").value=y.toUpperCase();
}
</script>
</head>
<body>
Enter your name: <input type="text" id="fname" onkeyup="upperCase(this.id)">
<br/>
<span id="mySpan"></span>
</body> </html>
But how can I make it so that it displays it UNDER the text box? And that when the user types, the upper case text is displayed under the text box?
Thanks!
I would suggest the following, more maintainable approach, which uses the event registration model as opposed to the inline model:
JS:
<script>
document.getElementById("fname").onkeyup = function() {
document.getElementById("mySpan").innerHTML = this.value.toUpperCase();
}
</script>
Markup:
Enter your name: <input type="text" id="fname"/>
<br/>
<span id="mySpan"></span>
Demo: http://jsfiddle.net/karim79/GPZ8h/
Create a css class
.showUpperCase { text-format: uppercase; }
and add this to your span or textBox.
<span id="mySpan" class="showUpperCase"></span>
This doesn't change the characters entered, only shows them as upper-case.
That means that if you're handling input via a textBox, you'll have to
change to upper-case server-side as well. This is not an additional
chore, since you have to be wary of client-side handling and da a server-side verification, regardless of what the client does