How to print html response (tinymce) in x-editable - javascript

Using x-editable and tinymce to edit a field, however the return value is printed showing the html code (with etc.), when reloading the page it is fine.
example of what is shown when saving the field;
<p>this is a test response</p>
<p> </p>
(instead of)
this is a test response
 
Editable initializations code:
$('.editable').editable('option','validate', function (v) {
if (this.dataset.type == 'textarea') {
return {newValue: tinyMCE.activeEditor.getContent()};
}
});
This is the editable field:
<%= editable #article, :introduction, url: article_update_path(#article), type: 'textarea', onblur: 'ignore' %>
I want it to be showing the "html-output" instead of the html code.

Problem solved:
$('.editable').editable('option','display', function (value, sourceData) {
this.innerHTML = value;
});

Related

Laravel js DataTable: how do I assign a value from js back to the .blade?

I have these rows:
each row is being outputted by the DataTable plugin within app.js
my target is this particular value, ${row.category_id}
let TABLE = $('#categoryList').DataTable({
{ data: 'id', name: 'id', width: '10%', orderable: false, searchable: false,
render: (data, type, row) =>{
let html = "";
if(row.category_name && row.category_name.toUpperCase() !== "GENERAL"){
html += `<ul class="list-inline no-margin">`;
html += `<li class="list-inline-item">
<button type="button" value="${row.category_id}" class="edit_category btn btn-outline-secondary"><i class="fas fa-edit" aria-hidden="true"></i> Edit</button>
</li>`;
html += `</ul>`;
}
return html;
}
}
});
now I have this blade file, index.blade.php that is connected to app.js using:
<script src="{{asset('/modules/bbr-category-configuration/js/app.js')}}"></script>
What I need to resolve is the constant below:
#section('scripts')
<script type="text/javascript">
const SELECTED_CATEGORY_ID = 1;
</script>
#endsection
by default it is set as 1, but this needs to changed each time the 'Edit' button is clicked (refer to the screenshot). Once the button is clicked, I need to get ${row.category_id} and assign it to the const SELECTED_CATEGORY_ID. What is the correct way of doing this?
TLDR: how do I pass a value from .js back to .blade.php?
What I tried:
my first obstacle is to get the value from ${row.category_id} on click, but here is where I got stuck
$(document).on('click', '.edit_category', function () {
console.log(${row.category_id});
});
I cannot console.log (to test if I got the correct variable) outside the DataTable because it cannot be read, or do it inside toe columns because it is not the right syntax.
please feel free to ask for any clarifications.
First of all, if your variable's data will change during the process then it is not const it should be declared as let. You should know the difference between var let and const.
And you can use data-* attributes in the edit button so you can easily fetch the category_id when that button is clicked eg:
<button type="button" data-category=`${row.category_id}`class="edit_category">Edit</button>
Then on click event, you can get that data using
$('.edit_category').click(function (e) {
SELECTED_CATEGORY_ID = $(this).data('category');
});
You can fetch the value attribute of the button too using jquery. But generally, I don't use that. Or I haven't seen much usage of that too. You can try it like this too
$('.edit_category').click(function (e) {
SELECTED_CATEGORY_ID = $(this).value;
});

Return and refresh select option value on closest tr

I have the below sample code:
<table id='myTable'>
<tr>
<td>Id</td>
<td>Status</td>
<td>Summary</td>
</tr>
</table>
//Sample document ready function
$(document).ready(function(){
$('#myTable').dataTable({
"aoColumnDefs": [
{
"aTargets":[1],
"createdCell": function (td, cellData, rowData, row, col){
if(cellData === 'ordered')
$(td).css('background-color', '#5cb85c');
if(cellData === 'not_ordered')
$(td).css('background-color', '#d9534f');
if(cellData === 'shipped')
$(td).css('background-color', '#f0ad4e');
}
},
{
"aTarget": [2],
"render": function(data, type, full, meta){
if(type === 'display' && data == null) {
data = "enter field summary";
return '<input type="text"' + data +'>';
}
else
return '<input type="text"' + data + '>';
}
}
]
});
//With this function, i want to change the background-color of select field per option selected.However, the val() is returning "undefined"
$('#myTable').on('change',function(){
var optionField = $(this).closest('tr').find('option:selected').val();
if(optionField === 'ordered')
$(this).css({'background-color':'#696969'});
else if(optionField === 'notOrdered')
$(this).css({'background-color':'#e7e7e7'});
else(optionField === 'shipped')
$(this).css({'background-color':'#326f3a'});
}
$('table').on('click', 'input[type="submit"]', function(e)){
var url = 'hiddenAPI.com';
$.ajax({
url: url,
type: "POST",
async: true,
data: {
id: idField,
status: statusField,
summary: summaryField
},
dataType: "json",
success: function (data){
$('#responseField').html('Order ' + idField + ', summary has been posted to the database successfully');
$('#myTable').ajax.reload(); //<- table not refreshing here
},
});
});
});
With the above code, I want to change the background color everytime a select option is selected (determined per value in the code above), also after every post to the database, I want to refresh the whole datatable with the new JSON data. So far the API provided on the datatable site (table.ajax.reload()) isn't working.
Two questions,
1.) With my code above, how can I change the background color of a specific column in datatable after select option is selected?
2.) How do I refresh datatable after every post to the database without having to refresh the entire window/page?
In here:
$(this).css({background-color':'#696969'});
else if(optionField === 'notOrdered')
$(this).css({background-color':'#e7e7e7'});
else(optionField === 'shipped')
$(this).css({background-color':'#326f3a'});
}
the "background-color" string is missing an extra ' at the start
edit: sorry, only fixed a syntax error
After playing around, I ended up fixing this myself.
1.) to refresh ajax data, I ended up calling another ajax call (from another primary function) inside the done function.
2.) to click and return the closest selected option in a table row, I ended up first creating an on click function on the table, and then nested another function for the select on change, then used $(this).closest('tr).find('select').val().

Updating an ArrayAttribute with ReactJs

EDITED:
renamed shouldComponentUpdate to onClick
I'm using Ruby on Rails with the gem react-rails. The idea is to use a "PATCH" method to update an ArrayAttribute but using just JavaScript. To be clear, I'm still a newbie building a project while learning.
The story is, when a user checks a checkbox, it marks their post as complete. Their Post's table has a column for is_complete: :boolean, :default => false. Im using Postgres for the database.
var Foo = React.createClass({
getInitialState: function() {
return {
is_complete: this.props.data.is_complete, # shows "Empty object"
# is_complete: this.props.data[0].is_complete ..... shows "false"
# I could not use that because data[0] and data[1] etc...
}
},
onClick: function(){
var newVal = this.state.is_complete;
this.setState({
is_complete: React.addons.update(this.state.is_complete, { '$set': [ newVal ] })
})
},
render: function() {
var supports = (s) => (
<input type="checkbox" onChange={this.onClick}
/> Mark complete
);
return (
<div>
{this.props.data.map(supports)}
</div>
);
}
});
Index.html.erb:
<%= react_component('Foo', { data: #userlist }) %>
controller:
#userlist = #user.supports.as_json(:only => [:is_complete] # shortened for emample
When the checkbox is checked I get Uncaught TypeError: Cannot read property of is_complete of undefined
I'm looping through all of that user's posts (supports) and outputting the result on one page with a checkbox to mark as complete. I could achieve something similar by adding the chechbox inside of the edit page but I don't want that.
After the edit, I'm not getting the result I want. I want when checked, Array[1] and [2]'s is_complete is set to true or false.
Somehow I need to loop the getInitialState(), is that possible? I see not documentation on that.

Parse Markdown into HTML in JavaScript X-Editable field

I am using the jQuery X-Editable edit-in-place library on a field and the JavaScript Marked Markdown Parser library to try and convert Markdown strings into HTML.
The goal is to show HTL and when it turns into a textarea edit field, to then how the Markdown. The Markdown will be what is saved and loaded from the backend in the live app.
I have setup a JSFiddle demo for this functionality...
http://jsfiddle.net/jasondavis/bfrrzz8h/
If you view the demo and click to edit the Description text and paste in this Markdown string # Marked in browser\n\nRendered by **marked** and click save, it will then alert you the parsed markdown to HTML string. THe problem is it does not update the DOM to show that new HTML string.
Any help in this please?
Marked library - https://github.com/chjj/marked
X-Editable library - https://github.com/vitalets/x-editable/
JavaScript from my demo
$('#task-description-modal').editable({
type: 'textarea', // text|textarea|select|date|checklist
url: '/updatetask',
pk: 123,
toggle: 'click', // click|dblclick|mouseenter|manual
inputclass: 'task_description resizable',
highlight: '#F1FFE7',
mode: 'inline', // inline | popup
placement: 'top',
title: 'Enter Task Description',
validate: function(value) {
if ($.trim(value) === '') {
return 'Task Description is Required';
}
},
params: function(params) {
//Addition params in addition to the default: pk, name, value
return params;
},
success: function(response, newValue) {
if (!response.success) return response.msg;
}
});
$('#task-description-modal').on('save', function(e, params) {
// Parse Description Markdown into HTML
var markdownDescription = marked(params.newValue);
alert(markdownDescription);
$('#task-description-modal').html(markdownDescription);
//$('#task-description-modal').html('test');
});
//ajax emulation. Type "err" to see error message
$.mockjax({
url: '/updatetask',
responseTime: 400,
response: function(settings) {
if(settings.data.value == 'err') {
this.status = 500;
this.responseText = 'Validation error!';
} else {
this.responseText = '';
}
}
});
You're injecting your compiled HTML into the element you're using to get markdown input. This is simply setting yourself up for failure: have two elements, one for markdown text, and one to show the result, and switch between the two.
For instance, the following code already makes things work fine:
HTML:
<div style="margin: 50px">
<span id="task-description-modal">Task Description text</span>
<div id="processed"></div>
</div>
JS:
$('#task-description-modal').on('save', function(e, params) {
var markdownDescription = marked(params.newValue);
$('#processed').html(markdownDescription);
});
You just need to make sure to only show the element you intend to be shown depending on what the user has just done. Hidden #task-description-modal until the user clicks on #processed, at which point you hide #processed and force .focus() on #task-description-modal? Perfect.

use jquery variable in # block razor

I'm strugling with a jquery script inside a cshtml page. For short my question is how to use a var inside a # statement in a cshtml page?
below an example of what I'm trying:
<select id="DefaultText">
<option value="-1">-- select --</option>
#foreach( var d in Model.DefaultTexts )
{
<option value="#d.Id" >#d.Name</option>
}
</select>
<script type="text/javascript">
$('#DefaultText').change(function () {
var id = parseInt($('#DefaultText :selected').val());
var text = #Model.DefaultTexts.First( t => t.Id == id );
$('#CustomProductText').val(text);
});
</script>
I can't reach the var id. It's out of scope. I've also tryed it with a for loop and a if statement. But in the if statement I get the same error: out of scope.
The full story is this:
On my page I've a dropdown list. The items to select are short names for default text parts. Based on the id or name, I want to show the default text part in a textbox.
#CustomProductText is my textbox where the content should be placed (code not posted).
I've also tryed it with #: and statement but that did not work.
What am I doing wrong or maybe its not even possible what I'm trying to do.
As an alternative I've added a action to my controller to get the text form there. Below the code:
<script type="text/javascript">
$('#DefaultText').change(function () {
var id = parseInt($('#DefaultText :selected').val());
$.post("Categories/GetDefaultText", { Id: id }, function (data) {
alert(data);
});
//$('#CustomProductText').val(text);
});
</script>
controller code:
[HttpPost]
public ActionResult GetDefaultText(int id)
{
using( var context = new MyContext() )
{
var text = context.DefaultText.First( d => d.Id == id ).Text;
return this.Content( text );
}
}
This doesn't work. The action doesn't get hit in debug mode.
regards,
Daniel
The $.post that is not working for you, you should prefix the url with / sign and it will be hit as expected:
$.post("/Categories/GetDefaultText", { Id: id }, function (data) {
alert(data);
});
As for the razor solution, you can't use javascript variables in the razor code as it's not a scripting language. What razor does is simply rendering the strings (be it html or javascript or anything) into the page.
To do what you want you either need to request the server to pass the text to your page or render all the texts you have in the page and then access this rendered content in your javascript.

Categories