create jquery components using a function and using them in the HTML - javascript

I want to create some jquery components using a function and use them in the html, but dont know how to do it. Here's what i've attempted.
function CreateElement (id, type) {
$(document).ready (function () {
if (type == "metricCombobox") {
var element = $('#' + id).combobox();
return element;
}
});
}
And in the HTML page.
<select id="' + CreateElement('metricComboboxSimples', 'metricCombobox') + '" >

You really need to create the element in the DOM and then append things to it?
Or can you create all elements in the jQuery? Creating in jQuery, at least for me, is easier to understand, you can control the entire creation of the element and then append it to another element that is already in the DOM or even to the document.body... please, take a look at the code below and run the snippet to see if my answer helps you.
var selectOptions= [
{val : 1, text: 'One'},
{val : 2, text: 'Two'},
{val : 3, text: 'Three'}
];
function CreateElement (id, type, options) {
$(document).ready (function () {
if (type == "metricCombobox") {
var arr = options;
var element = $('<select>');
element.attr('id', id);
$(arr).each(function() {
var selOption = $("<option>");
selOption.attr('value', this.val);
selOption.text(this.text);
element.append(selOption);
});
}else if (type == 'input'){
var element = document.createElement('input');
element.value = 'input created'
$(element).attr('id',id);
}
$("#MyDiv").append(element);
});
}
CreateElement('metricComboboxSimples', 'metricCombobox', selectOptions);
CreateElement('testeId', 'input');
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="MyDiv"></div>

Related

$(window).bind("load") and $(element).html in pure javascript

I am trying to change this jquery to pure javascript:
var subContainerElement = $('#' + mainContainerId).find('#' + subContainer);
$(window).bind("load", function () {
$(subContainerElement).html(function (index, text) {
newParagraphText = text.replace("aaa", "bbb");
return newParagraphText;
});
});
Javascript:
var subContainerElement = mainContainer.getElementsByClassName(subContainer)[0];
document.addEventListener("DOMContentLoaded", function(event) {
mainContainer.getElementsByClassName(subContainer)[0].innerHTML =
function (index, text) {
newParagraphText = text.replace("aaa", "bbb");
return newParagraphText;
};
});
Unfortunately, the innerHTML function set the html of the element to be:
function (index, text) { ......
Any help appreciated.
In the jQuery based code, you're looking for an element whose id is subContainer.
Assuming it works, the second one should be
var subContainerElement = document.getElementById(subContainer);
document.addEventListener("DOMContentLoaded", function(event) {
var html = subContainerElement.innerHTML;
html = html.replace("aaa", "bbb");
subContainerElement.innerHTML = html;
});
Note that the first code is very bad, with a very strange element selection and an undeclared variable.

Bind function with parameters to dynamically created element of dynamically added event

My question is little bit confuse. I created comment box to post comments in javascript. I am posting every comment using javascript by creating dynamically created elements, attributes and event handlers.
Javascript:
var commentSubmit = document.getElementById("commentSubmit"),
commentBox = document.getElementById("commentBox"),
deleteComment = document.getElementById("deleteComment"),
commentList = document.getElementById("commentList");
function getDataFromLocalStorage(){
var i = 0,
cArr = [],
cKey;
for (; cKey = window.localStorage.key(i); i++) {
var cObj = {};
cObj.cId = cKey;
cObj.cText = window.localStorage.getItem(cKey);
cArr.push(cObj);
}
return cArr;
}
function createElement(name,attr,events,html){
debugger;
var elem = document.createElement(name);
var elemText;
if(html){
for(var i=0;i<html.length;i++){
if(html[i].name == "text"){
elemText = document.createTextNode(html[i].value)
elem.appendChild(elemText);
}else{
elem.appendChild(html[i].value);
}
}
}
if(events){
for(var i=0;i<events.length;i++){
if(events[i]["customFunction"]){
elem.addEventListener(events[i].eventName,events[i]["customFunction"].bind(elem,events[i].eventParams.join(" ")),false);
}
}
}
for(var i=0;i<attr.length;i++){
elem.setAttribute(attr[i].name, attr[i].value);
}
return elem;
}
function deleteComment(cId){
localStorage.removeItem(cId);
loadComments();
}
function loadComments(){
var cComments = getDataFromLocalStorage(),
cTotal = cComments.length;
commentList.innerHTML = "";
if(cTotal){
for(var i=0;i<cTotal;i++){
var deleteCommentButton = createElement("BUTTON",
[
{name:"class",value:"deleteComment"},
{name:"id",value:"deleteComment"},
{name:"value",value:"X"}
],
[
{eventName:"onclick",eventParams:[cComments[i].cId],customFunction:"deleteComment"}
]
);
var commentWrapper = createElement("DIV",
[
{name:"class",value:"commentWrapper"},
{name:"id",value:cComments[i].cId}
],
[
{name:"text",value:cComments[i].cText},
{name:"html",value:deleteCommentButton}
]
);
/*var commentText = document.createTextNode(cComments[i].cText);
commentWrapper.setAttribute("class", "commentWrapper");
commentWrapper.setAttribute("id", cComments[i].cId);
commentWrapper.appendChild(commentText);*/
commentList.appendChild(commentWrapper);
}
}
}
loadComments();
commentSubmit.addEventListener("click", function(e){
var cKey = Date.now();
if(commentBox.value != ""){
localStorage.setItem(cKey,commentBox.value);
loadComments();
}
e.preventDefault();
return false;
}, false);
html:
<div class="commentForm">
<form>
<textarea rows=5 id=commentBox></textarea>
<button id=commentSubmit>Post</button>
</form>
</div>
<div id="commentList">
</div>
my question is
i want to attach deleteComment function to the dynamically created
element. here, i am sending the function name also dynamically. i was
unable to bind function.
here is jsfiddle
thanks in advance.
Don't set the listener to the function name. That's not how it works. Send the function itself:
{eventName:"onclick",eventParams:[cComments[i].cId],customFunction:deleteComment}
Also, depending on what exactly you want, joining the params may also not be what you REALLY want to do.
Additional answer:
Found a bug in your code:
{name:"id",value:"deleteComment"}
You're creating an HTML element (in this case a button) with the same name as a function. This causes the function to be deleted. This is a very weird feature that was introduced by IE that was copied by other browsers for compatibility with IE specific sites. Now it's part of the HTML5 specification :(
To fix this either rename your function or rename the element. See this edit for an example fix: http://jsfiddle.net/pcmyzhqu/10

html to xml conversion using javascript?

Is it possible to convert all div child information into XML or JSON using JavaScript?
$("#droppable").droppable({
drop : function(event, ui) {
var id = $(ui.draggable).attr("id");
var cloneObj = $((ui.draggable).clone());
$(cloneObj).removeClass("draggable ui-draggable");
if (id === "txt") {
inputOBj = document.createElement("input");
inputOBj.setAttribute("id", "txt" + i);
$("#droppable").append(inputOBj);
} else if (id == "combo") {
inputOBj = document.createElement("select");
inputOBj.setAttribute("id", "select" + i);
console.log("");
}
});
I believe you can use XMLSerializer to do this.
var yourString = new XMLSerializer().serializeToString(cloneObj[0]);
there is property called outerHTML.
It Sets or retrieves the object and its content in HTML.
U can use it in following way.
e.g:
$(document).ready(function() {
$('#p').click(function() {
alert($('#p')[0].outerHTML);
});
});
tip: p is your any tag ID in body of page.

Browser compatability issue -NOt working on IE

I have a problem with my work which works good on Firefox and Google Chrome, but it wouldn't work in IE. Can you point out where I'm getting it wrong?
Scripts.js
$(document).ready(function () {
$('.delete').click(function () {
var contentId = $(this).attr('contentid');
$.confirm({
'title': 'Delete Confirmation',
'message': 'Are you sure you want to delete this record?',
'buttons': {
'Yes': {
'class': 'blue',
'action': function () {
DoDelete(contentId);
}
},
'No': {
'class': 'orange',
'action': function () {}
// Nothing to do in this case. You can as well omit the action property.
},
'close': {
'action': function () {}
// Nothing to do in this case. You can as well omit the action property.
}
}
});
});
});
confirmscript to generate HTML markup
(function ($) {
$.confirm = function (params) {
if ($('#confirmOverlay').length) {
return false;
}
var buttonHTML = '';
$.each(params.buttons, function (name, obj) {
buttonHTML += '' + name + '<span></span>';
if (!obj.action) {
obj.action = function () {};
}
});
var markup = [
'<div id="confirmOverlay">',
'<div id="confirmBox">',
'<div id="header">',
'<div id ="title">',
params.title,
'</div></div>',
'<div id ="textbox">',
'<p>',
params.message,
'</p></div>',
'<div id="confirmButtons">',
buttonHTML,
'</div></div></div>'
].join('');
$(markup).hide().appendTo('body').fadeIn();
var buttons = $('#confirmBox .button'),
i = 0;
$.each(params.buttons, function (name, obj) {
buttons.eq(i++).click(function () {
obj.action();
$.confirm.hide();
return false;
});
});
}
$.confirm.hide = function () {
$('#confirmOverlay').fadeOut(function () {
$(this).remove();
});
}
})(jQuery);
Well first off, the first line of your $('.delete') handler is:
var contentId = $(this).attr('contentid');
but your markup for .delete is:
<div class="delete"></div>
(notice the lack of a contentId attribute). Luckily(?) your code doesn't actually seem to use contentId :-)
More relevantly, you need to determine which part of your code is breaking (if you had a JS Fiddle of your code I could look, but since you don't you'll have to find out yourself). I would put an alert just before $.confirm is called, and then again inside $.confirm, to make sure the code is even getting to your plug-in (if not, that's your problem).
If it is, the next question to ask is "is your markup getting added, but not revealed, or is it simply not being added at all". Either alerts or the IE developer tools should let you inspect the DOM and find out if your markup is being added; if not, that's your problem. If it is being added, but isn't getting shown, then something is going wrong with your fadeIn, and that's your problem.
As a final note, there's a simpler way you could hook up your button events; instead of:
var buttons = $('#confirmBox .button'),
i = 0;
$.each(params.buttons, function (name, obj) {
buttons.eq(i++).click(function () {
obj.action();
$.confirm.hide();
return false;
});
});
you could just do:
$('#confirmBox .button').each(function(button) {
$(button).click(function () {
params.buttons[$(this).text()].action();
$.confirm.hide();
return false;
});
});

Add multiple items to text-area with duplicate items

Add multiple items to text-area with duplicate items.
I have one text-area which store data after clicked add data link.
How can i prevent add duplicate items to text-area?
JavaScript call DOM event:
var Dom = {
get: function(el) {
if (typeof el === 'string') {
return document.getElementById(el);
} else {
return el;
}
},
add: function(el, dest) {
var el = this.get(el);
var dest = this.get(dest);
dest.appendChild(el);
},
remove: function(el) {
var el = this.get(el);
el.parentNode.removeChild(el);
}
};
var Event = {
add: function() {
if (window.addEventListener) {
return function(el, type, fn) {
Dom.get(el).addEventListener(type, fn, false);
};
} else if (window.attachEvent) {
return function(el, type, fn) {
var f = function() {
fn.call(Dom.get(el), window.event);
};
Dom.get(el).attachEvent('on' + type, f);
};
}
}()
};
JQuery add data to textarea:
$("#lkaddlanguage").click(function(){
var totalstring;
var checkconstring = $("#contentlng").text();
var strLen = checkconstring.length;
myStr = checkconstring.slice(0,strLen-1);
//alert(myStr);
var checkedItemsArray = myStr.split(";");
var j = 0;
var checkdup=0;
totalstring=escape($("#textval").val()) ;
var i = 0;
var el = document.createElement('b');
el.innerHTML = totalstring +";";
Dom.add(el, 'txtdisplayval');
Event.add(el, 'click', function(e) {
Dom.remove(this);
});
});
HTML Display data
<input type="textbox" id="textval">
<a href="#lnk" id="lkaddlanguage" >Add Data</a>
<textarea readonly id="txtdisplayval" ></textarea>
This seems a very straightforward requirement to me, so I'm not quite clear where you're getting stuck. I have not tried too hard to figure out your existing code given that you are referencing elements not shown in your html ("contentlng"). Also, mixing your own DOM code with jQuery seems a bit pointless. You don't need jQuery at all, but having chosen to include it why then deliberate not use it?
Anyway, the following short function will keep a list of current items (using a JS object) and check each new item against that list. Double-clicking an item will remove it. I've put this in a document ready, but you can manage that as you see fit:
<script>
$(document).ready(function() {
var items = {};
$("#lkaddlanguage").click(function(){
var currentItem = $("#textval").val();
if (currentItem === "") {
alert("Please enter a value.");
} else if (items[currentItem]) {
alert("Value already exists.");
} else {
items[currentItem] = true;
$("#txtdisplayval").append("<span>" + currentItem + "; </span>");
}
// optionally set up for entry of next value:
$("#textval").val("").focus();
return false;
});
$("#txtdisplayval").on("dblclick", "span", function() {
delete items[this.innerHTML.split(";")[0]];
$(this).remove();
});
});
</script>
<input type="textbox" id="textval">
<a href="#lnk" id="lkaddlanguage" >Add Data</a><br>
<div id="txtdisplayval" ></div>
<style>
#txtdisplayval {
margin-top: 5px;
width : 200px;
height : 100px;
overflow-y : auto;
border : 1px solid black;
}
</style>
Note I'm using a div (styled to have a border and allow vertical scrolling) instead of a textarea.
As you can see I've coded it to display an alert for duplicate or empty items, but obviously you could remove that and just ignore duplicates (or substitute your own error handling). Also I thought it might be handy to clear the entry field and set focus back to it ready for entry of the next value, but of course you can remove that too.
Working demo: http://jsfiddle.net/LTsBR/1/
I'm confused.
The only variable that might have duplicates comes from:
var checkedItemsArray = myStr.split(";");
However, checkedItemsArray is not used for anything.
Incidentally, the escape method is deprecated in favour of encodeURIComopnent.
When setting the value of the textarea, do just that: assign to its value property, not to its innerHTML (it can't have markup inside it or any elements, only text nodes).
If you want to check that the members of checkedItemsArray are unique, and you don't mind if they are sorted, you can use a simple function like:
function unique(arr) {
arr.sort();
var i = arr.length;
while (i--) {
if (arr[i] == arr[i - 1]) {
arr.splice(i, 1);
}
}
return arr;
}
Orignal order can be maintained, but it's a bit more code.

Categories

Resources