How to underline onclick and add to textarea - javascript

I have this code that enables the users to add a list of keywords to a text area and than submit it. The list will show on a div, then the user has to select one or many words in one line to add it to id="out".
The code is working as of now, but it's not what I want and I'm blocked. What I want is that the user can click (instead of select) one or many words to underline them and then click on the image to add them as a line to id="out".
I've big trouble to solve this as my JS knowledge is very limited, but I hope to learn quickly by working on similar projects and I've a lot in mind.
Thank you
Code:
var arraySearchTerms = [];
function add() {
arraySearchTerms = document.getElementById("searchTerms").value.split('\n');
let newKeywordHtmlStr = '';
for (var i = 0; i < arraySearchTerms.length; i++) {
newKeywordHtmlStr += '<div style="padding: 6px;border-bottom: #b5aeae; border-bottom-style: solid;border-bottom-width: 1px;"><span id="term' + i + '">' + arraySearchTerms[i] + "</span><span style='float: right;'><img src='Red_Cross.png' height='15' width='11'/></span></div>";
}
document.getElementById("keywords").innerHTML += newKeywordHtmlStr;
}
function get_selection() {
var txt = '';
if (window.getSelection) {
txt = window.getSelection().toString();
} else if (document.selection) {
txt = document.selection.createRange().keywords;
}
document.getElementById("out").innerHTML += txt;
}
<TITLE>Test</TITLE>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link rel="stylesheet" type="text/css" href="negative.css">
<div id="container">
<div id="container2">
Add your search terms:
<textarea type="text" id="searchTerms">
</textarea> <br />
<button onclick="add()">Add >></button><br />
<br /><br /> Negative keywords:
<textarea type="text" id="out"></textarea>
</div>
<div id="container1">
Search terms:
<div id="keywords" onclick="get_selection()"></div>
</div>
</div>
<script src="negative.js"></script>

Related

JQuery hide/show property is not working in my code

I have written code to upload multiple files by cloning input field in jquery.
Here the logic is; if #file_1 field is empty, the $('#addBtn').on('click', function () is supposed to go in else part of if condition and display the relevant hidden <p> tag. If first field is left empty, the add button (add more button) should not clone the field. Instead it should show a message to user to upload file in the first available field first and the click add button to upload more file. Here Jquery show()/hide function is not working.
Please have a look on my code, I'll be much obliged. Thank you!
console.log('objection page here');
var Index = 1;
// START CODE FOR BASIC DATA TABLE
$(document).ready(function () {
$('#addBtn').on('click', function () {
var uploadFieldVal = $('#file_'+ Index).val();
console.log(uploadFieldVal);
if(uploadFieldVal !="")
{
Index++;
var uFile = $('#file_1').clone();
//var id = "btnAdd_" + Index;
var fileItem = "<input type='file' name='fileUpload[file][]'' id='file_" + Index + "'class='form-control'/> ; " +
"<p id='fileMsg_" + Index + "style='visibility: hidden; color: red'>Please attach file here first </p>;"
$('#fileDiv').append(fileItem);
}
else
{
console.log('fileMsg_'+Index);
$('#fileMsg_'+Index).show();
//$('#fileMsg_1).show(); //its also not working
}
});
});
<button class="btn btn-sm btn-primary float-right" id="addBtn" type="button"><i class="fa fa-plus"></i>
</button>
<div class="form-group" id="fileDiv">
<label for="file_1">File</label>
<input type="file" name="fileUpload[file][]" id="file_1" class="form-control"/>
<p id="fileMsg_1" style="visibility: hidden; color: red">Please attach file here first </p>
</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js" integrity="sha512-894YE6QWD5I59HgZOGReFYm4dnWc1Qt5NtvYSaNcOP+u1T9qYdvdihz0PPSiiqn/+/3e7Jo4EaG7TubfWGUrMQ==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
.show() does not work on CSS for visibility.
The matched elements will be revealed immediately, with no animation. This is roughly equivalent to calling .css( "display", "block" ), except that the display property is restored to whatever it was initially. If an element has a display value of inline, then is hidden and shown, it will once again be displayed inline.
$(function() {
console.log('objection page here');
var Index = 1;
$('#addBtn').on('click', function() {
var uploadFieldVal = $('#file_' + Index).val();
console.log(uploadFieldVal);
if (uploadFieldVal != "") {
Index++;
var uFile = $('#file_1').clone();
var fileItem = "<input type='file' name='fileUpload[file][]'' id='file_" + Index + "' class='form-control'/> ; ";
fileItem += "<p id='fileMsg_" + Index + "' style='visibility: hidden; color: red'>Please attach file here first </p>;"
$('#fileDiv').append(fileItem);
} else {
console.log('fileMsg_' + Index);
$('#fileMsg_' + Index).css("visibility", "visible");
}
});
});
<button class="btn btn-sm btn-primary float-right" id="addBtn" type="button"><i class="fa fa-plus"></i></button>
<div class="form-group" id="fileDiv">
<label for="file_1">File</label>
<input type="file" name="fileUpload[file][]" id="file_1" class="form-control" />
<p id="fileMsg_1" style="visibility: hidden; color: red">Please attach file here first </p>
</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js" integrity="sha512-894YE6QWD5I59HgZOGReFYm4dnWc1Qt5NtvYSaNcOP+u1T9qYdvdihz0PPSiiqn/+/3e7Jo4EaG7TubfWGUrMQ==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
You need to change visibility to visible to "show" it.
See More: https://api.jquery.com/show/

jquery : how to toggle div after using search function on it?

I'm using a search function to highlight text (function 2) in different chapters. In parallel most of this text is stored in div called content to ease reading. You can toggle these div to read the text (function 1).
When text is found by function 2, it's no longer possible to toggle the text in this chapter. I suppose this is related to use of "this" in function 1 (If I delete this it works) or handlers (if I add live in front of click in function 1 it works but live is deprecated and remplacement "on" is not working).
// function 1 : toggle content when clicking the button
$(".chapter button").on('click',function(f) { //live deprecated to be replaced
f.preventDefault();
var id = $(this).attr('id');
console.log(id)
$('#' + id + '+*').toggle();
// toggle is not working when highlight function located in item in this specific chapter
});
// function 2 : highlight content
$('#monForm').submit(function(e) {
e.preventDefault();
console.log('submitted')
// clear form
var str = $('#valeurForm').val();
$('#valeurForm').val("");
console.log(str);
// highlight
var strCut = str.split(' ');
for (i = 0; i < strCut.length; i++) {
// grey chapter where the word is located
$("div[class='chapter']:contains(" + strCut[i] + ")").css("color", "#929aab");
// and highlight in red specific word
// but i want to highlight all occurences of the word in this chapter ? how can I define index d ?
$("div[class='chapter']:contains(" + strCut[i] + ")").each(function(d) {
$(this).html($(this).html().replace(strCut[i], '<font color="red">$&</font>'));
});
};
});
<head>
<meta charset="utf-8">
<style>
.content {
display: none;
}
</style>
</head>
<body>
<form name="search" id="monForm">
<input type="text" id="valeurForm">
</form>
<div class="chapter">
chapter 1
<button type="button" id="chapter1">Display content</button>
<div class="content">
content chapter1
</div>
</div>
<br>
<div class="chapter">
chapter 2
<button type="button" id="chapter2">Display content</button>
<div class="content">
content chapter2
</div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<!-- jQuery est inclus ! -->
</body>
The problem was your $(this).html(). The .replace that you did removes the event listener of your button, because it modifies the DOM. Instead of getting the whole .html(), I did it with .children(), and then replaced just the text of it.
About replacing all the occurrences of the chapter word, you could use a Regular Expression. Using a string will replace just the first occurrence of the string. With the regular expression you can replace all of them.
// function 1 : toggle content when clicking the button
$(".chapter button").click(function(f) { //live deprecated to be replaced
f.preventDefault();
var id = $(this).attr('id');
$('#' + id + '+*').closest('.content').toggle();
// toggle is not working when highlight function located in item in this specific chapter
});
// function 2 : highlight content
$('#monForm').submit(function(e) {
e.preventDefault();
console.log('submitted')
// clear form
var str = $('#valeurForm').val();
$('#valeurForm').val("");
// highlight
var strCut = str.split(' ');
for (i = 0; i < strCut.length; i++) {
// grey chapter where the word is located
$("div[class='chapter']:contains(" + strCut[i] + ")").css("color", "#929aab");
// and highlight in red specific word
$("div[class='chapter']:contains(" + strCut[i] + ")").each(function(d) {
var regex = new RegExp(strCut[i],"g")
$(this).children().each(function (index,element) {
const text = $(element).html().replace(regex,'<font color="red">$&</font>')
$(element).html(text)
})
});
};
});
<head>
<meta charset="utf-8">
<style>
.content {
display: none;
}
</style>
</head>
<body>
<form name="search" id="monForm">
<input type="text" id="valeurForm">
</form>
<div class="chapter">
chapter 1
<button type="button" id="chapter1">Display content</button>
<div class="content">
content chapter1 and the second ocurrence of chapter also highlighted
</div>
</div>
<br>
<div class="chapter">
chapter 2
<button type="button" id="chapter2">Display content</button>
<div class="content">
content chapter2
</div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<!-- jQuery est inclus ! -->
</body>
EDIT
I wasn't clear enough about the errors, sorry, and I've noticed the right solution.
The point is that, instead of modifying the parent element, I've changed the text of the childrens. When you change the whole html, you remove the listener of your buttons when you add it again to the html, and that's why isn't possible to toggle the divs.

html checkbox list that shows and hides links when filtered

I have written code that creates a checkbox list where when i click the checkbox below my list of options i would like a link to show underneath that the user can click (show/hide) I cannot figure out why my code will not work. If the user unchecked the box the link disappears but nothing happens when i click my check boxes. I would like to do this fix in JQuery
<!DOCTYPE html>
<html>
<div class ="container">
<head></head>
<body>
<input id="grp1" type="checkbox" value="group_1" onClick="http://google.com" />
<label for="grp1"> group 1 </label>
<div>
<input id="grp2" type="checkbox" value="group_2" onClick="http://google.com" >
group_2</label>
</div>
</body>
</html>
You'll have to use javascript to hide/show the wanted elements in html. There are many approaches to this. The most basic one would be something like
<!DOCTYPE html>
<html>
<body>
<div id="container">
<input id="grp1" type="checkbox" value="group_1"/>
<label for="grp1"> group 1 </label>
<br>
<input id="grp2" type="checkbox" value="group_2"/>
<label for="grp2"> group_2</label>
<!--hidden elements using css-->
Link for group_1
<br>
Link for group_2
</div>
<script>
//listen to the click event on the whole container
document.getElementById("container").onclick = function (e) {
//check every box if it's checked
if (document.getElementById('grp1').checked) {
document.getElementById('url1').style.display = 'block';
} else {
document.getElementById('url1').style.display = 'none';
}
if (document.getElementById('grp2').checked) {
document.getElementById('url2').style.display = 'block';
} else {
document.getElementById('url2').style.display = 'none';
}
}
</script>
</body>
</html>
Of course you can use different approaches like creating the element in javascript then adding it to the html if you don't like the idea if existing hidden elements. You might also use loops to loop through checkbox element and simply show/hide the url accordingly. And more to make the code flexible on any number of boxes. Something like this
<!DOCTYPE html>
<html>
<body>
<div id="container">
<div id="checkBoxContainer">
<input id="grp1" type="checkbox" value="group_1"/>
<label for="grp1"> group 1 </label>
<br>
<input id="grp2" type="checkbox" value="group_2"/>
<label for="grp2"> group_2</label>
</div>
<!--hidden elements using css-->
Link for group_1
<br>
Link for group_2
</div>
<script>
//listen to the click event on the whole container
document.getElementById("checkBoxContainer").onclick = function (e) {
var linkNumber = 1; //This is number of the first url element with ud url1
var containerChildren = document.getElementById("checkBoxContainer").children;
//loop through the children elements
for (var i = 0; i < containerChildren.length; i++) {
var oneChild = containerChildren[i]; //catch only one child in a variable
//simply filter the input elements which are of type checkbox
if(oneChild.tagName === "INPUT" && oneChild.type === "checkbox"){
//Show or hide the url accordingly.
if (oneChild.checked) {
document.getElementById('url' + linkNumber++).style.display = 'block';
} else {
document.getElementById('url' + linkNumber++).style.display = 'none';
}
}
}
}
</script>
</body>
</html>
The onclick HTML attribute doesn't work that way. The attribute value is executed as javascript. You can make a js function to show/hide the link.
Hi you want to try this:
<!DOCTYPE html>
<html>
<head>
<style type="text/css">
.group-link{
display: block;
}
.hidden{
display: none;
}
</style>
</head>
<body>
<div class="jsParent">
<label for="grp1">
<input id="grp1" type="checkbox" value="group_1" onchange="showLink(this)"/> group 1
</label>
<a class="group-link hidden jsLink" href="https://www.animalplanet.com/tv-shows/dogs-101/videos/the-doberman">Group 1 Link</a>
</div>
<div class="jsParent">
<label for="grp2">
<input id="grp2" type="checkbox" value="group_2" onchange="showLink(this)"/> group_2
</label>
<a class="group-link hidden jsLink" href="https://www.animalplanet.com/tv-shows/cats-101/videos/ragdoll">Group 2Link </a>
</div>
<script type="text/javascript">
function showLink(el){
var parent = el.parentElement.parentElement;
var linkEl = getAnchorEl(parent);
if(linkEl){
if(el.checked){
linkEl.classList = linkEl.classList.value.replace('hidden', '');
}else{
linkEl.classList = linkEl.classList.value + ' hidden';
}
}
}
function getAnchorEl(parent){
var childrens = parent.children;
var linkEl = null;
for (var i = 0; i < childrens.length; i++) {
var childEl = childrens[i];
if(childEl.classList.value.indexOf('jsLink') > -1){
linkEl = childEl;
break;
}
}
return linkEl;
}
</script>
</body>
</html>
Your question is undoubtedly a duplicate but I am answering because I would like to help you identify issues with the code you posted.
I notice you have a <div>tag between your tag and tag. Why? This is a bit of an over simplification but as a general rule never put anything between your <html> and <head> tag and only place <div> tags inside your <body> tag. Also be mindful of how you nest your elements. That tag starts after and before .
Even if that were correct placement you close the before you close your div arbitrarily in the middle of your body tag. you should never have
<div>
<p>
</div>
</p>
Instead it should look like this
<div>
<p>
</p>
</div>
In your onClick attribute you have a random URL. That will not open a new window. You new too put some javascript in there.
<input onClick="window.open('http://google.com')">
Also your second label tag does not have an opening, just a </label> close tag
To answer your question - I suggest you look at the jQuery toggle function.
<input type="checkbox" id="displayLink" />
Google
<script type="text/javascript">
$("#displayLink").click(function(){
$("#googleLink").toggle();
});
</script>
As a general rule you should favor event handlers (such as the $("").click() posted above) to handle events (like clicking) as opposed to html attributes such as onClick.

How can I make a textarea with character limit highlighting like Twitter?

Twitter's submit tweet textbox highlights the characters that are over the character limit:
As you can see, the characters that overrun the character limit are highlighted in red. How can I achieve something like this?
You'll find the necessary solution and required code here:
How to insert <em> tag when exceeding 140 limit i.e. going negative?
...and here:
REGEX - Highlight part over 19 chars
Your question appears to be duplicitous.
Note: I didn't have the option to post the above links as a comment (i.e. privilege contingent on reputation).
Here's the code as per Simon Kuang's recommendation (see comments):
HTML:
<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
<meta charset=utf-8 />
<title>JS Bin</title>
</head>
<body>
<h3>Your text here</h3>
<div contenteditable="true" id="myDiv">edit me
</div>
<p>
<h3>Stuff over 19 characters</h3>
<div id="extra">
</div>
<p>
<h3>Sample output</h3>
<div id="sample">
</div>
</body>
</html>
CSS:
.highlight {
color:red;
}
JavaScript:
$(document).ready(function() {
$('#myDiv').keyup(function() {
var content = $('#myDiv').html();
var extra = content.match(/.{19}(.*)/)[1];
$('#extra').html(extra);
var newContent = content.replace(extra, "<span class='highlight'>" + extra + "</span>");
$('#sample').html(newContent);
});
});
Here is the example, show alert when the limit is reached and thereafter highlight all the characters entered.
$(document).ready(function() {
var input = $('#text_text');
var warning = $('#warning');
var char_limit = 30;
input.on('keyup', function() {
var val = $(this).val();
if (val.length > parseInt(char_limit)) {
alert("limit reached");
warning.html('hello').css('display', 'block');
l = val.length
var input = document.getElementById("text_text");
input.setSelectionRange(char_limit, l);
input.focus();
} else {
warning.css('display', 'none');
}
});
});
#warning {
display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="test_box">
<textarea name="msg" cols="50" rows="5" id="text_text"></textarea>
<div id="warning"></div>
</div>
Try this (pattern)
html
<data></data><br />
<textarea maxlength="20" placeholder="20 character limit"></textarea>
js
$(function () {
$(document).on("keyup", "textarea", function (e) {
if ($(e.target).val().length >= 20) {
$("data").text($(e.target).attr("placeholder"))
.fadeIn(1000).fadeOut(9000);
};
});
});
jsfiddle http://jsfiddle.net/guest271314/8RScd/

change displayed div with Javascript

I've been trying to get this to work and thought it would be relatively easy but i'm just unable to target my div's with javascript.
I want a list of boxes and each one will be clickable and each one has a buddy which is hidden. when you click a , it hides and shows its buddy which will have an input box. Type the text in you need and press ok and it changes back to it's original displaying the text you have entered.
the head contains the following:
<head>
<script language="javascript">
var state = 'none';
function showhide(layer_ref) {
if (state == 'block') {
state = 'none';
}
else {
state = 'block';
}
if (document.all) { //IS IE 4 or 5 (or 6 beta)
eval( "document.all." + layer_ref + ".style.display = state");
}
if (document.layers) { //IS NETSCAPE 4 or below
document.layers[layer_ref].display = state;
}
if (document.getElementById &&!document.all) {
hza = document.getElementById(layer_ref);
hza.style.display = state;
}
}
</script>
And then my HTML contains:
<div id="div0">
<a href="#" onclick="showhide('div1');" style="text-decoration:none;">
<div style="width:200px; height:30px; background-color:grey;color:white">
Input: <div id="showinput"></div>
</div>
</a>
</div>
<div id="div1" style="display:none;">
<div style="width:200px; height:30px; background-color:grey;color:white">
<input type="text id="addInput" /">
<input type="submit" value="submit" name="submit" onclick="showhide('div1');" />
</div>
</div>
I'm trying to add the following but it just won't update the original and the script just makes the buddy div show below the original. How can i hide the original at the same time?
var myobj = document.getElementById("addInput");
var mytext = myobj.value;
document.getElementById("showinput").innerHTML = mytext;
You are missing a closing quote around type="text so the input id is not set. Try:
<input type="text" id="addInput" />

Categories

Resources