html to xml conversion using javascript? - 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.

Related

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

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>

JSON Data Not Showing In Plunker

I am having trouble getting a JSON data document to appear/input into a HTML document on Plunker.
The current JS being used:
$(document).ready(function() {
//Content Viewer Information
function checkViewers() {
//Base Variables
var viewer = $('#viewed span.user');
var totalViews = $('#viewed span.user').length;
var shortenViews = $('#viewed span.user').length -1;
if (totalViews === 0) {
$('<span> 0 people have </span>').insertBefore($('#viewed span:last-child'));
}
if (totalViews === 2) {
$('<span> and </span>').insertAfter(viewer.first());
}
if (totalViews >= 3) {
viewer.slice(1).hide();
$('<span> and </span>').insertAfter(viewer.first());
$('<span class="user count"></span>').insertAfter(viewer.eq(2));
$('.count').html(shortenViews + ' more people');
}
}
checkViewers();
//JSON Data
var xhr = new XMLHttpRequest();
xhr.onload = function() {
if (xhr.status === 200) {
responseObject = JSON.parse(xhr.responseText);
var newViewers = '';
for (var i = 0; i < responseObject.profiles.length; i++) {
newViewers += '<span class="user">' + responseObject.profiles[i].firstName + ' ';
newViewers += responseObject.profiles[i].lastName + '</span>';
}
//Update Page With New Content
var viewerSection = $('#viewed');
viewerSection.innerHTML = newViewers;
}
};
xhr.open('GET', 'data.json', true);
xhr.send(null);
console.log('JSON Fired');
});
The JSON Data should be inputted into the div #viewed with the viewers first and last name. I am not too familiar with Plunker, so I am not sure if I am going about something the wrong way within Plunker, or if a portion of the current code is causing the JSON Data to not be entered.
View the current Plunker.
The problem is you are mixing jQuery and native dom methods then getting confused about what is what
This returns a jQuery object:
var viewerSection = $('#viewed');
This is applying a property to that jQuery object that won't update the DOM since it isn't being applied to a DOM node:
viewerSection.innerHTML( newViewers);
to set the html using jQuery you need to use html() method:
viewerSection.html( newViewers);
Or to set it using native method you need to do
var viewerSection = $('#viewed')[0]; /* returns the DOM node from jQuery object */
/* or */
var viewerSection = document.getElementById('viewed');
/* then */
viewerSection.innerHTML( newViewers);
I would suggest for DOM manipulation you pick either jQuery or native javascript and stick to using one or the other and don't mix them
Working Demo Using html()

How to loop through ids with same prefix

I have this section of code that saves a list item on click to localStorage based on the list item's id number. On a different page I am then able to load whatever list items were saved.
var save1075 = $('#store-1075').get(0);
$('#store-1075').on('click', function () {
var storeStorageKey1075 = $(this).attr('id');
localStorage.setItem('storeStorageKey1075', $(this).attr('id'));
localStorage.setItem('storeStorageKey1075', this.innerHTML);
});
if ( localStorage.getItem('storeStorageKey1075') ) {
save1075.innerHTML = localStorage.getItem('storeStorageKey1075');
}
var storeStorageKey1075 = $(this).attr('id');
if ( localStorage.getItem('storeStorageKey1075') ) {
storeStorageKey1075 = localStorage.getItem('storeStorageKey1075');
}
Right now I have to repeat that chunk of code for every individual id number and I'm trying to instead make the id number a variable that loops through all possible id numbers when clicked but only saves the id of that specific one. Maybe something along the lines of this:
var id = //some sort of loop or array of possible ids.
var save = $('#store-'+id).get(0);
$('#store-'+id).on('click', function () {
var storeStorageKey = $(this).attr('id');
localStorage.setItem('storeStorageKey', $(this).attr('id'));
localStorage.setItem('storeStorageKey', this.innerHTML);
});
if ( localStorage.getItem('storeStorageKey') ) {
save.innerHTML = localStorage.getItem('storeStorageKey');
}
var storeStorageKey = $(this).attr('id');
if ( localStorage.getItem('storeStorageKey') ) {
storeStorageKey = localStorage.getItem('storeStorageKey');
}
Each of the list items has the same prefix of "store-" and the numbers are in no specific order but randomly generated each time a new store location is created.
The obvious thing to do is to add a class but you could also:
var elems = $( "[id^='store']")
elems.on( "click", function() {//Save html on click
localStorage.setItem( this.id, this.innerHTML );
});
//Retrieve html
elems.each( function() {
var html = localStorage.getItem( this.id );
if( html ) {
$(this).html( html );
}
});
This loops over all keys that begin with storeStorageKey:
for (var i=0; i<localStorage.length; i++) {
var key = localStorage.key(i);
if (/^storeStorageKey/.test(key)) {
var item = localStorage.getItem(key);
// do something with item
}
}
Instead of using a prefix in the id I'd suggest adding a class to indicate that an item is storable:
<div class="storable" id="store-1234">...</div>
then you can use the class to select all the storable things in one go:
$('.storable').on('click', function () {
var storeStorageKey = $(this).attr('id');
...
});

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.

Using jQuery to change a string of HTML: wont update the string

I have some JQuery that takes 2 strings of HTML. Each string contains exactly the same html except in one string the innertext contents of each element will be different, this string is called newContent, the other oldContent.
My function: iterates over oldContent, for each element of the class "updatable"(inside oldContent) we change its innerText to the innerText of the same element in newContent.
My Problem: it is not changing the contents of oldContent, after I perform the function, oldContent contains the exact same HTML (where what should happen is that elements of the class updatable should have different innerText).
Why doesn't the string oldContent change?
function insertContentIntoUpdatableElements( oldContent, newContent )
{
// Pre: oldContent & newContent must be strings of HTML returned from jquery's
// $("").html()
try
{
alert("BEFORE: "+oldContent);
var index = 0;
var oldElements = $(oldContent).find(".updatable");
var newElements = $(newContent).find(".updatable");
$(oldContent).find(".updatable").each( function()
{
var txt = $(newElements[index]).text(); alert("TEXT: "+txt);
alert("OLD TEXT: "+$(this).text());
$(this).text(txt);
index++;
alert("NEW TEXT: "+$(this).text()); // prints out CORRECT updated/changed text
});
alert("AFTER: "+oldContent); // prints out INCORRECT updated/changed text for each element of class "updatable"
return oldContent;
}
catch(ex) { alert("In insertContentIntoUpdatableElements(): "+ex); return "FAILED"; }
}
This should do the trick.
function insertContentIntoUpdatableElements( oldContent, newContent )
{
var result = $(oldContent);
var oldElements = result.find(".updatable");
var newElements = $(newContent).find(".updatable");
$(oldElements).each(function(index, el)
{
$(oldElements[index]).text($(newElements[index]).text());
});
return result;
}
See a working Demo on jsFiddle: http://jsfiddle.net/ZZVgh/

Categories

Resources