Changing the value of a Telerik RadEditor with Javascript/jQuery - asp.net

I'm trying to manually clean the HTML of a Telerik RadEditor with Javascript but I can't seem to find the correct place to store the value so that it gets saved on post back.
Here's the JS I have:
$(function () {
jQuery.fixHash = function ($html) {
// modify $html
return $html;
};
$("#adminEditingArea input[id$='SaveButton']").unbind("click").click(function () {
$("iframe[id$='_contentIframe']").trigger("save");
// call .net postback
return false;
});
});
var editorSaveEventInit = false;
function InitSaveEvent() {
if (!editorSaveEventInit) {
var $EditFrames = $("iframe[id$='_contentIframe']");
if ($EditFrames && $EditFrames.length > 0) {
$EditFrames.bind("save", function (e) {
var $thisFrame = $(this);
var thisFrameContents = $thisFrame.contents();
if (thisFrameContents) {
var telerikContentIFrame = thisFrameContents.get(0);
var $body = $("body", telerikContentIFrame);
var html = $.fixHash($body).html();
$body.html(html);
// also tried storing the modified HTML in the textarea, but it doesn't seem to save:
//$thisFrame.prev("textarea").html(encodeURIComponent("<body>" + html + "</body>"));
}
});
editorSaveEventInit = true;
}
}
};
$(window).load(function () {
InitSaveEvent();
});
Is there any way to access the Telerik RadEditor object with JavaScript (using OnClientCommandExecuted()?) so that I can access the .get_html() and .set_html(value) functions? If not, what values do I need to set before posting back?

Why don't you use custom content filters.

Ah, just discovered Telerik's built-in $find() function: http://www.telerik.com/help/aspnet-ajax/editor_getingreferencetoradeditor.html
Edit: here's the solution I came up with for my InitSaveEvent() function:
var editorSaveEventInit = false;
function InitSaveEvent() {
if (!editorSaveEventInit) {
var $EditFrames = $("iframe[id$='_contentIframe']");
if ($EditFrames && $EditFrames.length > 0) {
$EditFrames.bind("save", function (e) {
var $thisFrame = $(this);
var thisFrameContents = $thisFrame.contents();
if (thisFrameContents) {
var telerikContentIFrame = thisFrameContents.get(0);
var $body = $("body", telerikContentIFrame);
var html = $.fixHash($body).html();
// SOLUTION!
var $radeditor = $thisFrame.parents("div.RadEditor.Telerik:eq(0)");
var editor = $find($radeditor.attr("id"));
editor.set_html(html);
// ☺
}
});
editorSaveEventInit = true;
}
}
};

Related

template rendered is not working properly in meteor JS

template rendered is not working
when user successfully login in to system i redirect to profile page that time data is not get but if i visit another page and come back to profile page that time it is working fine. also when i reload page that time also it is not working
here is code
Template.profile.rendered = function(){
var user_email = {};
user_email.mail = Session.get('email');
var imgName = Session.get('image');
Meteor.call("imgSend",imgName,function(error, result){
$('.user_profile_image').attr("src",result)
});
Meteor.call("getLinkMeta",user_email,function(error, result){
var link_all_info = [];
var walldata = [];
var total = result.length;
var processed = 0;
var t = result.forEach(function (entry){
var link_info = {};
link_info.link_id = entry._id;
Meteor.call("getCommentList",link_info, function (error, res){
if(error){
console.log("e");
}else{
entry.comments = res;
}
processed++
if(processed == total){
//walldata=result;
}
});
});
Template.profile.walldata = function(){
return result;
};
//return result;
});
}
Router.route('profile', {
path: '/profile',
data: function() {
/* Meteor.subscribe("Users");
Meteor.subscribe("Link");
Meteor.subscribe("Linkfav");
Meteor.subscribe("LinkLike");
Meteor.subscribe("LinkComment"); */
$("body").removeClass('home');
this.render('profile');
setTimeout(function(){
$('#username').html(Session.get('first_name'));
$('#profile_username').html(Session.get('first_name'));
$('#setting_name').val(Session.get('first_name'));
$('#setting_username').val(Session.get('first_name'));
$('#setting_email').val(Session.get('email'));
$('#user_id').val(Session.get('id'));
$('.setting_day').val(Session.get('day'));
$('.setting_month').val(Session.get('month'));
$('.setting_year').val(Session.get('year'));
if(Session.get('image')!= ''){
$('.user_profile_image').attr("src",Session.get('image'));
}
if(Session.get('gender') == 0){
$('#user_gender').html('Male');
}else{
$('#user_gender').html('Female');
}
$('#day').html(Session.get('day'));
$('#month').html(Session.get('month'));
$('#year').html(Session.get('year'));
},100);
},onBeforeAction:function(){
if(Session.get('email')){
this.next();
}else {
//this.next();
this.redirect('/');
}
}
});
When you refresh/reload the page Session values are get undefined. You can get the current user email using meteor.user(). You just have to replace you session.get('email') like this.
var user_email = {};
user_email.mail = Meteor.user().emails[0].address;
I hope that is what you are looking for.

MeteorJS: Collection.find fires multiple times instead of once

I have an app that when you select an industry from a drop down list a collection is updated where the attribute equals the selected industry.
JavaScript:
Template.selector.events({
'click div.select-block ul.dropdown-menu li': function(e) {
var selectedIndex = $(e.currentTarget).attr("rel");
var val = $('select#industryPicker option:eq(' + selectedIndex + ')').attr('value');
var oldVal = Session.get('currentIndustryOnet');
if(val != oldVal) {
Session.set('jobsLoaded', false);
Session.set('currentIndustryOnet', val);
Meteor.call('countByOnet', val, function(error, results){
if(results > 0) {
Session.set('jobsLoaded', true);
} else {
getJobsByIndustry(val);
}
});
}
}
});
var getJobsByIndustry = function(onet) {
if(typeof(onet) === "undefined")
alert("Must include an Onet code");
var params = "onet=" + onet + "&cn=100&rs=1&re=500";
return getJobs(params, onet);
}
var getJobs = function(params, onet) {
Meteor.call('retrieveJobs', params, function(error, results){
$('job', results.content).each(function(){
var jvid = $(this).find('jvid').text();
var job = Jobs.findOne({jvid: jvid});
if(!job) {
options = {}
options.title = $(this).find('title').text();
options.company = $(this).find('company').text();
options.address = $(this).find('location').text();
options.jvid = jvid;
options.onet = onet;
options.url = $(this).find('url').text();
options.dateacquired = $(this).find('dateacquired').text();
var id = createJob(options);
console.log("Job Created: " + id);
}
});
Session.set('jobsLoaded', true);
});
}
Template.list.events({
'click div.select-block ul.dropdown-menu li': function(e){
var selectedIndex = $(e.currentTarget).attr("rel");
var val = $('select#perPage option:eq(' + selectedIndex + ')').attr('value');
var oldVal = Session.get('perPage');
if(val != oldVal) {
Session.set('perPage', val);
Pagination.perPage(val);
}
}
});
Template.list.jobs = function() {
var jobs;
if(Session.get('currentIndustryOnet')) {
jobs = Jobs.find({onet: Session.get('currentIndustryOnet')}).fetch();
var addresses = _.chain(jobs)
.countBy('address')
.pairs()
.sortBy(function(j) {return -j[1];})
.map(function(j) {return j[0];})
.first(100)
.value();
gmaps.clearMap();
$.each(_.uniq(addresses), function(k, v){
var addr = v.split(', ');
Meteor.call('getCity', addr[0].toUpperCase(), addr[1], function(error, city){
if(city) {
var opts = {};
opts.lng = city.loc[1];
opts.lat = city.loc[0];
opts.population = city.pop;
gmaps.addMarker(opts);
}
});
})
return Pagination.collection(jobs);
} else {
jobs = Jobs.find()
Session.set('jobCount', jobs.count());
return Pagination.collection(jobs.fetch());
}
}
In Template.list.jobs if you console.log(addresses), it is called 4 different times. The browser console looks like this:
(2) 100
(2) 100
Any reason why this would fire multiple times?
As #musically_ut said it might be because of your session data.
Basically you must make the difference between reactive datasources and non reactive datasources.
Non reactive are standard javascript, nothing fancy.
The reactive ones however are monitored by Meteor and when one is updated (insert, update, delete, you name it), Meteor is going to execute again all parts which uses this datasource. Default reactive datasources are: collections and sessions. You can also create yours.
So when you update your session attribute, it is going to execute again all helper's methods which are using this datasource.
About the rendering, pages were rendered again in Meteor < 0.8, now with Blaze it is not the case anymore.
Here is a quick example for a better understanding:
The template first
<head>
<title>test</title>
</head>
<body>
{{> hello}}
</body>
<template name="hello">
<h1>{{getSession}}</h1>
<h1>{{getNonReactiveSession}}</h1>
<h1>{{getCollection}}</h1>
<input type="button" name="session" value="Session" />
<input type="button" name="collection" value="Collection" />
</template>
And the client code
if (Meteor.isClient) {
CollectionWhatever = new Meteor.Collection;
Template.hello.events({
'click input[name="session"]': function () {
Session.set('date', new Date());
},
'click input[name="collection"]': function () {
CollectionWhatever.insert({});
}
});
Template.hello.getSession = function () {
console.log('getSession');
return Session.get('date');
};
Template.hello.getNonReactiveSession = function () {
console.log('getNonReactiveSession');
var sessionVal = null;
new Deps.nonreactive(function () {
sessionVal = Session.get('date');
});
return sessionVal;
};
Template.hello.getCollection = function () {
console.log('getCollection');
return CollectionWhatever.find().count();
};
Template.hello.rendered = function () {
console.log('rendered');
}
}
If you click on a button it is going to update a datasource and the helper method which is using this datasource will be executed again.
Except for the non reactive session, with Deps.nonreactive you can make Meteor ignore the updates.
Do not hesitate to add logs to your app!
You can read:
Reactivity
Dependencies

Drag and drop file upload (knockout + webapi + asp.net)

I am looking for Drag And Drop File Upload component, using Knockout + .NET WebApi technologies.
I have found File Api project, it doesn't support old browsers, but I can live with it. The code is here: https://github.com/khayrov/khayrov.github.com/tree/master/jsfiddle/knockout-fileapi.
It creates custom Knockout Bindings, some code parts:
HTML:
<input type="file" accept="image/*" data-bind="file: imageFile, fileObjectURL: imageObjectURL, fileBinaryData: imageBinary"/>
Knockout JS:
ko.bindingHandlers.file = {
init: function(element, valueAccessor) {
$(element).change(function() {
var file = this.files[0];
if (ko.isObservable(valueAccessor())) {
valueAccessor()(file);
}
});
},
update: function(element, valueAccessor, allBindingsAccessor) {
var file = ko.utils.unwrapObservable(valueAccessor());
var bindings = allBindingsAccessor();
if (bindings.fileObjectURL && ko.isObservable(bindings.fileObjectURL)) {
var oldUrl = bindings.fileObjectURL();
if (oldUrl) {
windowURL.revokeObjectURL(oldUrl);
}
bindings.fileObjectURL(file && windowURL.createObjectURL(file));
}
if (bindings.fileBinaryData && ko.isObservable(bindings.fileBinaryData)) {
if (!file) {
bindings.fileBinaryData(null);
} else {
var reader = new FileReader();
reader.onload = function(e) {
bindings.fileBinaryData(e.target.result);
};
reader.readAsArrayBuffer(file);
}
}
}
Unfourtunately I do not understand if I can reuse this code and integrated it within some Drag And Drop File upload component?
Is there any existing DnD file upload component that can be used with knockout + webapi?
See this http://jsfiddle.net/3LT9d/
function noopHandler(evt) {
evt.preventDefault();
return false;
}
ko.bindingHandlers.dropUpload = {
init: function (element, valueAccessor, allBindings, viewModel, bindingContext) {
element.addEventListener('dragenter', noopHandler, false);
element.addEventListener('dragover', noopHandler, false);
element.addEventListener('drop', function (evt) {
evt.preventDefault();
var value = valueAccessor();
for (var i = 0; i < evt.dataTransfer.files.length; i++) {
value.push(evt.dataTransfer.files[i]);
}
}, false);
}
};
How it works:
The dropUpload custom binding populates an observable array with the dragged files
To upload the files, the new API FormData is used since backward compatibility seems to be not an issue. FormData is easier to work with.
Follow this article to find out how to allow your webapi to accept FormData
http://www.asp.net/web-api/overview/working-with-http/sending-html-form-data,-part-2

XML Parsing using JavaScript

Here's an XML snippet:
<appSettings>
<add key="val1" value="val2"/>
The XML document is loaded in memory, ready to be parsed.
How would you get and write the value of "val2" to the web page?
Thanks,
rodchar
Post Comments:
I'm getting .selectSingleNode is not a function:
<script type="text/javascript">
if (window.XMLHttpRequest)
{
xhttp=new window.XMLHttpRequest()
}
else
{
xhttp=new ActiveXObject("Microsoft.XMLHTTP")
}
xhttp.open("GET","test.xml",false);
xhttp.send("");
xmlDoc=xhttp.responseXML;
var node = xmlDoc.selectSingleNode("/appSettings/add[#key='Key']");
alert(node.getAttribute("value"));
</script>
Use jQuery, it's so much nicer.
$(request.responseXML).find("add").each(function() {
var marker = $(this);
var key = marker.attr("key");
var value = marker.attr("value");
});
Try this:
var node = xmlDoc.selectSingleNode("/appSettings/add[#key='val1']");
alert(node.getAttribute("value"));
var xmlDoc;
if (typeof DOMParser !== 'undefined') {
xmlDoc = (new DOMParser).parseFromString(xmlText, 'text/xml');
} else {
xmlDoc = new ActiveXObject('Microsoft.XMLDOM');
xmlDoc.async = 'false';
xmlDoc.loadXML(xmlText);
}

How to make a dropdownlist disabled on change event using JQUERY?

$(document).ready(function() {
$('#<%=ddlContinents.ClientID %>').change(function() {
var element = $(this);
var totalLength = element.children().length;
if ($(this).disabled == false) { $(this).disabled = true; }
});
});
What I am trying to do is fire off the change event of the dropdownlist and on change making this dropdownlist disabled. The code is firing and everything, but it does not disable the dropdownlist.
This portion of the code is not working:
if ($(this).disabled == false) { $(this).disabled = true; } });
You should use .prop() for jQuery 1.6+ or .attr() for earlier versions of jQuery:
> jQuery 1.6:
$(document).ready(function() {
$('#<%=ddlContinents.ClientID %>').change(function() {
var element = $(this);
var totalLength = element.children().length;
if (!$(this).prop("disabled")) {
$(this).prop("disabled", true);
}
});
});
< jQuery 1.6:
$(document).ready(function() {
$('#<%=ddlContinents.ClientID %>').change(function() {
var element = $(this);
var totalLength = element.children().length;
if (!$(this).attr("disabled")) {
$(this).attr("disabled", "disabled");
}
});
});
if (!$(this).attr("disabled")) { $(this).attr("disabled","disabled"); }
If you want to enable it later on, you gotta do:
$(this).removeAttr("disabled");
I know this post is old..This might help if anyone stuck with disabling dropdown on dropdown chnage function
if ($(this).attr('disabled', false))
{ $(this).attr('disabled', true);
}

Resources