I have this block of code where I'm creating two link elements on a web page and adding a click event to them:
function createNewChat(){
//alert("new chat fired");
var roomName = document.getElementById("roomName").value
if (roomName){
resetErrorLog();
$('#createRoom').append('<p>would you like to password protect this room?</p>');
$('#createRoom').append('<div> yes </div>');
$('#createRoom').append('<div> no </div>');
}
else {
document.getElementById("errorlog").innerHTML = "<p>The room name input box seems to be empty</p>";
}
}
The DOM updates properly, but when I click the link I get an unexpected token } on line 2, which is an tag. This block of code is much later in the file. The helper method isn't getting fired at all so I'm pretty sure that the problem is with this code. Help is much appreciated.
onclick="newChatHelper("yes")" is a quoting issue in the HTML
You need to use onclick="newChatHelper('yes')" — notice the single quotes within the function call
But because you already have this in a single quote, you need to escape the inner single quotes, like this:
'<div> no </div>'
You could also consider not using the onclick attribute at all
$('#createRoom').append(
$('yes').click(function(event) {
newChatHelper("yes");
event.preventDefault();
}).wrap('<div/>').parent()
);
OR
$('#createRoom').append(
$('<div></div>').append(
$('yes').click(function(event) {
newChatHelper("yes");
event.preventDefault();
})
)
);
var roomName = document.getElementById("roomName").value
you may want to close this up with a ;
var roomName = document.getElementById("roomName").value;
var roomName = document.getElementById("roomName").value
by
var roomName = document.getElementById("roomName").value;
Related
I am developing a mobile application. I need to show an array in a list on my html. I have a function in an external .js file which returns an array with JSON data retrieved.
This is my function in javascript:
function getnames() {
var url = api + "/name";
$.getJSON(url).done(function (answer) {
if (!answer.length) {
console.warn("Empty list");
}
api.name = response;
for (i = 0; i < response.length; i++) {
$('#names').html(api.name[i].name);
}
}).fail(function (data, status, error) {
console.error("Something went wrong");
});
}
This is the html list I want them to be displayed in:
<div>
<div class="widget-container">
<div class="list-group">
<a>
<h4 id="names">
<script type="text/javascript">
window.onload = function () {
getnames();
};
</script>
</h4>
</a>
this is repeated 4 times.I have 4 headings meaning i need for 4 names which is as much the array returns
</div>
</div>
</div>
The list i would like to display them in is a menu from a panel. The code I have only shows me the last name for some reason.
$('#names').html(api.name[i].name); // You are overwriting with each loop
Try:
$('#names').append(api.name[i].name);
If I understand correctly, you want to generate a h4 tag for each of the array elements.
Some issues in your code:
There is no use in putting your script tag at the place where you want to inject data. Just place it just before the closing </body> tag or else in the <head> tag;
Don't use window.load. There are specific cases where it could be useful, but not in your case. Instead use the DOMContentLoaded event, or, as you use jQuery, the equivalent .ready() method;
You name the JSON response argument answer, but then start referring to response: obviously you should stick to the same variable name;
You assign multiple times HTML to the same element #names, so that you overwrite the previous value and are left with the last value only;
You use the html method for an argument that is pure text. This is not advised, as you can get problems with text that contains < or & characters, as they have a special meaning in HTML. Instead you should use .text();
You use the api variable in strange ways. First it seems to be a string (in url = api + "/name"), and then later you assign to its name property. Although this can work, it makes your code obscure. If it really is an object, then the first statement will be equal to url = api.toString() + "/name";
The code never adds another h4 element, which seems to be what you want. For that to happen you could generate the necessary h4 elements dynamically.
Here is the code adapted accordingly, which makes use of a fake JSON provider:
var api = 'https://jsonplaceholder.typicode.com';
function getnames() {
var url = api + "/posts"; // change to "/name"
$.getJSON(url).done(function (response) {
if (!response.length) {
console.warn("Empty list");
}
$.map(response, function(item) {
$('.list-group').append($('<h4>').text(item.title)); // change to item.name
});
}).fail(function (data, status, error) {
console.error("Something went wrong");
});
}
$(function() {
getnames();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.3/jquery.min.js"></script>
<div>
<div class="widget-container">
<div class="list-group">
</div>
</div>
</div>
One thing to avoid when working with HTML content is repeated updates: each time you update the DOM, the browser checks if it needs to update the display, and potentially kicks off a load of recalculations, repaints and other expensive processes. It's much better, if you can, to build up the content you want to update, and then insert it into the DOM in one step, like this:
function getnames() {
var url = api + "/name";
$.getJSON(url).done(function (answer) {
if (!answer.length) {
console.warn("Empty list");
}
// jQuery map gives you a new array of the returned values:
names = $.map(answer, function(e){
return e.name;
});
// Join turns the array into a string, separated with ', '
$('#names').html(names.join(', '));
}).fail(function (data, status, error) {
console.error("Something went wrong");
});
}
This code takes the answer from the getJSON call, and transforms it into an array of just the name properties. Join then turns it into a comma separated string, which is passed the the html method on #names.
I hope that's clear enough - let me know if it makes sense!
Im making WYSIWYG editor for web magazine with Riot.js.
I want to disply instagram image with delete icon when I click add button and delete instagram image when I click delete icon.
I can disply instagram image with delete icon but cant delete them because function killMedia doesnt work.
When I click delete icon, I get this error message.
Uncaught ReferenceError: killMedia is not defined
Im working on below code.
Does anyone know what problem is?
<div id='body-text' class='body-text' contenteditable=true data-placeholder='Body Contents'></div>
<label>
<input type='text' name='instagram' placeholder='Input Instagram embed code'>
<button onclick={ addInstagram }>add</button>
</label>
<script>
addInstagram(e) {
var embedCode = this.instagram.value
var instagram = document.createElement('div')
instagram.setAttribute('class', 'media-frame')
instagram.setAttribute('show', '{showMedia}')
instagram.innerHTML = embedCode
var i = document.createElement('i')
i.setAttribute('id', 'media-killer')
i.setAttribute('class', 'fa fa-times-circle-o media-killer')
i.setAttribute('aria-hidden', 'true')
i.setAttribute('show', '{showMedia}')
i.setAttribute('onclick', '{killMedia}')
var target = document.getElementById('body-text')
instagram.appendChild(i)
target.appendChild(instagram)
this.instagram.value = ''
this.update()
this.modal = false
}
this.showMedia = true
killMedia(e) {
this.showMedia = false
this.update()
}
</script>
The syntax you are using to define the function killMedia is incorrect. It seems like Riot.js has some alternative syntax for event handlers, which is why it works for addInstagram.
There are several ways to properly declare and define a function in JavaScript. One would be:
// declare variable killMedia and assign a function to it
var killMedia = function( e ){
this.showMedia = false;
this.update();
}
Also, I don't know anything about how Riot.js will call event functions, so, since you are using this inside your killMedia function, you may need to bind the proper this to the function as you declare it. One way to do this is with the bind function:
// declare variable killMedia and assign a function to it
var killMedia = function( e ){
this.showMedia = false;
this.update();
}.bind( this );
If the syntax is not the problem and Riot.js is handling the special declaration of killMedia, you may just need to declare killMedia before addInstagram, i.e. move that function above addInstagram. This is just a guess, since I don't know anything about Riot.js.
I added this as a comment but now I had time to implement this.
I think that is not working because you are trying to load the elements dynamically so is not compiled by Riot compiler.
A more Riot.js way to do what you want is to build another tag called instagram_image that you can remove, and have an array to iterate the images in the parent tag.
I simplified your code, but the idea is this:
(here is the plunker version http://plnkr.co/edit/EmkFhq0OyVtwSNIJqeJF?p=preview)
<my-tag>
<span each={img in instagram_images} >
<instagram_image embed_code={img.embed_code}></instagram_image>
</span>
<label>
<input type='text' name='instagram' placeholder='Input Instagram embed code'>
<button onclick={ addInstagram }>add</button>
</label>
<script>
this.instagram_images = []
addInstagram(e) {
var instagram_image = {embed_code: this.instagram.value}
this.instagram_images.push(instagram_image)
this.instagram.value = ''
}
</script>
</my-tag>
<instagram_image>
<div onclick={remove}>
{opts.embed_code}
</div>
<script>
this.remove = function() {
this.unmount()
this.update()
}
</script>
</instagram_image>
It's a pretty simple trick that I thought should work fine however it doesn't. So I have multiple checkboxes on the page. And whenever they are changed I would like to record any change to the database. So in the view event 'click' on checkbox I have similar to this:
var filter_name = $(e.target).attr("name");
var filter_value = $( "input:checkbox[name=" + filter_name + "]:checked" ).map(function () {
return this.value;
}).get();
console.log("filter_name: " + filter_name); #=> my_method_name
CarInsuranceApp.aciq.set({filter_name: filter_value});
CarInsuranceApp.aciq.save();
And here the results that I receive as a JSON:
"filter_name"=>"extra"
So my question would be how to dynamically pass model attribute name on the set?
use like this.
CarInsuranceApp.aciq.set(filter_name, filter_value);
Here is a possible one line JavaScript`ish solution:
CarInsuranceApp.aciq.attributes[filter_name] = filter_name;
I am quite new with CKEditor (starting to use it 2 days ago) and I am still fighting with some configuration like removing the tag from editor.
So for example, if a user type in source mode the following:
<script type="text/javascript">alert('hello');</script>
I would like to remove it.
Looking the documentation, I found that this can be done using an HTML filter. I so defined it but it does not work.
var editor = ev.editor;
var dataProcessor = editor.dataProcessor;
var htmlFilter = dataProcessor && dataProcessor.htmlFilter;
htmlFilter.addRules(
{
elements :
{
script : function(element)
{
alert('Found script :' + element.name);
element.remove();
},
img : function( element )
{
alert('Found script :' + element.name);
if ( !element.attributes.alt )
element.attributes.alt = 'Cookingfactory';
}
}
});
The img part is working well but not the script one. I guess I missed something. It even does not display the alert message for script.
Any help would be more than welcome :o)
You can use this :
CKEDITOR.replace('editor1', {
on: {
pluginsLoaded: function(event) {
event.editor.dataProcessor.dataFilter.addRules({
elements: {
script: function(element) {
return false;
}
}
});
}
}
});
If you are using CKEditor 4.1 or above, you may use Advanced Content Filter to allow the content you want.
If you are using CKEditor 4.4 or above, there is an easier way. You can use Disallowed Content to filter content you don't like .
config.disallowedContent = 'script';
As I'm having CKEditor 4, I did the next
CKEDITOR.instances.editor1.config.protectedSource.push( /{.*\".*}/g );
It will ignore quotes in smarty curly brackets
This example is simplified a bit, but in my ASP.NET web page in my c#/jquery code I am using a right hand context menu that displays ‘rightMenu’ when a right mouse is clicked.
$(document).ready(function() {
$(".RH_signoffrow td").contextMenu({
menu: 'rightMenu'
},
function(action, el, pos) {
var mykey = getkeyforitem(el);
mykey = "Details|" + mykey;
alert(
'Action: ' + action + '\n\n' +
'Key is: ' + mykey
);
if(action == "details"){
trigger_details_panel(mykey);
}
});
};
//for any td in the right hand side - get its row key
function getkeyforitem(el){
var mykey = $(el).parent().find('.hiddenrowkey').text();
// alert(
// 'Internal getkeyforitem Call' + '\n\n' +
// 'Key is: ' + mykey
// );
return mykey;
};
The callback of the menu passes back the element that was clicked, and that can be used to pull the keydata out of the current table row. Once I have that keydata, I can use it to call the real function I was after:
trigger_details_panel(mykey).
This works fine if I only want to use the right mouse, but I want to include an image in some of the rows, so that when the image is clicked, it produces the same effect,as the right mouse menu selection.
I am not sure how to accomplish that cleanly.
I can include an image that links to javascript in my page…
<asp:ImageButton ID="imgDetails" runat="server" ToolTip="Show Details"
ImageUrl="./images/details.gif" OnClientClick="showdetailsclicked();return
false;"></asp:ImageButton>
But how can I get it to call the code:
getkeyforitem(el);
Or at least know the element (el) it belongs to? It seems like there should be a way to use the (this) pointer to get at what I want - but I don't see it.
Am I just missing a more straightforward way to accomplish the whole problem?
If you replace the line:
var mykey = $(el).parent().find('.hiddenrowkey').text();
with
var mykey = $(el).parents("tr").find('.hiddenrowkey').text();
Then you can use this function to find the hidden rowkey from any element in the row.
Edit after comment:
You were right about using this. I'd probably do something like:
function showdetailsclicked(){ var rowKey = getkeyforitem(this);}
However, Im not sure if theres some issue with ASP, I doubt it, but you never know... You may have to do something like:
<asp:ImageButton ID="imgDetails" runat="server" ToolTip="Show Details"
ImageUrl="./images/details.gif" OnClientClick="showdetailsclicked(this);return
false;"></asp:ImageButton>
function showdetailsclicked(el){ var rowKey = getkeyforitem(el);}
Hope that helps!