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/
Related
I am trying to append a number of Div's to a div with an id "list", and each div has an event so i make an array for each div to be appended.
here is my code.
var count = Object.keys(data.results).length;
var el = [];
for(var i=1; i<=count; i++){
el[i] = $('<div id="'+i+'">data.results[i].name</div>');
$("#list").append(el[i]);
el[i].click(function(){
alert(data.results[i].name);
$('#searchbox').modal('toggle');
});
}
the data in div's was successfully appended. but as a try to alert the data in the event i bind to each div, it doesn't alert the data in the div.
what I am trying to do is append names with a div within the div with id "list" and if i click on a name, it should alert the name itself.
You can simplify the logic here by using a delegated event handler on all the appended div elements, then using the text() method to retrieve the required value. Try this:
var data = {
results: {
foo: { name: 'foo_name' },
bar: { name: 'bar_name' }
}
}
var $list = $("#list").on('click', 'div', function() {
console.log($(this).text());
//$('#searchbox').modal('toggle');
});
Object.keys(data.results).forEach(function(key, i) {
$list.append('<div id="' + i + '">' + data.results[key].name + '</div>');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="list"></div>
The problem is that by the time an element is clicked i is already set to the maximum value i = count. To fix that you'll have to create a closure. Try this:
var count = Object.keys(data.results).length;
var el = [];
function closure(index){
el[index].click(function(){
alert(data.results[index].name);
$('#searchbox').modal('toggle');
});
}
for(var i=1; i<=count; i++){
el[i] = $('<div id="'+i+'">data.results[i].name</div>');
$("#list").append(el[i]);
closure(i);
}
<script type="text/javascript">
function searchAndHighlight(searchTerm, selector) {
if (searchTerm) {
var selector = selector || "body"; //use body as selector if none provided
var searchTermRegEx = new RegExp(searchTerm, "ig");
var matches = $(selector).text().match(searchTermRegEx);
if (matches) {
$('.highlighted').removeClass('highlighted'); //Remove old search highlights
$(selector).html($(selector).html()
.replace(searchTermRegEx, "<span class='highlighted'>" + searchTerm + "</span>"));
if ($('.highlighted:first').length) { //if match found, scroll to where the first one appears
$(window).scrollTop($('.highlighted:first').position().top);
}
return true;
}
}
return false;
}
$(document).ready(function () {
$('#btnSearch').on("click", function () {
if (!searchAndHighlight($('#txtSearch').val())) {
alert("No results found");
}
});
});
</script>
In above code i have searched and highlighted the text. But issue is if i type "in" it search whole page inner html and images. Screen short is given below.
How i search the text which is displayed in the page content.
Edited
So what i have thought of is p, div and span are the elements in which you should perform the check to find the substring.
var search = ['p', 'div', 'span'];
var pattern = searchTerm;
$.each(search, function(i){
var str = search[i];
var orgText = $(str).text();
orgText = orgText.replace(pattern, function($1){
return "<span class='highlighted'>" + $1 + "</span>"
});
$(str).html(orgText);
});
});
http://www.codeproject.com/Questions/617348/How-to-search-text-from-page-with-next-and-previou
I have completed my task using this plugin.
I want to change the text inside of an element for dynamically created elements. i = 2 because that's Why is it not working?
var loanName = function() {
for(var t=1; t < i; t++) {
$('body').on('keyup', '.loanNameV'+t, function () {
var loanN = $('.loanNameV'+t).val();
$('.nameLoan'+t).text(loanN);
});
}
};
$('body').on('keyup', '[class^="loanNameV"]', function () {
var numbesideclass = ($(this).attr('class').split('loanNameV'))[1];
var loanN = $(this).val();
$('.nameLoan'+numbesideclass).text(loanN);
});
Note: this code will work if you don't have another class for loanNameV elements like class="loanNameV1 anotherclass anotherclass" in this case this code will not work as expected
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.
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.