I need to parse the following example XML in jquery, to get the attribute "V"
XML file:
<RES>
<R N="1">
<MT N="myMeta1" V="myMeta1Value"/>
<MT N="myMeta2" V="myMeta2Value"/>
<MT N="myMeta2" V="myMeta2Value"/>
</R>
</RES>
And my javascript is the following:
function(data){
$(data).find('R').each(function(){
var $result = $(this);
$result.find('MT').each(function(_mt) {
console.log($(_mt).attr("V") );
});
});
}
I get undefineds, what am I doing wrong?
The first argument to .each callback is the index, the second one is the value. You can also use this:
$result.find('MT').each(function() {
console.log($(this).attr("V") );
});
Or:
$result.find('MT').each(function( index, _mt ) {
console.log($(_mt).attr("V") );
});
You are using index as an element in each. As first parameter is index pass two parameter in each and use the second to get the element.
function(data){
$(data).find('R').each(function(){
var $result = $(this);
$result.find('MT').each(function(_mt, obj) {
console.log($(obj).attr("V") );
});
});
}
Related
https://i.imgur.com/r3tTCuh.jpg
this my html script
<td><p1><?php echo $result->bn_nomor;?></p1></td>
<td> <button class="btn1 badge badge-info">Copy Nomor</button>
and this my javascript
<script>
var clipboard=new Clipboard(".btn1",{
target:function(){
return document.querySelector("p1")
}
});
clipboard.on("success",function(o){
console.log(o)
}),
clipboard.on("error",function(o){
console.log(o)
});
</script>
I cant copy one by one data which results from $ result-> bn_number;
only one can copy , the other cant i copy, I want to be in copy one by one the result data with same class.. thanks
You could add a loop in jquery:
var obj = {
"flammable": "inflammable",
"duh": "no duh"
};
$.each( obj, function( key, value ) {
alert( key + ": " + value );
});
Issue: Upon updating the src of images, retrieved via GET request, the DOM never updates but their new values show in console.
Suspected Cause: I think there is some conflict with using data-attributes, but using attr() instead of data() does not seem to remedy.
HTML to be updated:
<div class="data-block">
<img data-item="hp-logo" />
<img data-item="hp-banner" />
</div>
GET Request:
if(promoid != null) {
$.get({
url: '/snippets/data.html',
cache: false
}).then(function(data){
var tempData = $('<output>').append($.parseHTML(data)).find('.data[data-promo-id="' + promoid + '"]');
myContent = tempData.html();
dataItems = $('.data-block').html();
//console.log('Data Items On Page: ', dataItems);
$(dataItems).each(function (index, value) {
if( $(this).is('[data-item]')) {
//console.log('Data Items With Attribute: ', this);
dataItemLookup = $(this).attr('data-item');
//console.log('Data Item Lookup Value: ', dataItemLookup);
$(myContent).each(function (index, value) {
//console.log('Retrieved Items Checking Against: ', this);
if ( $(this).attr('data-alias') == lastalias ) {
//console.log('Retrieved Items Match Alias: ', this);
if ($(this).attr('data-item') == dataItemLookup) {
//console.log('Retrieved Item Match', this);
dataImageDesktop = $(this).attr('data-image-desktop');
//console.log('Value to be Passed to Data Item: ', dataImageDesktop);
} else {
// Do nothing
}
} else {
// Do nothing
}
});
$(this).attr('src', dataImageDesktop);
console.log(this);
}
});
});
}
data.html:
<div class="data-container">
<div class="data" data-promo-id="11202016">
<div data-alias="test.html" data-item="hp-logo" data-image-desktop="http://placehold.it/250x150"></div>
<div data-alias="test.html" data-item="hp-banner" data-image-desktop="http://placehold.it/350x250"></div>
<div data-alias="not-test.html" data-item="hp-spot" data-image-desktop="http://placehold.it/450x350"></div>
</div>
</div>
Not sure how to proceed in troubleshooting this issue. Everything works as expected, except the DOM updating. Ideas?
Using html() on an element will get you the innerHTML of the object, which is a string. As such using it inside $() later will cause jQuery to create new elements that are not attached to the DOM. If all you are after is to select elements and modify them, simply use the $(selector) and modify it. Do not use html() and wrap the results with $().
Instead of $(selector).attr('data-name') try using $(selector).data('name') as shown in the jQuery.data() documentation.
I need to find all elements in a page by attribute value only (ignoring the key) using jquery.
Is there a way to do this easily?
Currently, I am just iterating on all elements in the page, on every property etc..
You can use $.expr, Element.attributes, Array.prototype.some()
$.expr[":"].attrValue = function(el, idx, selector) {
return [].some.call(el.attributes, function(attr) {
return attr.value === selector[selector.length - 1]
})
};
// filter element having attribute with `value` set to `"abc"`
$(":attrValue(abc)").css("color", "blue");
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js">
</script>
<div title="abc">abc</div>
<div title="def">def</div>
<div title="ghi">ghi</div>
<div title="jkl">jkl</div>
Use brackets []
var ElementsWithAttributeKeyTest = $('[attributeKey="Test"]');
Or pass an object with the attribute name and value as parameter to this function:
var getElemsByAttribute = function(obj) {
if (obj) {
if (obj.attributeKey && obj.attributeValue) {
return $('[' + obj.attributeKey + '="' + obj.attributeValue + '"]');
}
}
}
var attrObj = {
attributeKey: 'data-color',
attributeValue: 'red'
}
getElemsByAttribute(attrObj).css('color', 'red');
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.1/jquery.min.js"></script>
<span data-color="red">Red</span>
<span data-color="red">Red</span>
<span data-color="green">Green</span>
<span data-color="blue">Blue</span>
<span data-color="red">Red</span>
<span data-color="green">Green</span>
If you want to search all attributes values you can use this small plugin:
$.fn.search_by_attr_value = function(regex) {
return this.filter(function() {
var found = false;
$.each(this.attributes, function() {
if (this.specified && this.value.match(regex)) {
found = true;
return false;
}
});
return found;
});
};
and you can use it like this:
$('*').search_by_attr_value(/^some value$/);
Based on this answer
You could define new function take as parameter the value you want to filter with (e.g get_elements_by_value(filter)), then inside this function parse all the elements of the page using $('*').each(), after that parse the attributes of every element el of those elements using attribute attributes like below :
$.each(el.attributes, function(){ })
Then inside the each loop you could make your condition and push the matched values with the passed filter inside matched[] that should be returned.
Check working example below, hope this helps.
function get_elements_by_value(filter){
var matched=[];
$('*').each(function(index,el) {
$.each(el.attributes, function() {
if( this.value===filter )
matched.push(el);
})
})
return $(matched);
}
get_elements_by_value('my_value').css('background-color','green');
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div title="my_value">AA</div>
<div title="def">BB</div>
<input type='text' name='my_value' value='CC'/>
<p class='my_value'>DD</p>
<span title="test">EE</span>
I need to append this json data to an html element.
[
{
"website":"google",
"link":"http://google.com"
},
{
"website":"facebook",
"link":"http://fb.com"
}
]
How to convert this easily using any plugin.Presently,I couldn't find any simple plugins in jquery,So please help me friends.
Thanks in advance..........
Hi you can use jPut jQuery Plugin (http://plugins.jquery.com/jput/)
Create a HTML jPut Template
<div jput="template">
{{website}}
</div>
<div id="main">
</div>
<script>
$(document).ready(function(){
var json=[{"website":"google","link":"http://google.com"},
{"website":"facebook","link":"http://fb.com"}];
$('#main').jPut({
jsonData:json, //your json data
name:'template' //jPut template name
});
});
</script>
jPut is easy to use comparing to normal parsing.
if there is lots of data to be appended it is very difficult to append using $.each loop.
in jPut just need to create template & to print the data just put the object name in {{}}.
With jQuery, you could do something like this:
data = $.parseJson(json);
$.each(data, function(key, obj) {
htmlElement = $(''+website+'');
$('body').append(htmlElement);
})
Why use a plugin for this? No need to write a plugin to go around this. Just simply loop it through & do what you wan't with the data. Here is an example:
var data = [
{
"website":"google",
"link":"http://google.com"
},
{
"website":"facebook",
"link":"http://fb.com"
}
];
var html = '';
$.each(data, function (index, item) {
html += '' + item.website + '';
});
$('body').append(html);
If you're expecting it to be an anchor tag then -
Html -
<div id="siteContainer"></div>
JS-
var sites = [
{
"website":"google",
"link":"http://google.com"
},
{
"website":"facebook",
"link":"http://fb.com"
}
]
var $container = $('siteContainer');
$(sites).each(function(item, index){
var name = item['website'];
var link = item['link'];
var anchorTag = '' + name + '');
$container.appendTo(anchorTag);
});
NO need plugin, simply iterate with each function and append anchor tag with any selector tag.
var links = [
{
"website":"google",
"link":"http://google.com"
},
{
"website":"facebook",
"link":"http://fb.com"
}
];
$.each(links, function(index, object){
$("<a></a>").attr("href", object.link).
text( object.website).css("margin", "5px").appendTo("body");
})
no plugin needed, can be done without jquery too
<div id="container">
</div>
<script>
var data = [
{
"website":"google",
"link":"http://google.com"
},
{
"website":"facebook",
"link":"http://fb.com"
}
]
document.getElementById('container').innerHTML = ''+data[0]['website']+' >> '+data[0]['link']+' <br> '+data[1]['website']+' >> '+data[1]['link']
</script>
LF way to short my js/jquery function:
$.ajax({ // Start ajax post
..........
success: function (data) { // on Success statment start
..........
//1. Part
$('var#address').text(data.address);
$('var#telephone').text(data.telephone);
$('var#mobile').text(data.mobile);
$('var#fax').text(data.fax);
$('var#email').text(data.email);
$('var#webpage').text(data.webpage);
//2. Part
if (!data.address){ $('p#address').hide(); } else { $('p#address').show(); };
if (!data.telephone){ $('p#telephone').hide(); } else { $('p#telephone').show(); };
if (!data.mobile){ $('p#mobile').hide(); } else { $('p#mobile').show(); };
if (!data.fax){ $('p#fax').hide(); } else { $('p#fax').show(); };
if (!data.email){ $('p#email').hide(); } else { $('p#email').show(); };
if (!data.webpage){ $('p#webpage').hide(); } else { $('p#webpage').show(); };
}, End Ajax post success statement
Here is my html:
<p id="address">Address:<var id="address">Test Street 999 2324233</var></p>
<p id="telephone">Telephone:<var id="telephone">+1 0000009</var></p>
<p id="mobile">Mobile:<var id="mobile">+1 0000009</var></p>
<p id="email">E-mail:<var id="email">info#example</var></p>
<p id="webpage">Web Page:<var id="webpage">www.example.com</var>/p>
How can we reduce the number of selector*(1. part)* and else if the amount (2. part)?
Assuming your object's property names exactly match the spelling of your element ids you can do this:
for (var k in data) {
$('var#' + k).text(data[k]);
$('p#' + k).toggle(!!data[k]);
}
...because .toggle() accepts a boolean to say whether to show or hide. Any properties that don't have a matching element id would have no effect.
Note: your html is invalid if you have multiple elements with the same ids, but it will still work because your selectors specify the tag and id. Still, it might be tidier to just remove the ids from the var elements:
<p id="address">Address:<var>Test Street 999 2324233</var></p>
<!-- etc. -->
With this JS:
$('#' + k).toggle(!!data[k]).find('var').text(data[k]);
And then adding some code to hide any elements that aren't in the returned data object:
$('var').parent('p').hide();
...and putting it all together:
$.ajax({
// other ajax params here
success : function(data) {
$('var').parent('p').hide();
for (var k in data) {
$('#' + k).toggle(!!data[k]).find('var').text(data[k]);
}
}
});
Demo: http://jsfiddle.net/z98cw/1/
["address", "telephone", "mobile", "fax", "email", "webpage"].map(
function(key) {
if (data.hasOwnProperty(key) && !!data[key]) {
$('p#' + key).show();
} else {
$('p#' + key).hide();
}
});
But you should not.
As long as the properties of the object match the id attributes of the p tags you can iterate through the object using the property name as a selector. Also since id attributes are unique, refrain from prefixing the selector with var it is unnecessary.
var data = {
address: "address",
telephone: "telephone",
mobile: "mobile",
fax: "fax",
email: "email",
webpage: "webpage"
};
for(x in data){
var elem = $("#" + x);
if(elem.length == 1){
elem.text(data[x]);
}
}
JS Fiddle: http://jsfiddle.net/3uhx6/
This is what templating systems are created for.
If you insist on using jQuery there is a jQuery plugin: https://github.com/codepb/jquery-template
More:
What Javascript Template Engines you recommend?
I would use javascript templates for this (I've shortened the example a quite a bit, but you should get the gist).
First the template, I love Underscore.js for this so I gonna go ahead and use that.
<% if data.address %>
<p id="address">Address: {%= Test Street 999 2324233 %}</p>
to compile this inside your success function
success: function(data) {
//assuming data is a json that looks like this {'address':'my street'}
var template = _.template(path_to_your_template, data);
$('var#addresscontainer').html(template);
}
Thanks for birukaze and nnnnnn:
With your advice came function;) :
for (var key in data) {
if (data.hasOwnProperty(key) && !!data[key]) {
$('p#' + key).show().find('var').text(data[key]);
} else {
$('p#' + key).hide();
}
};
Now i can avoid for selector with var.