Replacing part of div in my preview with html entites - javascript

On my script I can preview my out put by clicking on my preview button.
In side my pre tags if there is a open <div> and close </div> found with < and > how can I just replace it with the html entities I have tried
$('.preview pre').html(str.replace(/</g, "<").replace(/>/g, ">"));
But because there are br tags in there it replaces the ones around br also which I do not want. I only just want to replace the ones around the open and close div's in side my pre tag.
Question: how can I just replace it with the html entities < and
> only round the open and close divs
Codepen Example Here
Script
<script type="text/javascript">
$('#preview-question').on('click', function (e) {
var editor = $('#question').val();
$('.preview').html(editor.replace(/\n/g, '<br/>'));
$('.preview pre').next('br').remove();
if ($('.preview').find("pre").length > 0){
var str = $('.preview pre').html();
$(".preview pre div").replaceWith("<div>");
//$('.preview pre').html(str.replace(/</g, "<").replace(/>/g, ">").next('div'));
$('.preview pre').html(str);
$('pre').each(function(i, block) {
hljs.highlightBlock(block);
});
}
});
</script>

I have make a for loop for detect only div element and remove all <br>. It's a bit ugly but work fine.
$('#preview-question').on('click', function (e) {
var editor = $('#question').val();
$('.preview').html(editor.replace(/\n/g, '<br/>'));
$('.preview pre').next('br').remove();
if ($('.preview').find("pre").length > 0){
var $str = $('.preview pre');
var pre = $str.html();
$str.html("");
pre = pre.replace(/<br>/g,"\n")
for(t=0;t<pre.length;t++){
if(pre.substr(t,1) == "<" && pre.substr(t+1,3) == "div"){
$str.html($str.html() + pre.substr(0,t).replace(/</g, '<'))
}else if(pre.substr(t,1) == "<" && pre.substr(t+1,4) == "/div"){
$str.html($str.html() + pre.substr(0,t+5).replace(/</g, '<'))
}
if(pre.substr(t,1) == ">" && pre.substr(t-3,3) == "div"){
$str.html($str.html() + pre.substr(t,1).replace(/>/g, '>'))
}
}
}
});
body {
background-color: #F0F0F0;
}
.panel {
box-shadow: 0 0 4px 0 rgba(0, 0, 0, 0.08), 0 2px 4px 0 rgba(0, 0, 0, 0.12);
}
.panel-default > .panel-heading {
background-color: #4d525b;
border-color: none;
color: #FFFFFF;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="panel panel-default">
<div class="panel-heading">
<h1 class="panel-title"></h1>
</div>
<div class="panel-body">
<div class="form-group">
<label class="col-lg-2">Title</label>
<div class="col-lg-10">
<input type="text" name="title" class="form-control" placeholder="Title" />
</div>
</div>
<div class="form-group">
<label class="col-lg-2">Question</label>
<div class="col-lg-10">
<textarea name="question" id="question" class="form-control" rows="10">
Hello this is some code
<pre>
<div class="">
</div>
</pre>
</textarea>
</div>
</div>
<div class="form-group">
<label class="col-lg-2"></label>
<div class="col-lg-10">
<div class="preview"></div>
</div>
</div>
</div>
<div class="panel-footer">
<div class="btn-group text-center">
<button type="submit" class="btn btn-primary">Submit</button>
<button type="button" id="preview-question" class="btn btn-default">Preview</button>
Cancel
</div>
</div>
</div>

Related

Target every label elements that has the correct data-answer attributs with javascript

I have a HTML code and I want to select each label that has the data-anwser set to "correct", how can I do it with pure Javascript? Here's my HTML
<div class="form-group answer" role="group">
<label data-answer="correct">
<div>Test</div>
</label>
</div>
<div class="form-group answer" role="group">
<label data-answer="incorrect">
<div>Test</div>
</label>
</div>
And here's the begining of what I tried with the JS
<script>
var div = document.getElementsByClassName('answer');
window.onload = (event) => {
for (var i = 0; i < div.length; i++) {
var label = div[i].getElementsByTagName('label');
if (label[i].dataset == 'correct') {
console.log("CORRECTE");
} else {
console.log("INCORECTE");
}
console.log(label[i].dataset);
}
}
</script>
Thank you:)
use query selectors:
const btn = document.getElementById('btn');
btn.addEventListener('click', ev => {
const correctAnswers = document.querySelectorAll('.answer [data-answer="correct"]');
correctAnswers.forEach(el => {
el.classList.toggle('selected');
});
});
.form-group > label {
margin: 0.33em;
padding: 0.33em;
border: 2px solid gray;
background-color: silver;
width: 250px;
display: inline-block;
}
.form-group > label.selected {
background-color: yellow;
border: 2px dotted black;
}
<div class="form-group answer" role="group">
<label data-answer="correct">
<div>Test 1</div>
</label>
</div>
<div class="form-group answer" role="group">
<label data-answer="incorrect">
<div>Test 2</div>
</label>
</div>
<div class="form-group answer" role="group">
<label data-answer="correct">
<div>Test 3</div>
</label>
</div>
<button id="btn">highlight correct answers</button>
Try this
var answersCorrect = document.querySelectorAll("*[data-answer='correct']")
Array.from(answersCorrect).forEach(element => {
console.log(element)
})

split textarea value properly jQuery regex

I am having problems to properly split textarea value. My current snippet split each line that starts with "-" and displays it as value of span element, but, it wont collect next line value which does not start with "-".
For example if I paste this text into textarea:
- first match
rest of first match
- second match
- third match
Script should output:
<span style="color:red;">- first match rest of first match </span><br>
<span style="color:red;">- second match</span><br>
<span style="color:red;">- third match</span><br>
$(document).ready(function() {
const regex = /^\s*-\s*/;
$("#txt").keyup(function() {
const entered = $('#textarea').val()
const lines = entered.split(/\n/);
let spans = "";
for (const line of lines) {
if (regex.test(line)) {
spans += "<span style='color:red;'>- " + line.replace(regex, '') + "</span><br/>";
}
}
$(".results").html(spans);
});
});
.row {
background: #f8f9fa;
margin-top: 20px;
padding: 10px;
}
.col {
border: solid 1px #6c757d;
}
<script src="https://code.jquery.com/jquery-3.5.1.slim.min.js" integrity="sha384-DfXdz2htPH0lsSSs5nCTpuj/zy4C+OGpamoFVy38MVBnE+IbbVYUew+OrCXaRkfj" crossorigin="anonymous"></script>
<div class="container">
<div class="row">
<div class="col-12">
<form>
<textarea id="textarea" rows="5" cols="60" placeholder="Type something here..."></textarea>
</form>
</div>
<div class="col-12 results"></div>
</div>
</div>
So, basically script should split textarea value from line that starts with "-" until next line which starts "-".
Code snippet is also available here: https://jsfiddle.net/zecaffe/f7zv3udh/1/
Why not just a split to the \n-?
$(document).ready(function() {
$("#textarea").keyup(function() {
const entered = $('#textarea').val()
const lines = entered.split(/\n-/);
let spans = "";
lines.forEach((l,i)=>{
// remove the first -
if(i===0 && l[0]==="-") l = l.slice(1)
spans += "<span style='color:red;'>- " + l + "</span><br/>";
})
$(".results").html(spans);
});
});
.row {
background: #f8f9fa;
margin-top: 20px;
padding: 10px;
}
.col {
border: solid 1px #6c757d;
}
<script src="https://code.jquery.com/jquery-3.5.1.slim.min.js" integrity="sha384-DfXdz2htPH0lsSSs5nCTpuj/zy4C+OGpamoFVy38MVBnE+IbbVYUew+OrCXaRkfj" crossorigin="anonymous"></script>
<div class="container">
<div class="row">
<div class="col-12">
<form>
<textarea id="textarea" rows="5" cols="60" placeholder="Type something here..."></textarea>
</form>
</div>
<div class="col-12 results"></div>
</div>
</div>

How to make it so that previous answer is displayed when number is clicked after equals in js calculator?

I need to make it so that the previous result is displayed when the user presses a num after pressing equals... how do I do it? And just fyi I am just helping my friend make the code for his calculator clean - his was very messy - if you want I can show you his code as well.
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<body>
<div class='container'>
<div class='answer'>
<p class='returnAnswer'>Answer Will Come Here</p>
</div>
<div class='buttonDiv'>
<div class='button'>0</div>
<div class='button'>1</div>
<div class='button'>2</div>
<div class='button'>3</div>
<div class='button'>4</div>
<div class='button'>5</div>
<div class='button'>6</div>
<div class='button'>7</div>
<div class='button'>8</div>
<div class='button'>9</div>
<div class='equals'>=</div>
<div class='button'>c</div>
<div class='button'>+</div>
<div class='button'>-</div>
<div class='button'>x</div>
<div class='button'>÷</div>
<div class='button'>.</div>
<div class='button'>%</div>
</div>
</div>
</body>
</html>
<script type="application/javascript" src="/share.js"></script>
<script>
var eq = "";
var ans = eval(eq);
$('.button').click(function() {
eq += $(this).text();
$('.returnAnswer').text(eq);
});
$('.equals').click(function() {
$('.returnAnswer').text(ans);
});
</script>
This was a fun thing to do.... Here is what I have done to your code
Added some styles to the button (not important, but makes it easier to click)
Added a class named num to each number button, that will be used to reset the display if any button is clicked following '=' button.
Removed 'equals' class from '=' button and added it as an ID
Added code to clear the display when 'C' is clicked
Changed buttons 'x' to ' * ' and '÷' to '/' as otherwise eval function will not work
Changed back to 'x' and '÷', and added 2 lines inside equals.clicked to replace these with correct operators
Check the Code snippet
var eq = "";
var ans = eval(eq);
var equalsCliked = false;
$('.button').not("#equals, #cbutton").click(function () {
if ($(this).hasClass('num') && equalsCliked)
eq = "";
eq += $(this).text();
$('.returnAnswer').text(eq);
equalsCliked = false;
});
$('#equals').click(function () {
equalsCliked = true;
eq = eq.split("÷").join("/");
eq = eq.split("x").join("*");
ans = eval(eq);
eq = ans;
$('.returnAnswer').text(ans);
});
$('#cbutton').click(function () {
equalsCliked = false;
eq = "";
ans = eval(eq);
//eq = ans;
$('.returnAnswer').text("");
});
.button {
border: 1px solid gray;
padding: 8px;
margin: 3px 3px;
float: left;
cursor: pointer;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<body>
<div class='container'>
<div class='answer'>
<p class='returnAnswer' style="width:330px; padding: 10px; min-height:20px; border: 1px solid gray; border-radius: 2px;">Answer Will Come Here</p>
</div>
<div class='buttonDiv' style="background-color:yellow; float:left; width: 330px;">
<div class='button num'>0</div>
<div class='button num'>1</div>
<div class='button num'>2</div>
<div class='button num'>3</div>
<div class='button num'>4</div>
<div class='button num'>5</div>
<div class='button num'>6</div>
<div class='button num'>7</div>
<div class='button num'>8</div>
<div class='button num'>9</div>
<div id="equals" class='button'>=</div>
<div id="cbutton" class='button'>C</div>
<div class='button'>+</div>
<div class='button'>-</div>
<div class='button'>x</div>
<div class='button'>÷</div>
<div class='button'>.</div>
<div class='button'>%</div>
</div>
</div>
</body>

Set the selector cursor to a new position in contenteditable div [duplicate]

This question already has answers here:
How to set the caret (cursor) position in a contenteditable element (div)?
(13 answers)
Closed 2 years ago.
i've been making a text editor but i couldn't been able to get and set the "cursor" in a new position in the div with the content editable.
<form action="submitchapter.php" method="post">
<div class="input-group mb-3" style="margin-top:30px;">
<input type="text" class="form-control name" placeholder="Chapter Name" name="sname" value="No Title For The Chapter" required>
</div>
<div class="buttons shadow-sm">
<button style="padding:0; border:0px solid white; background-color:white;" type="button" id="buttonbold"><i class="fas fa-bold" id="bold"></i></button>
<input id="file-input" type="file" name="name" style="display: none;" />
</div><br>
<div class="containe shadow-sm" style="padding:20px; background-color:white;">
<div class="content" contenteditable="true" name="content" id="content" role="textbox" spellcheck="false"></div>
</div>
var content = document.getElementById("content");
var bold = document.getElementById("bold");
var content = document.getElementById("content");
$("#buttonbold").click(function(){
content.focus();
var valuelength = content.value.length - 4;
content.setSelectionRange(content.value.length,valuelength);
});
var boldactive = false;
$("#bold").click(function(){
if (boldactive == false) {
var content1 = content.innerHTML;
content.innerHTML = content1 + "<b>";
boldactive = true;
} else {
var content1 = content.innerHTML;
content.innerHTML = content1 + "</b>";
boldactive = false;
}
});
But nothing worked. I have tried with textarea too, but I think I'm doing something wrong.
<div> elements have no value property
$("#buttonbold").click(function(){
content.focus();
var valuelength = content.textContent.length - 4;
content.setSelectionRange(content.textContent.length,valuelength);
});
.
<div> elements do not have a setSelectionRange method either,
so here is a solution to make this kind of selection for elements using the contenteditable property:
const myDiv = document.getElementById('my-div')
, btSelectRange = document.getElementById('bt-select-range')
;
function setSelectionRangeCE(el, pos, len)
{
el.focus();
let range = document.createRange()
, sel = window.getSelection()
;
range.setStart(el.firstChild, pos)
range.setEnd(el.firstChild, pos+len)
sel.removeAllRanges()
sel.addRange(range)
}
btSelectRange.onclick=_=>
{
setSelectionRangeCE(myDiv,2,5)
}
#my-div {
margin: 1em;
padding: .7em;
width: 16em;
height: 3em;
border: 1px solid grey;
}
button {
margin: 1em;
}
<div id="my-div" contenteditable >hello world</div>
<button id="bt-select-range" > select range pos:2 len:5 </button>

Jquery custom function issues

I'm trying to grab the article elements id value for all the article elements one by one so I can add it to the
countCharacters() function so I can have a unique character count for each textarea but both my jquery functions dont seem to work correctly. For example my character count should look something like this.
countCharacters('#comment-1535 .review-info', '#comment-1535 .review-info + div .count', 5000);
countCharacters('#comment-553 .review-info', '#comment-553 .review-info + div .count', 5000);
countCharacters('#comment-6547 .review-info', '#comment-6547 .review-info + div .count', 5000);
Here is my JSFiddle https://jsfiddle.net/jm52wg9k/
HTML
<article class="review" id="comment-1535">
<div class="review-details">
<div class="review-stats">
<!-- content -->
</div>
<form method="post" action="" class="review-form">
<fieldset>
<ol>
<li><label for="review-info">Review Info:</label></li>
<li><textarea name="review_info" class="review-info"></textarea><div class="some"><span class="count"></span></div></li>
</ol>
</fieldset>
<fieldset>
<ol>
<li><input type="submit" name="submit_review" value="Submit Review" class="submit-review" /></li>
</ol>
</fieldset>
</form>
</div>
</article>
<article class="review" id="comment-553">
<div class="review-details">
<div class="review-stats">
<!-- content -->
</div>
<form method="post" action="" class="review-form">
<fieldset>
<ol>
<li><label for="review-info">Review Info:</label></li>
<li><textarea name="review_info" class="review-info"></textarea><div class="some"><span class="count"></span></div></li>
</ol>
</fieldset>
<fieldset>
<ol>
<li><input type="submit" name="submit_review" value="Submit Review" class="submit-review" /></li>
</ol>
</fieldset>
</form>
</div>
</article>
<article class="review" id="comment-6547">
<div class="review-details">
<div class="review-stats">
<!-- content -->
</div>
<form method="post" action="" class="review-form">
<fieldset>
<ol>
<li><label for="review-info">Review Info:</label></li>
<li><textarea name="review_info" class="review-info"></textarea><div class="some"><span class="count"></span></div></li>
</ol>
</fieldset>
<fieldset>
<ol>
<li><input type="submit" name="submit_review" value="Submit Review" class="submit-review" /></li>
</ol>
</fieldset>
</form>
</div>
</article>
Jquery
$(document).ready(function() {
function countCharacters( input, output, max ) {
var $input = $(input);
var $output = $(output);
$output.text(max + ' characters left');
$input
.keydown(function(event) {
if (event.keyCode != 8 &&
event.keyCode != 46 &&
$input.val().length >= max)
event.preventDefault();
})
.keyup(function() {
var val = $input.val().slice(0, max);
var left = max - val.length;
$input.val(val);
$output.text(left + ' characters left');
});
}
countCharacters(reviewInfo() + '.review-info', reviewInfo() + '.review-info + div .count', 5000);
});
$(document).ready(function(){
function reviewInfo(){
var review = $('.review-info').closest('article').attr('id');
var review2 = '#' + review;
return review2;
};
});
CSS
*{
border: 0;
margin: 0;
padding: 0;
}
article{
margin-top: 1em;
}
textarea{
width: 90%;
}
input{
margin: 1em 0;
color: #fff;
background: green;
padding: .5em;
}
DEMO
Your code was fine but the way you were implementing it wasn't proper. Below changes I have made to your code.. See inline comments for more details
function countCharacters(input, output, max,event) {
//Only changes here is I removed .keyup and .keydown which I've binded outside
var $input = $(input);
var $output = $(output);
if (event.keyCode != 8 && event.keyCode != 46 &&
$input.val().length >= max)
event.preventDefault();
var val = $input.val().slice(0, max);
var left = max - val.length;
$input.val(val);
$output.text(left + ' characters left');
}
$(".review-info").on('keyup keypress',function(event){
var _this=$(this);//key up and key press out side document.ready
var _thisCount=_this.next('.some').find('.count');
//find the span using current control's next .some div and its child .count
var max=5000; //also you can add as an data-* attribute to your controls
countCharacters(_this,_thisCount,max,event);//call the function with necessary params
})

Categories

Resources