Note taking feature, line break and no content - javascript

I'm building the feature to take notes on my web app. I'm running into two problems:
I can't figure out how to recognize line breaks. I can hardcore text with line breaks, but when user clicks Edit it shows on the text the <br> and if he saves it just shows <br> in plain text.
Also if the user deletes all the text and clicks save it doesn't work and just prints <textarea>.
Any help is greatly appreciated!
$('#edit').click(function() {
$('#edit').hide();
$('#note').each(function() {
var content = $(this).html();
$(this).html('<textarea style="width:inherit">' + content + '</textarea>');
});
$('#save').show();
});
$('#save').click(function() {
$('#save').hide();
$('textarea').each(function() {
var content = $(this).val(); //.replace(/\n/g,"<br>");
$(this).html(content);
$(this).contents().unwrap();
});
$('#edit').show();
});
#note {
word-wrap: break-word;
max-width: 40rem;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="col-md-6">
<h5 class="card-tittle">Note</h5>
<hr>
<div class="container index">
<div class="row">
<div class="jumbotron col-md-12" id="note">
Test Text.
</div>
<div class="col-md-12">
<button class="btn btn-primary" id="edit"><span class="glyphicon glyphicon-edit"></span>Edit</button>
<button class="btn btn-primary" id="save"><span class="glyphicon glyphicon-save"></span>Save</button>
</div>
</div>
</div>
</div>

I think you want to do something like this...
$('#edit').click(function() {
$('#edit').hide();
$('#note').each(function() {
var content = $(this).html().replace(/<br>/g,"\n");
$(this).html('<textarea style="width:inherit">' + content + '</textarea>');
});
$('#save').show();
});
$('#save').click(function() {
$('#save').hide();
$('textarea').each(function() {
var content = $(this).val().replace(/\n/g,"<br>"); //.replace(/\n/g,"<br>");
$(this).html("");
$(this).append(content);
$(this).contents().unwrap();
});
$('#edit').show();
});
Demo: https://www.codeply.com/go/hAL9pWWUFk

Related

Displaying elements based on search

I would like the .box elements to show/hide based on the words the user searches for, so for example if a user types in 'Title2 Title1' because those words exists inside box one and two they will remain visible with the renaming .box elements hiding. All the text within the .box elements needs to be searchable not just that in the .title element.
Below is how far I've got. It's almost there but it's not quite working as hoped.
Any help would be great.
Many thanks.
<input placeholder="Search" id="search" type="text" />
<div class="box">
<div class="title">Box Title1</div>
<div class="content">
Box title one content
</div>
</div>
<div class="box">
<div class="title">Box Title2</div>
<div class="content">
Box title two content
</div>
</div>
<div class="box">
<div class="title">Box Title3</div>
<div class="content">
Box title three content
</div>
</div>
<script>
$("#search").on("input", function () {
var search = $(this).val();
if (search !== "") {
var searchArray = search.split(" ");
searchArray.forEach(function(searchWord) {
$(".box").each(function () {
if($(this).is(':contains('+ searchWord +')')) {
$(this).show();
} else {
$(this).hide();
}
});
});
} else {
$(".box").show();
}
});
</script>
You need to use a different search method. :contains does not work as you expect. Consider the following example.
$(function() {
function filter(e) {
var term = $(e.target).val();
if (term.length < 3) {
$(".box").show();
return;
}
$(".box").each(function(i, el) {
if ($(".content", el).text().indexOf(term) >= 0) {
$(el).show();
} else {
$(el).hide();
}
});
}
$("#search").keyup(filter);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input placeholder="Search" id="search" type="text" />
<div class="box">
<div class="title">Box Title1</div>
<div class="content">Box title one content</div>
</div>
<div class="box">
<div class="title">Box Title2</div>
<div class="content">Box title two content</div>
</div>
<div class="box">
<div class="title">Box Title3</div>
<div class="content">Box title three content</div>
</div>
So for example if on is entered, no filtering is performed. If one is entered, the script will look inside the content class of each box and if one is found in the text, it will be shown otherwise, it is hidden. If the User clears their search out, all items are shown.
Hide all box before iterate, then only show when match any words:
$("#search").on("input", function () {
var search = $(this).val();
if (search !== "") {
var searchArray = search.split(" ");
// Hide all .box
$(".box").each(function () {
$(this).hide();
})
searchArray.forEach(function(searchWord) {
$(".box").each(function () {
if($(this).is(':contains('+ searchWord +')') ) {
$(this).show();
}
});
});
} else {
$(".box").show();
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input placeholder="Search" id="search" type="text" />
<div class="box">
<div class="title">Box Title1</div>
<div class="content">
Box title one content
</div>
</div>
<div class="box">
<div class="title">Box Title2</div>
<div class="content">
Box title two content
</div>
</div>
<div class="box">
<div class="title">Box Title3</div>
<div class="content">
Box title three content
</div>
</div>
Loop through all .boxs and using regex pattern matching, check either the title or content matches the search query. Show all matched boxes and hide all others
I have also fiddled it here
$("#search").on("input", function () {
var searchables=$('.box');
console.log(searchables)
var query=$(this).val();
searchables.each(function(i,item){
var title=$(item).find('.title').text();
var content=$(item).find('.content').text();
var rgx=new RegExp(query,'gi');
if(rgx.test(title) || rgx.test(content))
{
$(item).show();
}
else
{
$(item).hide();
}
})
})

How can I get direct text without a tag with jQuery

I've got an issue where I want to select (and replace) a string of text with no tags with jQuery. I need to retrieve the "us-east1-mp2 lobby", but it only selects the text with a span.
My code:
function fixServerLocation() {
setTimeout(function() {
if ($(".admin.chatLog").find(".section").length > 0) {
var section = ($(".admin.chatLog").find(".section"));
if (typeof section !== 'undefined') {
var chatMessages = document.querySelectorAll("[id^='chatMessage']");
if (typeof chatMessages !== 'undefined') {
$('.section [id^="chatMessage"]').children('div.details').children().css({
"color": "red",
"border": "2px solid red"
});;
//The code that I currently have to select the tag-less text. The styling is only to highlight it.
}
}
}
fixServerLocation();
}, 70);
}
fixServerLocation();
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="chatMessage listItem first" id="chatMessage-us-east1-mp2-6668675">
<button class="expand small" type="button" tabindex="-1">+</button>
<div class="options right"></div>
<div class="details"><span class="time">2020-04-04 11:07</span>us-east1-mp2 lobby
<span><span class="username adminLookup">CommanderAnime</span></span>:
<span class="message ">Test</span></div>
</div>
How it currently looks when running the code:
I want to replace the "us-east1-mp2 lobby" with "Newark lobby". Thanks for any help
This is quite dangerous if your text is part of text attributes
NOTE: because I remove the event handler when I rewrite the HTML, you will need to delegate the button:
$("#someStaticContainerForTheChatMessages").on("click","button.expand",function() { whatever the button does })
$(function() {
const $chatMessages = $("[id^='chatMessage']");
if ($chatMessages.length > 0) {
$chatMessages.each(function(i, message) {
$('div.details', message).children().addClass("highlight")
message.innerHTML = message.innerHTML.replace("us-east1-mp2 lobby", "Newark lobby")
})
}
})
.highlight {
color: red;
border: 2px solid red;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="chatMessage listItem first" id="chatMessage-us-east1-mp2-6668675">
<button class="expand small" type="button" tabindex="-1">+</button>
<div class="options right"></div>
<div class="details"><span class="time">2020-04-04 11:07</span>us-east1-mp2 lobby<span><span class="username adminLookup">CommanderAnime</span></span>:
<span class="message ">Test</span></div>
</div>
If using jquery, you can easily achieve this by using javascript String.replace method:
const detailsHtml = $('.details').html()
const replacedContent = detailsHtml.replace('us-east1-mp2 lobby', 'Newark lobby')
$('.details').html(replacedContent)
Whats the idea: As this text isn't inside a tag, you need to get the whole div html as a string, and perform a replace. The first line returns the html content of .details as a string.
Then we perform the replace and use the same .html(value) method to set the new content.
Check the fiddle: https://jsfiddle.net/diogocosta/7wrmLog5/5/
const detailsHtml = $('.details').html()
const replacedContent = detailsHtml.replace('us-east1-mp2 lobby', 'Newark lobby')
$('.details').html(replacedContent)
//console.log(replacedContent)
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="chatMessage listItem first" id="chatMessage-us-east1-mp2-6668675">
<button class="expand small" type="button" tabindex="-1">+</button>
<div class="options right"></div>
<div class="details"><span class="time">2020-04-04 11:07</span>us-east1-mp2 lobby
<span><span class="username adminLookup">CommanderAnime</span></span>:
<span class="message ">Test</span></div>
</div>

jquery: read inside each div, span and input

I'm creating a project in ASP.NET MVC and jQuery. When a user click on addSentence button, I want to duplicate a div called copythis with all events and insert it in another div called myform.
in copythis I have two div: in the first there is a span called sentence where I insert the text in the input in the second the user can add more then one field with different text.
When the user clicks the button called save I want to read all copythis in myform and create a structure to send to a webapi.
I have a problem is the javascript because I can read properly each div.
$("#addSentence").on("click", function (event) {
if ($("#inputSentence").val() == "")
alert("Sentence must have a value");
else {
event.preventDefault();
var theContainer = $("#copythis");
if (theContainer != null) {
var clonedSection = $(theContainer).clone(true);
if (clonedSection != null) {
$(clonedSection).find("#sentence")
.text($("#inputSentence").val());
$(clonedSection).appendTo("#myform");
}
}
}
});
$("#save").on("click", function (event) {
$("#myform #copythis").children().each(function (index, element) {
var elm = $(this);
var sentence = elm.find('.row span#sentence').val();
if (sentence != '') {
console.log('Sentence: ' + sentence);
$("input").children().each(function (m, l) {
var txt = $(this).val();
if (txt != '') {
console.log('Example: ' + txt);
}
});
}
});
});
function makeRepeater(sectionsSelector, addClass, removeClass, AYSMsg) {
$(sectionsSelector + " " + addClass + "," + sectionsSelector +
" " + removeClass).on("click", function (event) {
// Avoiding the link to do the default behavior.
event.preventDefault();
// Get the container to be removed/cloned
var theContainer = $(this).parents(sectionsSelector);
if ($(this).is(addClass)) {
// Cloning the container with events
var clonedSection = $(theContainer).clone(true);
// And appending it just after the current container
$(clonedSection).insertAfter(theContainer);
} else {
// If the user confirm the "Are You Sure" message
// we can remove the current container
if (confirm(AYSMsg)) {
// Making fade out, hide and remove element a sequence
// to provide a nice UX when removing element.
$(theContainer).fadeOut('normal',
function () {
$(this).hide('fast',
function () { $(this).remove(); }
);
}
);
}
}
});
}
makeRepeater(
'.my-repeated-section-form', /* The container selector */
'.addform', /* The add action selector */
'.removeform', /* The remove action selector */
'Are you sure you want to remove this section?' /* The AYS message. */
);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js">
</script>
<div class="row">
<div class="row">
<div class="col-lg-10">
<div class="input-group">
<input id="inputSentence" type="text"
class="form-control" placeholder="Sentence...">
<span class="input-group-btn">
<button class="btn btn-secondary"
type="button" id="addSentence">Add</button>
</span>
</div>
</div>
</div>
<div class="col-lg-12">
<div style="display: inline;">
<div class="group-of-repeated-sections" style="display: none;">
<div class="my-repeated-section">
<div id="copythis">
<div class="row">
<div class="col-lg-10">
<span id="sentence"></span>
</div>
<div class="col-lg-2">
<span>
+
-
</span>
</div>
</div>
<div class="my-repeated-section-form">
<div class="row">
<div class="col-lg-12">
<input type="text" />
<span>
+
-
</span>
</div>
</div>
</div>
<div style="height:25px;"></div>
</div>
</div>
</div>
</div>
</div>
</div>
<div id="myform"></div>
<button id="save">Save</button>

How can I make jquery script shorter?

I have got following code (i shorted it to make it more readable)
And I would like to ask if it is possible to do not write almost the same code for every button? How can I do it the easiest way? I have got 6 buttons and code would be quite long.
<script>
$(document).ready(function(){
$("#option1").click(function(){
if($(".option1").is(":visible")){
$(".option1").hide("slow",function(){});
}
else{
$(".option2, .option3").hide("slow",function(){});
$(".option1").show("slow",function(){});
}
});
$("#option2").click(function(){
if($(".option2").is(":visible")){
$(".option2").hide("slow",function(){});
}
else{
$(".option1, .option3").hide("slow",function(){});
$(".option2").show("slow",function(){});
}
});
$("#option3").click(function(){
if($(".option3").is(":visible")){
$(".option3").hide("slow",function(){});
}
else{
$(".option1, .option2").hide("slow",function(){});
$(".option3").show("slow",function(){});
}
});
});
</script>
<body>
<div class="containter">
<div class="row">
<div class="col-md-4">
<button type="button" id="option1" class="btn btn-primary">Button1 >></button>
</div>
<div class="col-md-4">
<button type="button" id="option2" class="btn btn-primary">Button2 >></button>
</div>
<div class="col-md-4">
<button type="button" id="option3" class="btn btn-primary">Button3 >></button>
</div>
</div>
</div>
</body>
Without the need to change much of your html, add a common class option to all your option1, option2, ... :
<div class ="option option1">a</div>
<div class ="option option2">b</div>
<div class ="option option3">c</div>
and then you can use this below:
Array.from(document.getElementsByTagName('button')).forEach(function(btn){
btn.addEventListener('click', function(e){
if($("." + e.target.id).is(":visible")){
$("." + e.target.id).hide("slow",function(){});
}
else{
$(".option").hide("slow",function(){});
$("." + e.target.id).show("slow",function(){});
}
});
});
DEMO
You can reduce the code to just one click listener. Try this:
<script>
$(document).ready(function() {
$(".btn-primary").click(function() {
var option = $(this).data("option");
if ($(".option." + option).is(":visible")) {
$(".option." + option).hide("slow", function() {});
} else {
$(".option").not("." + option).hide("slow", function() {});
$(".option." + option).show("slow", function() {});
}
});
});
</script>
<body>
<div class="containter">
<div class="row">
<div class="col-md-4">
<button type="button" id="option1" data-option="option1" class="btn btn-primary">Button1 >></button>
</div>
<div class="col-md-4">
<button type="button" id="option2" data-option="option2" class="btn btn-primary">Button2 >></button>
</div>
<div class="col-md-4">
<button type="button" id="option3" data-option="option3" class="btn btn-primary">Button3 >></button>
</div>
</div>
</div>
<!-- common class option added -->
<div class="options">
<div class="option option1"></div>
<div class="option option2"></div>
<div class="option option3"></div>
</div>
</body>
I added a common class to all the options, and a data-option attribute to your buttons.
You don't need to check to see whether the current button is visible. It's visible because it was just clicked on.
All you need to do is show the other buttons that weren't clicked on and hide the one that was. To do this, assign the same class to all 3 buttons. In the example below, I added the class "myBtn" to all 3 buttons.
$(".myBtn").click(function () {
var id = $(this).attr('id');
$(".myBtn:not(#"+id+")").show("slow", function () {});
$(this).hide();
});
JSFiddle demo.

Why is my sidebar hiding everytime after second click?

The sidebar is hidden and it will fadeIn once I have submitted the correct pin. But when I click any option in the sidebar more than once it is hiding! Why?
var pin = 1234;
$("#confirm_pin").click(function () {
var pin = document.getElementById("Pin").value;
if (pin == 1234) {
alert("You have now acesss!");
$(".management").hide();
$(".management_sidebar").fadeIn();
} else {
alert("Please, enter the correct pin");
}
});
$(".option_management").on("click", function () {
$(".page_holder_management").children().hide();
var option = $.trim($(this).text());
var find_click_object = $(this).attr("id");
if (option == "Home page") {
$("div.page_holder_management > div:nth-child(1)").fadeIn();
} else {
alert("false");
}
});
HTML
<div class="management_sidebar" style="display:none;">
<div class="header_management_sidebar">
<p style="position:absolute; margin:10px; font-weight:bold;"> Site administration </p>
</div>
<div id="management_content" STYLE="margin:20px; color:black;">
<div class="box_management">
<div class="option_management" id="1">Home page</div>
<div class="option_management" id="2">Table page</div>
<div class="option_management"> test </div>
<div class="option_management"> test </div>
</div>
</div>
</div>
<div class="page_holder_management">
<div class="management_homePage" style="display:none;">
<div class="header_management_homePage">
<p style="position:absolute; margin:10px; color:black; font-weight:bold;"> Change home page </p>
</div>
</div>
<div class="management_tablePage" style="display:none;">
<div class="header_management_homePage">
<p style="position:absolute; margin:10px; color:black; font-weight:bold;"> Change table page </p>
</div>
</div>
</div>
In the html code I made pages that should fadeIn when I click on any option in the sidebar and it should fadeOut when i click another option with another page should fadeIn!
Please tell me where I am doing wrong?
PLease check this http://kapten.mzzhost.com/test/System_management.php to test my problem! The pin is: 1234
Check the fiddle, you should make html and js relations simpler. I used data attributes there and if i understand correctly, this is what you want
var pin = 1234;
$("#confirm_pin").click(function () {
var pin = document.getElementById("Pin").value;
if (pin == 1234) {
alert("You have now acesss!");
$(".management").hide();
$(".management_sidebar").fadeIn();
} else {
alert("Please, enter the correct pin");
}
});
$(".option_management").on("click", function () {
var target = $(this).data('target');
$('.contents').hide();
$('.contents.' + target).fadeIn();
});
html changes with data attribute
<div class="option_management" data-target="management_homePage" id="1">Home page</div>
<div class="option_management" data-target="management_tablePage" id="2">Table page</div>

Categories