I am trying to input strings in a contenteditable div and based on "#" in a string ,go for ajax call .
1) If '#' comes as first character as user input, go for ajax call.
2) If whitespace/tab comes before `'#', go for ajax call
3) If user inputs a string and places cursor manually in between of string and provide whitespace followed by '#' and then whitespace, go for ajax call.
.html
<div contenteditable="true" onkeyup="detectHash($event)"></div>
.js
function detectHash(event){
var input = event.target.innerText.trim();
// check above conditions (1),(2),(3), conditons true,
// go for ajax call
$().ajax({
success:function(){
}
}}
}
You can use a regex to pass these rules:
1) If '#' comes as first character as user input, go for ajax call.
2) If whitespace/tab comes before `'#', go for ajax call
(3 is the same as 2)
Rule 1: ^# ^ = start of line
Rule 2: \s# \s = any whitespace, including tab
Example snippet, these can be combined into a single regex, but left as separate for demonstration (as with noajax/goajax classes - for the snippet only)
$("div").on("input", detectHash);
function detectHash(event) {
var input = event.target.innerText.trim();
if (input.match(/^#/) || input.match(/\s#/))
{
$("#out").removeClass("noajax").addClass("goajax");
} else {
$("#out").removeClass("goajax").addClass("noajax");
}
}
div#inp { border:1px solid #ccc; height:200px; width:200px; }
div.noajax { background-color: red; height:5px; width:200px; }
div.goajax { background-color: green; height:5px; width:200px; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id='inp' contenteditable="true"></div>
<div id='out' class="noajax"></div>
Alternatively, you can use .indexof but might need an extra if you also need to check for tabs, whereas .match with \s handles this for you.
if (input.indexOf("#") === 0 || input.indexOf(" #") >= 0)
Related
I need to delete <annot:annotationLevel><annot:body> and </annot:body></annot:annotationLevel> only if the line contains "(a)" through "(zzz)"
It's for something that looks like this:
<annot:annotationLevel><annot:body><p>“(a) Definitions. In this section:</p></annot:body></annot:annotationLevel>
<annot:annotationLevel><annot:body><p>“(1) List of Material Interested Parties. The term “List of Material Interested Parties” means the List of Material Interested Parties established under subsection (c)(1).</p></annot:body></annot:annotationLevel>
<annot:annotationLevel><annot:body><p>“(2) Oversight Board. The term “Oversight Board” has the meaning given the term in section 5 of PROMESA (48 U.S.C. 2104).</p></annot:body></annot:annotationLevel>
<annot:annotationLevel><annot:body><p>“(b) Required Disclosure.</p></annot:body></annot:annotationLevel>
In the above sample, (a) and (b) should have their annot tags deleted and only have p tags left.
NOTE: It should only work for lowercase alpha characters and NOT on uppercase alpha. (Now I wonder how I'll differentiate alpha with roman numeral (i), (v), and (x), cause those shouldn't be affected, but maybe that's for later)
I've been solving this but my current solution isn't working for some reason. In this one, I'm only trying to target "(a)" and not yet the rest using RegEx.
function annotationWrapCleanups() {
let lines = document.querySelector('#textarea3').value.split('\n');
for (let i = 0; i < lines.length; i++) {
if (lines[i] !== "" && lines[i].includes('(a) Definitions.')) {
lines[i].replace('<annot:annotationLevel><annot:body>', '')
lines[i].replace('</annot:body></annot:annotationLevel>', '')
}
}
}
.main-textarea {
height: 50px;
width: 99%;
}
.main-textarea:focus {
outline: none;
}
.cleanup-btn {
padding: 10px;
margin-top: 10px;
}
<textarea class="main-textarea annotation-wrap" id="textarea3"></textarea>
<button class="cleanup-btn" onclick="annotationWrapCleanups();">clean</button>
Anyways, thank you in advance for any help, any insight would be appreciated!
Check if the line matches the Regex /<p>“\([a-z]+\)/.
Our matched string should:
<p>" Start with this. So that we're looking at the beginning of the element's text content.
This avoids matching things like (c) in your second line
\( Match an open bracket.
\ is to escape what ( normally does in regex.
[a-z]+ Match one or more lowercase letters
\) Match a closing bracket
Using combining this and roman numerals will be a whole different beast, because the simplest question would be, how could you know if it's (i) the letter or (i) as in one.
I set it up for you in the snippet, just click clean and check if the results match what you're looking for. I added the extra line breaks after cleaning to make it clearer to see.
function annotationWrapCleanups() {
const textArea = document.querySelector('#textarea3')
let lines = textArea.value.split('\n');
for (let i = 0; i < lines.length; i++) {
if (lines[i].match(/<p>“\([a-z]+\)/g)) {
lines[i] = lines[i].replace('<annot:annotationLevel><annot:body>', '')
lines[i] = lines[i].replace('</annot:body></annot:annotationLevel>', '')
}
}
textArea.value = lines.join('\r\n\n')
}
document.querySelector('#textarea3').value = `<annot:annotationLevel><annot:body><p>“(a) Definitions. In this section:</p></annot:body></annot:annotationLevel>
<annot:annotationLevel><annot:body><p>“(1) List of Material Interested Parties. The term “List of Material Interested Parties” means the List of Material Interested Parties established under subsection (c)(1).</p></annot:body></annot:annotationLevel>
<annot:annotationLevel><annot:body><p>“(2) Oversight Board. The term “Oversight Board” has the meaning given the term in section 5 of PROMESA (48 U.S.C. 2104).</p></annot:body></annot:annotationLevel>
<annot:annotationLevel><annot:body><p>“(b) Required Disclosure.</p></annot:body></annot:annotationLevel>`
.main-textarea {
height: 50px;
width: 99%;
}
.main-textarea:focus {
outline: none;
}
.cleanup-btn {
padding: 10px;
margin-top: 10px;
}
<textarea class="main-textarea annotation-wrap" id="textarea3"></textarea>
<button class="cleanup-btn" onclick="annotationWrapCleanups();">clean</button>
I'm trying to select multiple <div> elements with the class .choice and then check if the contents are all uppercase OR if the contents are all lowercase. Based on if its contents are all lowercase or uppercase i then want to apply a CSS class.
I've been trying to use Jquery/Javascript to do this however I'am very new to both languages.
The Jquery i used was along the lines of:
$(".choice").text()
// and also
$(".choice").text().isUppercase().addClass()
But i'm pretty sure i can't use JavaScript and Jquery in this manner.
To achieve this you can provide a function to addClass() which checks the case of the text in the current element and returns the class to add based on what it finds. Try this:
$(".choice").addClass(function() {
var t = $(this).text();
if (t.toUpperCase() === t)
return 'upper';
else if (t.toLowerCase() === t)
return 'lower'
});
.upper { color: #C00; }
.lower { color: #0C0;
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="choice">ALL UPPERCASE</div>
<div class="choice">Both Cases</div>
<div class="choice">all lowercase</div>
Note that the if condition can be shortened using the below ternary statement. It's a personal preference if you prefer brevity over readability:
return t.toUpperCase() === t ? 'upper' : t.toLowerCase() === t ? 'lower' : null;
Hello I have try a lot but can't solve . can any one explain me how I'll drive a JavaScript event after write" in " . I mean i wanted to make a div display:none to display:block after write " in ". that's a auto suggestion issue i've attaching a image the pattern is like that [word] [in] [word].
That's will do onkeyup event.
JS version...
var myInput = document.getElementById('myInput');
var messageBox = document.getElementById('messageBox')
myInput.addEventListener("keyup", checkString);
function checkString() {
var str = myInput.value;
// notice whitespace either side of "in" to prevent false positives
if (str.indexOf(' in ') > -1) {
messageBox.style.display = "block";
} else {
messageBox.style.display = "none";
}
}
#messageBox {
display: none;
padding: 15px;
background: #f2f2f2;
border: 1px solid #e6e6e6;
margin-top: 15px;
}
<input id="myInput" placeholder="Type here">
<div id="messageBox">In was typed</div>
Use input event in jQuery
$('#some_text_box').on('input', function() {
var value = $(this).val();
// do your stuff
// split the value by space and check if it contains 'in'
});
Using jQuery keyup event you can get value which user type in text box while user typing. Then with the use of indexOf javascript method you can compare string with in word. if match found you can display div otherwise hide that div.
Make sure to use toLowerCase() to convert string enter by user in lower case to get perfect match with in word. if user enter in in uppercase it function works fine.
DEMO
What is indexOf() method ?
The indexOf() method returns the position of the first occurrence of a
specified value in a string.
This method returns -1 if the value to search for never occurs.
Note: The indexOf() method is case sensitive.
$('#text').on('keyup', function() {
var value = $(this).val();
if(value.toLowerCase().indexOf(' in ') >= 0){
$('yourdiveselector').show()
}else{
$('yourdiveselector').hide()
}
});
In visual studio and other code editors it is possible to view the white space characters. These would appear as small ellipses in the line.
Is it possible to mimic this feature in html. I have been able to use the pre tag to display the text but I am at a loss on how to display the white space characters.
Is it possible via CSS or javascript to show the white space characters?
You can wrap each space in your pre elements in a span with background, so the spaces become visible, but you could copy the text as usually. Here is a JSFiddle example.
Example script (assuming there are no nested tags in the pre):
var pres = document.querySelectorAll('pre');
for (var i = 0; i < pres.length; i++) {
pres[i].innerHTML = pres[i].innerHTML.replace(/ /g, '<span> </span>')
}
CSS:
pre > span {
display: inline-block;
background: radial-gradient(circle, #cc0, rgba(192,192,0,0) 2px);
}
Alternatively, you can use a custom font for pre elements, in which the whitespace characters are replaced with something visible.
you could replace whitespace chars with the ellipsis symbol, like
jsstring.replace(/[\s]/g, "\u2026");
where jsstring denotes a javascript variable with the text to alter. note that you can get and set the textual representation of an html tag including its contentby means of the jquery html() function.
in case you wish to keep line breaks, use
jsstring.replace(/[ \t]/g, "\u2026");
(example available on jsfiddle: http://jsfiddle.net/collapsar/ARu7b/3/).
in fact, [\s] is just a shorthand for [ \t\r\n]. you may define your own character class containing exactly what you consider to be a whitespace character.
It's impossible to do that by CSS but in Javascript you can do something like this. Note that I used jQuery; if you are not loading jQuery in your project let me know to change my code to plain JavaScript.
for example you have something like:
<pre>
ul.nav-menu { list-style: none; }
ul.nav-menu li:last-child { border: none; }
ul.nav-menu li a { color: #b3b3b3; display: block; }
</pre>
You can do:
<script>
var text = $("pre").html();
$("pre").empty()
words = text.split(" ");
for (i = 0; i < words.length; i++) {
$("pre").append(words[i] + '%');
}
</script>
And it will replace spaces with any characters like '%' or whatever.
Result will be:
ul.nav-menu%{%list-style:%none;%}
ul.nav-menu%li:last-child%{%border:%none;%}
ul.nav-menu%li%a%{%color:%#b3b3b3;%display:%block;%%}
I set out on a journey to create an iTunes-like search using Javascript. I learned about jQuery, and with some help from people on StackOverflow, I was successful.
I've come back here to share with you a very simple way to create a dynamic hide/show list based on the user input.
Let's search!
The entirety of the tutorial code can be found here.
And a JSFiddle for it is here!
So good to see Nick was successful on this experiment. good job on learning how to do it :)
Just in case you haven't encountered this jquery plugin, you might want to take a look at it too it's called Quick search.
https://github.com/riklomas/quicksearch
And I've used it on numerous pages and it works like a charm. example:
http://fedmich.com/works/types-of-project.htm
First, create a simple Div Layout with some text in the divs and search bar above it.
<div class="search_bar">
<form><!--The Field from which to gather data-->
<input id="searchfield" type="text" onclick="value=''" value="Case Sensitive Search">
</form>
</div>
<!--Containers With Text-->
<div class="container">
<div class="container_of_hc">
<div class="horizontal_containers">Cat</div>
<div class="color">Black</div>
<div class="color">White</div>
<div class="color">Orange</div>
</div>
<div class="horizontal_containers">Dog</div>
<div class="horizontal_containers">Rat</div>
<div class="horizontal_containers">Zebra</div>
<div class="horizontal_containers">Wolf</div>
</div>
CSS:
.container {
width: 100%;
}
.horizontal_containers {
height:10%;
border: solid 3px #B30015;
font-size: 45px;
text-align: center;
}
Second, you will make a script utilizing jQuery. Remember the title says this is a Dynamic Search, meaning (for us) we want to update the search with each key typed:
$("#searchfield").keyup(function() {
Note: Need a selector refresher?
Then we will set a variable to the value in #searchfield:
var str = $("#searchfield").val(); //get current value of id=searchfield
To ensure we show all the divs in our list when there is nothing in the searchfield we create an if statement based on the length of our new variable (str):
if (str.length == 0) {
//if searchfield is empty, show all
$(".horizontal_containers").show();
}
Last, we do the actual hiding of the divs if the length of str is not 0:
else {
//if input contains matching string, show div
//if input does not contain matching string, hide div
$("div:contains('" + str + "').horizontal_containers").show();
$("div:not(:contains('" + str + "')).horizontal_containers").hide();
}
});
The div:contains() and div:not(:contains()) statements are what set the conditions. It's essentially an if statement. They search the text contained within the div, not the div attributes. If you want to search a deeper div structure you can use more than one selector in the script's jQuery statements like so:
if (str.length == 0) {
//if searchfield is empty, show all
$(".container .color").show();
} else {
//if input contains matching string, show div
//if input does not contain matching string, hide div
$(".container div:contains('" + str + "').color").show();
$(".container div:not(:contains('" + str + "')).color").hide();
}
Replace the script statement you already have to give it a try.
Note: The nesting structure of your divs must match that in your selector.
And that's essentially it. If you have tips to improve this, know how to change it to a case insensitive search, or anything else you can think of, please let me know!
Thanks to MrXenoType I have learned case insensitivity for the :contains function.
To create a case insensitive search for this project simply add:
$.expr[":"].contains = $.expr.createPseudo(function(arg) {
return function( elem ) {
return $(elem).text().toUpperCase().indexOf(arg.toUpperCase()) >= 0;
};
});
This creates a pseudo for the contains function. Place this code above your other script (within the same script) to make true for only this script.
Try:
$.expr[":"].contains_nocase = $.expr.createPseudo(function(arg) {
return function( elem ) {
return $(elem).text().toUpperCase().indexOf(arg.toUpperCase()) >= 0;
};
});
for adding a :contains_nocase() selector with jQuery 1.8