I have the following code
$(document).ready(function () {
$(".page").on('click', function () {
$("#ctl00_MainContent_dfComments").html(function (i, val) {
return val.replace(/\]/g, '>');
});
});
$(".page").on('click', function () {
$("#ctl00_MainContent_dfComments").text(function (i, val) {
return val.replace(/\[/g, "<");
});
});
});
Which with the help of replacing characters in entire document JQuery works wonderfully. However, when the < bracket is inserted, the entire div goes blank. I can replace the [ with anything, but as soon as I put in < everything inside that div disappears. Any idea of what might be going on?
Yes, this is supposed to create a bold (kind of like a bb parser)
Your second replace is using .text() instead of .html(). As a side note, you can also combine the two event handlers.
$(document).ready(function () {
$(".page").on('click', function () {
$("#ctl00_MainContent_dfComments").html(function (i, val) {
return val.replace(/\]/g, '>').replace(/\[/g, '<');
});
});
});
Here it is in action: http://jsfiddle.net/pbnDP/8/
Pressing the button makes the text go bold.
The obvious security concerns are discussed in the comments on the main post. Don't put this on a site where users can generate the content this is being run on.
It looks like your probably not ending up with Valid HTML and the DOM rendering the html is disposing of any invalid HTML for you.
Theres a few problems with your script - the first it that it promotes dangerous html, your appear not to be doing any form of sanity or blacklist/whitelist checking on the code.
The other issue is your manually naming ASP.NET IDs - this is bad since they can change. Use .ClientID instead.
$(".page").on('click', function () {
$("#ctl00_MainContent_dfComments").html(function (i, val) {
return val.replace(/\[/g, "<");
});
});
.html might work better then text, and also use class name or clientid to select elements with like John suggested in his answer , that is not good to guess what the browser is going to change the id to.
Pleas check your DOM again, seems like browser either detects the < > as html tag or html aint valid.
Working version: http://jsfiddle.net/pbnDP/
I do know in few programming world including Ruby there is somthing called html_safe you might want to use alongside this.
Hope it helps.
Related
I am creating a plugin for a template. After publishing the template to the web, there is an attribute inside an inserted script that I need to get its value and use it in my plugin.
Is there a way to do it with JS/jQuery?
Here is the part of the page in which the attribute is located:
Platform.Utils.initWidget('#skyline', function (elem) {
new Website.tool.Constantin(elem, {
event: 'click',
transitionDuration: 93000
});
});
I need to find a way to search the html and get the value for transitionDuration i.e 93000.
Additional comment:
This code is generated by the template and I have no control on changing how it is formed.
I inspected the html, and the template places the code as a JS code ( "the code" ) somewhere in the body.
So I assumed that there might be a way that the plugin that I am making could be able to read the html, find the attribute and use it to get the same transition duration that the html defines on its elements.
After re-reading and seeing your comments, I assume your template inserts
a script somewhere and you want to get at the transitionDuration with the plugin.
As in
var scripts = document.getElementsByTagName("script"), duration=0;
for (var i=0;i<scripts.length;i++) {
var text = scripts[i].textContent;
if (text.indexOf("transitionDuration") !=-1) {
duration = parseInt(text.split("transitionDuration:")[1],10);
break;
}
}
alert(duration);
<script>
Platform.Utils.initWidget('#skyline', function (elem) {
new Website.tool.Constantin(elem, {
event: 'click',
transitionDuration: 93000
});
});
</script>
You can get CSS values in javascript and jQuery but in this case, is better if you store the value in a variable.
var transDuration = 93000;
Platform.Utils.initWidget('#skyline', function (elem) {
new Website.tool.Constantin(elem, {
event: 'click',
transitionDuration: transDuration
});
});
alert(transDuration);
You can access to the transDuration variable when you need it.
If you need to read a CSS value, take a look at this:
Get a CSS value with JavaScript
Good luck
Im knocking my head to this scripts and I cant get my function to be displayed inside the Aletify.js alerts.
Some help will be incredibly helpful ;-)
The Function:
Oshoplang = {
// System Message Text
RemoveError: '<p>This item has now been removed from your cart.\n\nThank you.',
Added: 'Has now been added to your cart',
OutOfStock: '<p>This item is not currently available or is out of stock.</p>',
PreOrder: '<p>Your pre-order has been made successfully.\n\nThank you.</p>',
InvalidQuantity: '<p>It looks like you entered an invalid quantity.\n\nPlease try again.</p>',
}
window.alert = function() {};
$("#confirm-else").on('click', function() {
reset();
$('#e-content').addClass('blur');
alertify.alert(Oshoplang, function(e) {
if (e) {
alertify.success("OK");
$('#e-content').removeClass('blur');
location.reload();
} else {
alertify.error("You've clicked Cancel");
}
});
return false;
});
I normally don't get a message on the run, but this way but i believe i'm close somewhere :-)
Not sure if you're still having this issue, but I believe that the alertify.alert function doesn't have any callbacks, as it's just a way to show a message. You're probably looking for the alertify.confirm instead.
The message is also not showing up because the first argument to alertify.alert or alertify.confirm needs to be a string. In your example, you're passing an object.
I've set up a demo of your code which has been adjusted to work on here on JSFiddle.
For what it's worth, the code sample is using an older version of alertify (0.3) and it has been updated, so that version 1 which is now out would have a somewhat adjusted syntax.
I need a function that adds and removes a column in a table if a checkbox is checked or not. The code I got at the moment works fine to an extend. The console messages come up at the right time and the table column is correctly added to the HTML.
The problem lies in the else{} part: The columns are not removed when checkbox is unchecked. In firebug I get a message that my selector is wrong but I am not sure how to fix it. And assuming the selector was correct, is my application of .detach(this) correct?
function makevisible(idsandclasses,object,folder){
$('#checkbox'+idsandclasses).change(function() {
console.log(idsandclasses, "before if checked")
if($('#checkbox'+idsandclasses).is(':checked')){
console.log(idsandclasses, "if checked")
$('tr:contains("Details")').append('<td id="rowdetails'+folder+'">'+object.name+'</td>')
}else{
console.log("unchecked")
$('#rowdetails'+folder).detach(this)
}
})
};
Here I use the function:
$(document).ready(function() {
$("#dot0001").hover(makevisible("info0001", object0001,"object0001"))
})
This is the firebug message:
TypeError: expr.replace is not a function
expr = expr.replace( rattributeQuotes, "='$1']" )
And this is the part in my jquery-1.9.0.js file my code has problems with:
expr = expr.replace( rattributeQuotes, "='$1']" );
I assumed there is no need for the HTML. If that should be the case though let me know.
Remove this from detach. Just .detach() is sufficient.
You need to pass a selector to detach (or nothing at all its optional). You are passing this which is a DOM element. Ideally, $('#rowdetails'+folder) will match the element you are trying to detach.
Source:
http://api.jquery.com/detach/
i suppose the problem is
$(document).ready(function() {
$("#dot0001").hover(function(){
makevisible("info0001", object0001,"object0001")
})
})
UPDATED POST
Ok I've managed to make Markdown and MathJax work together, it was relatively simple actually. I've used marked together with MathJax.
$(function() {
var $text = $("#text"), // the markdown textarea
$preview = $("#preview"); // the preview div
$text.on("keyup", function() {
$preview.html( marked($text.val()) ); // parse markdown
MathJax.Hub.Queue(["Typeset", MathJax.Hub, "preview"]); // then let MathJax do its job
})
});
Problem now is: I think markdown is parsing my math 1st before MathJax can change it. How do i fix this? I think its fixed on Math StackOverflow, but how? I need to stop markdown from parsing math
UPDATE 2
This works, but not sure if its the way math.stackexchange does it, but it seems to produce similar/same results with what I tested so far ...
$(function() {
var $text = $("#text"),
$preview = $("#preview");
$text.on("keyup", function() {
$preview.html( $text.val() );
MathJax.Hub.Queue(["Typeset", MathJax.Hub, "preview"]);
});
MathJax.Hub.Register.MessageHook("End Process", function (message) {
$preview.html( marked($preview.html()) );
});
});
OLD POST BELOW
In the math stackexchange, I can use MathJax with Markdown. I wonder what do I need to do that? I can use a library like marked to render Markdown, but for MathJax, it seems like it just renders on page loads. How can I call it to re-render or better just render whats needed (specified by me)
html = marked("some markdown string") // a HTML string
// is there something like
html = MathJax.parse(html)
UPDATE
I think I should be looking at http://www.mathjax.org/docs/1.1/typeset.html#manipulating-individual-math-elements. But when I try
$text.on("keyup", function() {
$preview.html( marked($text.val()) );
var math = MathJax.Hub.getAllJax("preview");
console.log(math);
MathJax.Hub.Queue(["Text", math, "a+b"]);
})
Where:
$text: is the jQuery element for my textarea
$preview: is the preview div
I find that math is undefined, so it seems var math = MathJax.Hub.getAllJax("preview") is not working. I have a div#preview btw.
The fastest way is to protect the math from your markdown-parser.
See this question for a detailed answer by Davide Cervone, including a link to the code used by math.SE.
For sublime, add the following code to Markdown Preview --> Settings - User,
{
/*
Enable or not mathjax support.
*/
"enable_mathjax": true
}
as shown below,
Refer to How to enable MathJax rendering in Sublimetext Markdown Preview.
So I am using jQuery to load in an html file then do a simple string replace on some tokens. However they will not do the replace. Can someone explain to me why this is not working with the replace calls?
pendingRow.html
<span id="{pendingDbId}" data-database="{pendingName}">
{pendingName} ({pendingTime}) - <a id="cancel-{pendingDbId}" data-dbId="{pendingDbId}" href="#">Cancel</a>
<br />
</span>
jQuery
$('#pendingLoadDiv').load('templates/pendingRow.html', function() {
$('#pendingLoadDiv').html($('#pendingLoadDiv').html().replace("{pendingName}", $('#database option:selected').text()));
$('#pendingLoadDiv').html($('#pendingLoadDiv').html().replace("{pendingDbId}", $('#database').val()));
$('#pendingLoadDiv').html($('#pendingLoadDiv').html().replace("{pendingTime}", "--:--:--"));
$('#pendingDiv').append($('#pendingLoadDiv').html());
});
It is getting all the way to the append at the bottom with no errors however it is not replacing any text.
I have even tried storing the pendingLoadDiv to a variable then running the replace calls on the variable and still am having the same issue.
Any ideas?
You really should not use load, I am sure the browser freaks out with the invalid characters in the id. Plus you are doing all of this DOM look ups when you can just work with the string directly.
$.ajax({
url: "templates/pendingRow.html",
success: function( data ){
var html = data.replace("{pendingName}", $('#database option:selected').text())
.replace("{pendingDbId}", $('#database').val())
.replace("{pendingTime}", "--:--:--");
$('#pendingDiv').append( html );
}
});
In the load success handler it has not yet updated the container. You should first set the html into the container and then try to replace.
$('#pendingLoadDiv').load('templates/pendingRow.html', function(data) {
var $pendingLoadDiv = $('#pendingLoadDiv').html(data);
var markup = $pendingLoadDiv.html();
markup = markup.replace("{pendingName}", $('#database option:selected').text());
markup = markup.replace("{pendingDbId}", $('#database').val());
markup = markup.replace("{pendingTime}", "--:--:--");
$('#pendingDiv').append(markup);
});
.replace() will only replace the first instance of the string, then return. To do a replaceAll, use a regular expression with the global flag: http://jsfiddle.net/RwPuu/
$('#pendingLoadDiv').html($('#pendingLoadDiv').html().replace(/{pendingName}/g, "replacingString"));
EDIT: The jQuery API documentation also seems to state, contrary to the other answers, that the selected element's content is replaced, then the callback is run. http://api.jquery.com/load
I'd guess that at the time the inner function has been called, Jquery has not yet updated the contents of your div with the loaded data, so you're search/replacing the OLD data, which is about to get deleted.
Try
$('#pendingLoadDiv).load('templates/pendingRow.html', function(data) {
^^^^^--- the loaded data
data.replace("{pendingName}", $('#database option:selected').text()));
etc...
$('#pendingDiv').append(data);
}