How to get options id in other function - javascript

I've the following code:
this.showNotificationcenter = function () {
centerNotification =
$("<div class='notificationbar'> <h2>Notificaties</h2>" +
"<ul></ul></div>");
var fullPage = $(document).find("#fullPage");
fullPage.append(centerNotification);
}
this.center = function (options) {
var notificationsUl = $(centerNotification).find("ul");
notification = $("<li id="+options.id+"><b>" + options.title + "<span class='fa fa-times'></span></b><br />" + options.content + "</li>");
notificationsUl.append(notification);
}
this.removeLi = function () {
var test = $(notification).find("id").val();
}
And I use this code to create a notification:
eformity.notification.center({
title: "Dit is een titel",
content: "Dit is een content",
id: "een",
});
I need to get the options.id in the function removeLi but I've no idea how to. (var test is now undefined) Eventually, I need a click event on the span which will delete that Li. Can someone help me? Thanks in advance.

you should be using attr to find the value of the attribute id.
var test = $(notification).attr("id");

To get Id
var test=$(notification).attr('id');
To replace Id
var test=$(notification).attr('id', 'newId');

Related

Uncaught ReferenceError: clickDone is not defined at HTMLSpanElement.onclick (home.html:1)

In my web app, a user can create a classroom and then it will be save to the firebase database. After that, the newly created classroom and along with the old class will be retrieve and store in the Classroom: as shown in the image
All the classroom on the list can be click and should show the details of it like: Classroom ID, Teacher, Students. But whenever I do that, an error would appear on the console log
This is the code:
var userRef = firebase.database().ref().child('Classes' + '/' + user.uid);
userRef.on('child_added', function(data) {
var roomNames = data.val().TheClass;
var titsNames = data.val().Teacher;
var classD = data.val().ClassID;
var ul = document.createElement('ul');
document.getElementById('myList').appendChild(ul);
var li = document.createElement('li');
ul.appendChild(li);
Object.keys(roomNames).forEach(function(key){
li.innerHTML += '<span
onclick="clickDone(this)">'+roomNames[key]+'</span><ul style="display:none">
<li>Class Id : '+classD[key]+'</li><li>Teacher : '+titsNames[key]+'</li>
</ul>';
});
function clickDone(thisVar){
var is = thisVar.nextSibling.style.display;
if(is == 'none'){
thisVar.nextSibling.style.display = 'initial';
}else{
thisVar.nextSibling.style.display = 'none';
}
}
});
What went wrong? What did I miss? Any help from you would be greatly appreciated.
The function clickDone must be global to be referred during the onclick event. Move the function clickDone outside of all code, after the last line.
AND the "li" must be created inside the loop
TRY THIS
var userRef = firebase.database().ref().child('Classes' + '/' + user.uid);
userRef.on('child_added', function(data) {
var roomNames = data.val().TheClass;
var titsNames = data.val().Teacher;
var classD = data.val().ClassID;
var ul = document.createElement('ul');
document.getElementById('myList').appendChild(ul);
Object.keys(roomNames).forEach(function(key){
var li = document.createElement('li');
ul.appendChild(li);
li.innerHTML += '<span onclick="clickDone(this)">'+roomNames[key]+'</span><ul style="display:none">' +
'<li>Class Id : '+classD[key]+'</li><li>Teacher : '+titsNames[key]+'</li>' +
'</ul>';
});
});
function clickDone(thisVar){
var is = thisVar.nextSibling.style.display;
if(is == 'none'){
thisVar.nextSibling.style.display = 'initial';
}else{
thisVar.nextSibling.style.display = 'none';
}
}

how to do use onclick inside innerhtml

I have craeted a new div and inside the div Idisplay the information about a topic and also a link to read more about the topic, but my onlick funciton is not working it keeps telling that id is not define. How can I pass value thru innerHTML
function displayNews(section, id, title) {
var section = section;
var id = id;
var title = title;
contentDiv.innerHTML = '<div onclick="displayInfo(id, title);">More info</div>';
}
You could make a real element rather than html to optionally do this.
function displayNews(section, id, title) {
var section = section;
var id = id;
var title = title;
var element = document.createElement('div');
element.onclick = function () {
displayInfo(id, title);
};
element.innerHTML = "More info";
//i don't see contentDiv defined, but this shows the operation
contentDiv.appendChild(element);
}
You didn't properly concatenate the values.
This is what you meant to do, I guess:
function displayNews(section, id, title) {
var section = section;
var id = id;
var title = title;
var div = '<div onclick="displayInfo(' + id + ', "' + title + '");">More info</div>';
alert(div);
}
displayNews(1, 2, 3);

How to swap link with data value with javascript or jQuery

How do I swap this:
var message = 'Another hurricane is coming <a contenteditable="false" data-number="23">here</a>. And check out pictures <a contenteditable="false" data-number="43">over there</a>.';
Into this:
message = 'Another hurricane is coming #[23]. And check out pictures #[43].';
What I have so far:
var swap = function(message) {
message.each(function() {
var text = '#[' + $(this).data(number) + ']';
message = $(this).replaceWith(text);
});
return message;
}
Thanks for your help!
This tiny regular expression could fix that for you:
message = message.replace(/<a contenteditable="false" data-number="(\d+)">.+?<\/a>/g, '#[$1]');
Or as the required function:
var swap = function (message) {
return message.replace(/<a contenteditable="false" data-number="(\d+)">.+?<\/a>/g, '#[$1]');
}
A more flexible/dynamic version
message = message.replace(/<a.+?data-number=(?:"|')(\d+)(?:"|').+?<\/a>/g, '#[$1]');
This will work with any amount of attributes of <a> and even accept digits from both data-number="" and data-number=''. Doesn't get more flexible than that. Or does it? :-)
Try
var message = 'Another hurricane is coming <a contenteditable="false" data-number="23">here</a>. And check out pictures <a contenteditable="false" data-number="43">over there</a>.';
var swap = function(message) {
var msg = $.parseHTML(message)
, message = msg[0].textContent
+ "#[" + msg[1].dataset.number + "]"
+ msg[2].textContent
+ "#[" + msg[3].dataset.number + "]";
return message
};
var message = 'Another hurricane is coming <a contenteditable="false" data-number="23">here</a>. And check out pictures <a contenteditable="false" data-number="43">over there</a>.';
var swap = function(message) {
var msg = $.parseHTML(message)
, message = msg[0].textContent
+ "#[" + msg[1].dataset.number + "]"
+ msg[2].textContent
+ "#[" + msg[3].dataset.number + "]";
return message
}; var _message = swap(message); document.write(_message)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
You can create a temp disconnected element and use jQuery selectors to manipulate the HTML in a structured way. This has no DOM overhead and makes processing the HTML very convenient. It will also work if the attributes on the anchors ever differ from the example shown as it does not try to exact match:
Final shorter function version now brought to the top:
JSFiddle: http://jsfiddle.net/xbm2h6aL/5/
var swap = function (message) {
var element = $('<div>').html(message);
var $anchors = element.find('a').each(function () {
$(this).replaceWith("#[" + $(this).data('number') + "]");
});
return element.html();
}
Older versions below:
JSFiddle: http://jsfiddle.net/xbm2h6aL/1/
Note: the display div was purely for testing purposes, to show it worked.
var message = 'Another hurricane is coming <a contenteditable="false" data-number="23">here</a>. And check out pictures <a contenteditable="false" data-number="43">here</a>.'
// create a disconnected div with the content
var element = $('<div>').html(message);
var $anchors = element.find('a');
$anchors.each(function(){
var $a = $(this);
var n = $a.data('number');
$a.replaceWith("#[" + n + "]");
});
$('#result').append(element.contents());
The code can be shortened by a line or two, but I wanted it to be instructional :)
As a function (like the original): http://jsfiddle.net/xbm2h6aL/3/
var message = 'Another hurricane is coming <a contenteditable="false" data-number="23">here</a>. And check out pictures <a contenteditable="false" data-number="43">here</a>.'
var swap = function (message) {
// create a disconnected div with the content
var element = $('<div>').html(message);
var $anchors = element.find('a');
$anchors.each(function () {
var $a = $(this);
var n = $a.data('number');
$a.replaceWith("#[" + n + "]");
});
return element.html();
}
$('#result').append(swap(message));
Here's a code using jQuery native functions and without RegExp:
var message = 'Another hurricane is coming <a data-number="23">here</a>. And check out pictures <a data-number="43">here</a>.';
var swap = function(msg){
var html = jQuery.parseHTML(msg);
var result = '';
$.each(html, function(i, el){
var element = $(el).filter('a');
if(element.length > 0){
var number = element.data('number');
var text = '#[' + number + ']';
result += text;
} else {
result += $(el).text();
}
});
return result;
}
swap(message);
You shouldn't rely on RegExp because you might have several attributes for the HTML elements you're using.
Here's a JSFiddle: http://jsfiddle.net/g3k3ovd4/

Create DOM element with jQuery

I have a function
$(document).ready(function () {
$("#btnhighlight").click(function () {
var htext = $("#txthighlighttext").val();
$("#lstCodelist option").each(function () {
var sp = $(this).text();
var sp1 = sp.split(' ');
$.each(sp1, function (i, l) {
if (l == htext) {
var boldText = "<div style=\"background-color: yellow; display: inline; font-weight: bold;\">" + htext + "</div>";
$(document).append(boldText);
}
});
});
});
});
I updated the code but no luck.
Here in this code I need to create a l has a DOM element to apply color yellow to that.
please can any body help me out how to create a dom element.
Thanks
I didn't understand where does l is in your current code. Anyway, you can create a DOM element with jQuery like this: var myel = $('<div class="someclass"></div>'). Then you can append myel to wherever you want in the DOM using function like .appendTo(), .after(), etc.
EDIT
You seem to be trying to highlight some words inside an <option> element. I have doubts if that is going to work on all browsers, since form elements are a little tricky when it comes to CSS. You can try something like this (untested):
$(document).ready(function () {
$("#btnhighlight").click(function () {
var htext = $("#txthighlighttext").val();
$("#lstCodelist option").each(function () {
var sp = $(this).text();
var re = new RegExp("\\b" + htext + "\\b")
sp = sp.replace(re, '<span class="highlighted">$1</span>', "gi");
$(this).html(sp);
});
});
});
You also need some CSS on your page, defining the style for .highlighted
UPDATE AFTER CHAT
I got something working using a <p> instead of <option>, to rule out the problem of form element styling:
http://jsfiddle.net/GTydh/3/
The updated js (in case fiddle is deleted):
$(document).ready(function () {
$("#btnhighlight").click(function () {
var htext = $("#txthighlighttext").val();
//$("#lstCodelist option").each(function () {
$("p").each(function () {
var sp = $(this).text();
var re = new RegExp("\\b(" + htext + ")\\b")
var sOpen = "<span class='highlight'>";
var sClose = "</span>";
var newhtml = sp.replace(re, sOpen + "$1" + sClose, "gi");
$(this).html(newhtml);
});
});
});
Something like this?
$(document).append($('<div />').css('color', 'yellow'));
That will append a new div with a colour of yellow to the document. If you need to add it to a specific element just use $('#myselector') instead of $(document)
Its quite simple
var newEl = $('<div THE_ATTRIBUTES_YOU_WANT></div>');
$('THE_ELEMENT_YOU_WANT_TO_APPEND_OR_ADD').append(newEl);

How to pass this parameter to this function?

Here is my function:
function updateRecord(id, textEl) {
db.transaction(function(tx) {
tx.executeSql("UPDATE products SET product = ? WHERE id = ?", [textEl.innerHTML, id], null, onError);
});
}
Here is the call:
<span contenteditable="true" onkeyup="updateRecord('+item['id']+', this)">'+
item['product'] + '</span>
I would like to add a parameter to the call so that I can use the function for multiple columns. Here is what I'm trying but it doesn't work:
<span contenteditable="true" onkeyup="updateRecord('+item['id']+', "product", this)">'+
item['product'] + '</span>
function updateRecord(id, column, textEl) {
db.transaction(function(tx) {
tx.executeSql("UPDATE products SET " + column + " = ? WHERE id = ?", [textEl.innerHTML, id], null, onError);
});
}
They should do the exact same thing, I only specified the product column in the call instead of in the function. Is my syntax incorrect, am I missing something?
Edit:
Here is the full function in which the call is located:
// select all records and display them
function showRecords() {
document.getElementById('results').innerHTML = '';
db.transaction(function(tx) {
tx.executeSql("SELECT * FROM products", [], function(tx, result) {
for (var i = 0, item = null; i < result.rows.length; i++) {
item = result.rows.item(i);
document.getElementById('results').innerHTML +=
'<li><span contenteditable="true" onkeyup="updateRecord('+item['id']+', "product", this)">'+
item['product'] + '</span> x</li>';
}
});
});
}
Update: Ok, then the issue only lies in using double quotes for product. Use single quotes and escape them:
document.getElementById('results').innerHTML +=
'<li><span contenteditable="true" onkeyup="updateRecord('+item['id']+', \'product\', this)">' + ...;
But you really should consider to refactor your code. E.g. you could write it like this:
var results = document.getElementById('results');
var container = document.createDocumentFragment();
for (var i = 0, l = result.rows.length; i < l; i++) {
var item = result.rows.item(i);
var li = document.createElement('li');
var span = document.createElement('span');
span.setAttribute('contenteditable', 'true');
span.onkeyup = (function(item) {
return function() {
updateRecord(item['id'], 'product', this);
}
}(item));
span.innerHTML = item['product'];
var a = document.createElement('a');
a.href = '#';
a.onclick = (function(item) {
return function() {
deleteRecord(item['id'])
}
}(item));
a.innerHTML = 'x';
li.appendChild(span);
li.appendChild(a);
container.appendChild(li);
}
results.appendChild(container);
It is more code but easier to maintain in the long run...
You have syntax and quotation issues. This should work:
onkeyup="updateRecord('item[\'id\']', 'product', this)"
But the code seems a bit weird to me. Is this in your actual HTML or are you echoing or printing it? Because
<span...>'+ item['product'] + '</span>
looks weird in HTML. It will literally put '+ item['product'] + ' inside the <span> tag. Please post a more complete version of your code.

Categories