Insert JavaScript code using Text shortcodes without using php - javascript

I'm using some javascript code to show post dates and comment number in my blog, but my blog doesn't support using php codes.
My JavaScript code
if(showpostdate==true){document.write('<span class="post-date">'+daystr+'</span>')}
if(showpostcomment==true){document.write('<span class="post-comment">'+commento+'</span>')}
My HTML code to call the JavaScript code is
<script>showpostdate = true;var showpostcomment = true;</script>
I want to change this JavaScript code so if I write this text in my text box
[date][comment]
it can show the html code
<span class="post-date">'+daystr+'</span>
<span class="post-comments">'+commento+'</span>

If you use the jQuery library something like this would work to replace the shortcodes:
$('textarea').change(function() {
$this = $(this);
// to be more efficient I would employ a test here that a shortcode exists before applying the replace functions
var textInBox = $this.val();
textInBox = textInBox.replace('[date]', date); // where date is your date var
$this.val(textInBox.replace('[comment]', commentsCount)); // where commentsCount is your comments var
});
It won't create the span that you want to wrap each variable in because you cannot nest these inside a textarea. If you want to have the shortcode typed in a textarea and then nest the returned variables in something so that you can style them, you will need to employ some kind of html + css magic where you place a see-through textarea over a div and update the div contents whenever the textarea is updated. You can then put the span elements inside the div container, and style as you want.

Related

How to assign HTML text to a JavaScript variable?

Is it possible to assign HTML text within an element to a JavaScript variable? After much Googling, I note that you can assign HTML elements to a variable, but I want the actual text itself.
Details about my goal:
I am currently working on a CRUD application, and with the click of a delete button, a modal will display and ask the user for confirmation before deleting the record. Once the button has been clicked, I want to retrieve HTML text within a specific element used for AJAX call data. However, what I have tried so far is not being logged to the console; even when I change the global variable to var deleteLocationID = "test"; I doubt the modal displaying will affect the click function?
The code:
var deleteLocationID;
$("#deleteLocationBtn").click(function () {
deleteLocationID = $(document).find(".locationID").val();
console.log(deleteLocationID);
});
What I have tried so far:
Changing "deleteLocationID = $(document).find(".locationID").val();" to the following variations:
deleteLocationID = $(document).find(".locationID").html();
deleteLocationID = $(".locationID").val() / deleteLocationID = $(".locationID").html();
deleteLocationID = document.getElementsByClassName("locationID").value;
Any help would be much appreciated.
Use the text() method from JQuery, with this you can get the text inside of your element.
Use this way, it may help you:
deleteLocationID = $(document).find(".locationID").text()
Here is example of getting text from class element:
$('.locationID').text()
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.12.2/jquery.min.js"></script>
<div class="locationID">45</div>
It depends on the type of element you are trying to find your value.
for input types you can find the value by .val() in jQuery like:
$(document).find(".locationID").val();
you can grab innerHTML of the element by .html() in jQuery like:
$(".locationID").html();
but if you want to grab innerText of an element you can use .text() in jQuery like:
$(".locationID").text();

get the html of element itself using jquery .html()

How to get the html of element itself using Jquery html. In the below code I would like get the input element inside div using JQuery as shwon below
<div id="content">content div</div>
<input type='text' id="scheduledDate" class="datetime" />
$(function() {
console.log($('#scheduledDate').html('dsadasdasd'));
$('#content').html($('#scheduledDate').html());
});
EDIT:
Can I get the $("#scheduledDate") as string which represent the real html code of the input box, because my final requirement is I want to pass it to some other SubView( I am using backboneJS) and eventually use that html code in a dust file.
My original requirement was to get that input field as string so that I can pass it to some other function. I know, if I keep it inside a DIV or some other container, I can get the html by using .html method of JQuery. I dont want use some other for that purpose. I am just trying to get html content of the input box itself using it's id.
If you want to move the input element into div, try this:
$('#content').append($('#scheduledDate'));
If you want to copy the input element into div, try this:
$('#content').append($('#scheduledDate').clone());
Note: after move or copy element, the event listener may need be registered again.
$(function() {
var content = $('#content');
var scheduledDate = $('#scheduledDate');
content.empty();
content.append(scheduledDate.clone());
});
As the original author has stated that they explicitly want the html of the input:
$(function() {
var scheduledDate = $('#scheduledDate').clone();
var temporaryElement = $('<div></div>');
var scheduleDateAsString = temporaryElement.append(scheduledDate).html();
// do what you want with the html such as log it
console.log(scheduleDateAsString);
// or store it back into #content
$('#content').empty().append(scheduleDateAsString);
});
Is how I would implement this. See below for a working example:
https://jsfiddle.net/wzy168xy/2/
A plain or pure JavaScript method, can do better...
scheduledDate.outerHTML //HTML5
or calling by
document.getElementById("scheduledDate").outerHTML //HTML4.01 -FF.
should do/return the same, e.g.:
>> '<input id="scheduledDate" type="text" value="" calss="datetime">'
if this, is what you are asking for
fiddle
p.s.: what do you mean by "calss" ? :-)
This can be done the following ways:
1.Input box moved to the div and the div content remains along with the added input
$(document).ready(function() {
var $inputBox = $("#scheduledDate");
$("#content").append($inputBox);
});
2.The div is replaced with the copy of the input box(as nnn pointed out)
$(document).ready(function() {
var $inputBox = $("#scheduledDate");
var $clonedInputBox = $("#scheduledDate").clone();
$("#content").html($clonedInputBox);
});
Div is replaced by the original input box
$(document).ready(function() {
var $inputBox = $("#scheduledDate");
$("#content").html($inputBox);
});
https://jsfiddle.net/atg5m6ym/4485/
EDIT 1:
to get the input html as string inside the div itself use this
$("#scheduledDate").prop('outerHTML')
This will give the input objects html as string
Check this js fiddle and tell if this is what you need
https://jsfiddle.net/atg5m6ym/4496/

Inserting html code with markdown to a div, using a twig function

I want to use Markdown to preview to the user how a form field on a twig file will be styled using javascript.
Basically what I'm trying to do, is :
// This function is used to show the Description Preview
$( "#server_new_profile_description" ).on('input propertychange', function() {
// This should make the $(this).val() formated in markdown
var descrString = $(this).val();
$("#descriptionPrev div").html("{{- "+descrString+"|markdown|raw -}}");
});
What I get:
If the input is *ABC*
the output will be: {{*ABC*|markdown|raw}}.
instead of ABC
Can anyone get me through this?
Twig is rendered server-side, which means it gets executed only once, when you request the page. So you will have to use javascript functions to achieve the markdown effects. This means you will need a markdown parser, for example: https://github.com/evilstreak/markdown-js
I created HTML that looks like this.
<div id="server_new_profile_description">
<input type="text">
</div>
<div id="descriptionPrev">
</div>
And I would achieve what you are looking to do like this.
$( "#server_new_profile_description input" ).change(function() {
var descrString = $(this).val();
$("#descriptionPrev").html("{{*"+descrString+"*|markdown|raw -}}");
});
It grabs the input element that is inside the div with the server_new_profile_description ID and won change it grabs the value assigning it to a variable. That variable is then placed inside of the DIV with the ID of descriptionPrev and concatenated with the two string parts

Can jQuery or Javascript change elements within textareas?

My first SO question! Here's what I am trying to do:
I'm rewriting a tool that generates some code a user can paste directly into Craigslist and other classified ad posting websites. I have created a list of websites (they populate from a database with PHP) the user can choose from with a radio button, and I want their choice to populate as bare text (not a link) between some <p></p> elements in a textarea. I'm using jQuery for this.
Textarea before the user chooses:
<p id="thing"></p>
Textarea after the user chooses:
<p id="thing">www.somewebsite.com</p>
HTML
<input type="radio" name="sitechoice" value="www.websiteone.com">www.websiteone.com<br />
<input type="radio" name="sitechoice" value="www.secondwebs.com">www.secondwebs.com
<textarea>
Some stuff already in here
Here is the website you chose:
<p id="thing"></p>
More stuff already here.
</textarea>
JS
$(document).ready(function () {
$("input").change(function () {
var website = $(this).val();
alert(website);
$("#thing2").html(website);
});
});
JS Fiddle (With comments)
If you see the JS Fiddle, you can see that I put another p element on the page outside the textarea, and it updates just fine, but the one inside the textarea does not. I have read many other like questions on SO and I'm starting to think that I can't change an element that's between textarea tags, I can only change the entire textarea itself. Please, lead me to enlightenment!
You actually can fairly easily manipulate the text contents of the textarea like it is part of the DOM, by transforming its contents into a jQuery object.
Here is a jsFiddle demonstrating this solution: http://jsfiddle.net/YxtH4/2/
The relevant code, inside the input change event:
// Your normal code
var website = $(this).val();
$("#thing2").html(website);
// This turns the textarea's val into a jQuery object ...
// And inserts it into an empty div that is created
var textareaHtml = $('<div>' + $("#textarea").val() + '</div>');
// Here you can do your normal selectors
textareaHtml.find("#thing").html(website);
// And this sets the textarea's content to the empty div's content
$("#textarea").val(textareaHtml.html());
The empty div wrapping your HTML is so that you can easily retrieve it as a string later using jQuery's .html() method, and so the parse does not fail if additional text is entered around the p element inside the textarea.
The real magic is $($("#textarea").val()), which takes your textarea's text and parses it into an HTML node contained in a jQuery object.
It can't do it the way that you are thinking (i.e., manipulate it as if it were a DOM element), but it is still accessible as the value of the textarea, so you can retrieve it like that, use basic string manipulation to alter it, and then set the updated string as the new value of the textarea again.
Something like this . . . first give the <textarea> an id value:
<textarea id="taTarget">
Some stuff already in here
Here is the website you chose:
<p id="thing"></p>
More stuff already here.
</textarea>
Then alter your script like this:
$(document).ready(function () {
$("input").change(function () {
var website = $(this).val();
var currentTAVal = $("#taTarget").val();
$("#taTarget").val(currentTAVal.replace(/(<p id="thing">)([^<]*)(<\/p>)/, "$1" + website + "$3"));
});
});
Unless you need the <p> element in there, you might consider using a more simple placeholder, since it won't actually act as an HTML element within the textarea. :)
EDIT : Fixed a typo in the .replace() regex.
I know that this answer is a little bit late, but here it goes =)
You can do exactly the way you want to do. But for that, you need to implement a small trick.
by having this HTML
<input type="radio" name="sitechoice" value="www.websiteone.com">www.websiteone.com
<br />
<input type="radio" name="sitechoice" value="www.secondwebs.com">www.secondwebs.com
<p id="thing2"></p>
<textarea id="textarea">
<p id="thing"></p>
</textarea>
you can edit textarea content, as a DOM by implementing something like the function changeInnerText
$(document).ready(function () {
$("input").change(function () {
var website = $(this).val(); // Gets value of input
changeInnerText(website);
//$("#thing").html(website); // Changes
//$("#thing2").html(website); // Does not change
});
var changeInnerText = function(text) {
var v = $("#textarea").val();
var span = $("<span>");
span.html(v);
var obj = span.find("#thing")[0];
$(obj).html(text);
console.log(obj);
console.log(span.html());
$("#textarea").val(span.html());
}
});
As you can see, I just get the information from the textarea, I create a temporary variable span to place textarea's content. and then manipulate it as DOM.
Instead of attempting to insert the text into the <p> element, insert the text into <textarea> element and include the <p> tag. Something like this should do the trick:
Change:
$("#thing").html(website);
to:
$("textarea").html('<p id="thing">'+website+'</p>');
And here is a fiddle: http://jsfiddle.net/nR94s/

Write inside text area with Javascript

I am trying to write something in text area when I click on a link.
function writeText(txt){
document.getElementById("writeArea").innerHTML = txt;
}
I would like to pass html tag in place of txt as parameter to this function so that I can get image, link etc inside text area. Is it possible in Javascript? || JQuery will be good?
Pre-thanks.
Or if jquery tag was there for a reason:
$('#writeArea').val(txt);
You should use value:
document.getElementById("writeArea").value = txt;
If you want to render some images and anchor tags on the screen then don't use a textarea. Use any other container like <div>, <span>, <p> etc.
$("#yourelementid").html(yourtext);
will put the text (in your case HTML) inside the element with id yourelementid
HTML
<p id="para1"></p>
jQuery
var txt = "<a href='http://www.google.com'>Google</a>";
$("#para1").html(txt);
See a working sample
You can easily do it in jQuery if you just want to set the text of a textarea:
$("#yourid").val("hello");
See it working: http://jsfiddle.net/quQqH/
If you're looking to have HTML in it then it needs to be a container element (such as a div).
// Html
<div id="yourid"></div>
//JavaScript
$("#yourid").html('My link');
Otherwise, another option is to have a Rich Text Editor (like Yahoo Editor) so that it renders the HTML that's in the textarea input - this will make it user editable. This is slightly more complicated, as you'll need to include the correct files to make the editor work. Then just do something like the following:
var myEditor = new YAHOO.widget.SimpleEditor('yourid', {
height: '200px',
width: '350px',
toolbar: 0 // Hides the toolbar
});
myEditor.render();
$("#yourid").val("Click for <a href='http://yahoo.com'>Yahoo</a>");
You can see this working: http://jsfiddle.net/quQqH/1/. In this case, I've removed the toolbar by setting it to 0 but it is customisable to show different buttons, etc. Just remove that line to display the default toolbar.
just give like this
$("#ID").val("<img src='images/logo.png' />");
If you want to write long text in the textarea, you can use this way:
HTML
<textarea id="theId"></textarea>
jQuery
var a = 'Test textarea content. Google" ';
$("#theId").val(a);
JS FIDDLE

Categories

Resources