I'm looping through a JSON array using the jQuery $each function. I think i'm being incredibly thick here, but I'd like to wrap the 3 elements in a container div on each iteration. Please advise?
success: function(data) {
var access = data.query.results.json.data;
$.each(access, function(index, value) {
var ob = value;
$(".front-page .main .object").append('<img class="post-image" src="' + ob.images.standard_resolution.url + '">');
$(".front-page .main .object").append('<div class="post-caption">' + ob.caption.text + '"</div>');
$(".front-page .main .object").append('<div class="post-tags">' + ob.tags + '"</div>');
});
},
To do that you can create the wrapper object, append the three items to it, then append the wrapper to the target, something like this:
var access = data.query.results.json.data.forEach(function(obj) {
var $wrapper = $('<div />').appendTo('.front-page .main .object');
$wrapper.append(`<img class="post-image" src="${obj.images.standard_resolution.url}" />
<div class="post-caption">${obj.caption.text}</div>
<div class="post-tags">${obj.tags}</div>`);
});
Related
As the title says, I am having some issues converting images to links using jquery. My code right now is:
var all_img = $(".message .content").find("img");
$.each(all_img, function (index, value) {
var src = value.src;
value.replaceWith($("<a href='" + src +"'>Image " + index+1 + "</a>"));
});
Which results in the images being replaced with [object Object]. I have also tried:
$.each(all_img, function (index, value) {
var src = value.src;
value.replaceWith("<a href='" + src +"'>Image " + index+1 + "</a>");
});
Which results in the html I am trying to insert going in as plain unclickable text. Am I misunderstanding how .replaceWith() works?
You couldn't call the jQuery .replaceWith() method on value, you need to use a jQuery object, to target the current img in every iteration you need to use $(this) like :
all_img.each(function (index, value) {
var src = value.src;
$(this).replaceWith("<a href='" + src +"'>Image " + index+1 + "</a>");
});
I think it is better to create a new element and remove/hide the img:
$('.turnInAnchor').click(function(e){
$('img').each(function(index, el) {
$('body')
.append("<a href='"+el.src+"' target='_blank'>Image "+index+"</a>");
el.remove();
})
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button class="turnInAnchor">Turn in anchor</button>
<img src="https://upload.wikimedia.org/wikipedia/it/7/75/Twin_Peaks_Episodio_Pilota_Laura_Palmer.png" />
I am trying to get all span elements inside the form. The span elements are turning into input text fields and become editable. When you click away they are turning back into span elements. I will attached fiddle live example.
I gave it a go but the problem is that I am getting both ids but only value of the first span element.
Here is my html:
<span name="inputEditableTest" class="pztest" id="inputEditableTest" data-editable="">First Element</span>
<span name="inputEditableTest2" class="pztest" id="inputEditableTest2" data-editable="">Second Element</span>
<input id="test" type="submit" class="btn btn-primary" value="Submit">
And here is JavaScript with jQuery:
$('body').on('click', '[data-editable]', function () {
var $el = $(this);
var name = $($el).attr('name');
var value = $($el).text();
console.log(name);
var $input = $('<input name="' + name + '" id="' + name + '" value="' + value + '"/>').val($el.text());
$el.replaceWith($input);
var save = function () {
var $p = $('<span data-editable class="pztest" name="' + name + '" id="' + name + '" />').text($input.val());
$input.replaceWith($p);
};
$input.one('blur', save).focus();
});
$("#test").on('click', function(){
var ok = $("span")
.map(function () {
return this.id;
})
.get()
.join();
var ok2 = $("#" + ok).text();
alert(ok);
alert(ok2);
//return [ok, ok2];
});
Here is the fiddle https://jsfiddle.net/v427zbo1/3/
I would like to return the results as an array example:
{element id : element value}
How can I read ids and values only inside specific form so something like:
<form id = "editableForm">
<span id="test1">Need these details</span>
<span id="test2">Need these details</span>
<input type="submit">
</form>
<span id="test3">Don't need details of this span</span>
Lets say I have got more than 1 form on the page and I want JavaScript to detect which form has been submitted and grab values of these span elements inside the form
I will be grateful for any help
$("#test").on('click', function(){
var result = {};
$("span").each(function (k, v) {
result[v.id] = v.innerHTML;
});
alert(JSON.stringify(result));
//return [ok, ok2];
});
Here is an example: https://jsfiddle.net/v427zbo1/4/
Container issue:
You should use this selector: #editableForm span if you want to get all the divs inside this container.
$("#editableForm span").each(function (k, v) {
result[v.id] = v.innerHTML;
});
But if you want to get only first-level children elements then you should use this selector: #editableForm > span
Example with getting all the spans inside #editableForm container: https://jsfiddle.net/v427zbo1/9/
If you want to have several forms, then you can do like this:
$('form').on('submit', function(e){
e.preventDefault();
var result = {};
$(this).find('span').each(function (k, v) {
result[v.id] = v.innerHTML;
});
alert(JSON.stringify(result));
//return [ok, ok2];
});
Example with two forms: https://jsfiddle.net/v427zbo1/10/
You can't use .text to return the value of multiple elements. It doesn't matter how many elements are selected, .text will only return the value of the first one.
Virtually all jQuery methods that return a value behave this way.
If you want to get an array of values for an array of matched elements, you need another map. You also need to join the strings with , # as you're producing something along the lines of #id1id2id3 instead of #id1, #id2, #id3:
var ok = $("span").map(function () {
return this.id;
}).join(', #')
var ok2 = $("#" + ok).map(function () {
return $(this).text();
});
That said, you're already selecting the right set of elements in your first map. You pass over each element to get its ID, you already have the element. There is no reason to throw it away and reselect the same thing by its ID.
If I got you right following code will do the job
var ok = $("span")
.map(function () {
return {id: $(this).attr('id') , value: $(this).text()};
}).get();
Check this fiddle.
What is the optimize way to append this element to my specific DIV Class using JQUERY. This will generate dynamic elements. I use .AppendTo then display dynamically the element inside <div class='parent-list-workorder'>.
Here's my code so far but it doesn't work:
$(document).ready(function(){
var ListOfWorkOrders = [];
$("#button").click(function(){
//var _WOID = $('.list-workorder-id').text();
var _WOID = $('#txtWOID').val();
//alert(_WOID);
$.ajax({
url:'getWorkOrders.php',
type:'POST',
data:{id:_WOID},
dataType:'json',
success:function(output){
for (var key in output) {
if (output.hasOwnProperty(key)) {
$("<div class='child-list-workorder'>
<div class='list-workorder'>
<div class='list-workorder-header'>
<h3 class='list-workorder-id'>" + output[key] + "</h3>
</div>
<p>" + Sample + ":" + key + "</p>
</div>
</div>").appendTo("<div class='parent-list-workorder'>");
//alert(output[key]);
}
}
console.log(output);
}
});
});
});
Am I missing something?
Your problem is in the code below:
.appendTo("<div class='parent-list-workorder'>");
The parameter of appendTo() should also be a valid selector.
you can try this instead:
.appendTo("div.parent-list-workorder");
granting that div.parent-list-workorder already exists.
You have two problems. First, you need to use a selector as an argument to .appendTo(), not an HTML string. Second, you need to remove or escape the newlines in the HTML string.
$("<div class='child-list-workorder'>\
<div class='list-workorder'>\
<div class='list-workorder-header'>\
<h3 class='list-workorder-id'>" + output[key] + "</h3>\
</div>\
<p>" + Sample + ":" + key + "</p>\
</div>\
</div>").appendTo("div.parent-list-workorder");
I have created a html like this:
<body onload = callAlert();loaded()>
<ul id="thelist">
<div id = "lst"></div>
</ul>
</div>
</body>
The callAlert() is here:
function callAlert()
{
listRows = prompt("how many list row you want??");
var listText = "List Number";
for(var i = 0;i < listRows; i++)
{
if(i%2==0)
{
listText = listText +i+'<p style="background-color:#EEEEEE" id = "listNum' + i + '" onclick = itemclicked(id)>';
}
else
{
listText = listText + i+ '<p id = "listNum' + i + '" onclick = itemclicked(id)>';
}
listText = listText + i;
//document.getElementById("lst").innerHTML = listText+i+'5';
}
document.getElementById("lst").innerHTML = listText+i;
}
Inside callAlert(), I have created id runtime inside the <p> tag and at last of for loop, I have set the paragraph like this. document.getElementById("lst").innerHTML = listText+i;
Now I am confuse when listItem is clicked then how to access the value of the selected item.
I am using this:
function itemclicked(id)
{
alert("clicked at :"+id);
var pElement = document.getElementById(id).value;
alert("value of this is: "+pElement);
}
But getting value as undefined.
Any help would be grateful.
try onclick = itemclicked(this.id) instead of onclick = 'itemclicked(id)'
Dude, you should really work on you CodingStyle. Also, write simple, clean code.
First, the html-code should simply look like this:
<body onload="callAlert();loaded();">
<ul id="thelist"></ul>
</body>
No div or anything like this. ul and ol shall be used in combination with li only.
Also, you should always close the html-tags in the right order. Otherwise, like in your examle, you have different nubers of opening and closing-tags. (the closing div in the 5th line of your html-example doesn't refer to a opening div-tag)...
And here comes the fixed code:
<script type="text/javascript">
function callAlert() {
var rows = prompt('Please type in the number of required rows');
var listCode = '';
for (var i = 0; i < rows; i++) {
var listID = 'list_' + i.toString();
if (i % 2 === 0) {
listCode += '<li style="background-color:#EEEEEE" id="' + listID + '" onclick="itemClicked(this.id);">listItem# ' + i + '</li>';
}
else {
listCode += '<li id="' + listID + '" onclick="itemClicked(this.id);">listItem# ' + i + '</li>';
}
}
document.getElementById('thelist').innerHTML = listCode;
}
function itemClicked(id) {
var pElement = document.getElementById(id).innerHTML;
alert("Clicked: " + id + '\nValue: ' + pElement);
}
</script>
You can watch a working sample in this fiddle.
The problems were:
You have to commit the id of the clicked item using this.id like #Varada already mentioned.
Before that, you have to build a working id, parsing numbers to strings using .toString()
You really did write kind of messy code. What was supposed to result wasn't a list, it was various div-containers wrapped inside a ul-tag. Oh my.
BTW: Never ever check if sth. is 0 using the ==-operator. Better always use the ===-operator. Read about the problem here
BTW++: I don't know what value you wanted to read in your itemClicked()-function. I didn't test if it would read the innerHTML but generally, you can only read information from where information was written to before. In this sample, value should be empty i guess..
Hope i didn't forget about anything. The Code works right now as you can see. If you've got any further questions, just ask.
Cheers!
You can pass only the var i and search the id after like this:
Your p constructor dymanic with passing only i
<p id = "listNum' + i + '" onclick = itemclicked(' + i + ')>
function
function itemclicked(id)
{
id='listNum'+i;
alert("clicked at :"+id);
var pElement = document.getElementById(id).value;
alert("value of this is: "+pElement);
}
is what you want?
I am not sure but shouldn't the onclick function be wrapped with double quotes like so:
You have this
onclick = itemclicked(id)>'
And it should be this
onclick = "itemclicked(id)">'
You have to modify your itemclicked function to retrieve the "value" of your p element.
function itemclicked( id ) {
alert( "clicked at :" + id );
var el = document.getElementById( id );
// depending on the browser one of these will work
var pElement = el.contentText || el.innerText;
alert( "value of this is: " + pElement );
}
demo here
I want to make the following code:
<h2>TEXTz</h2>
<p>ARTICLE</p>
<h2>TEXTx</h2>
<p>ARTICLE</p>
Look like this:
<div class="highlight">
<h2>TEXTz</h2>
<p>ARTICLE</p>
</div>
<h2>TEXTx</h2>
<p>ARTICLE</p>
But I have to use: contains for find h2 text and add wrap before h2 and after p.
My failed code:
$.extend($.expr[':'],{containsExact: function(a,i,m){return $.trim(a.innerHTML.toLowerCase()) === m[3].toLowerCase();}});
var byItem = "TEXTz"
var ItemTitle = $("h2:containsExact(" + byItem +")").text();
var ItemDes = $("h2:containsExact(" + byItem +")").next("p").text();
$("h2:containsExact(" + byItem +")").html('<section class="highlightitem"><h2>' + ItemTitle + '</h2><p>' + ItemDes + '</p></div>');
http://jsfiddle.net/NDUzW/
The method .add() allows adding elements to a jquery object.
Then you can use .wrapAll() to wrape a set of elements in jQuery.
var $h2 = $("h2:containsExact(" + byItem +")");
if ($h2.length) {
$h2.add( $h2.next('p') )
.wrapAll( $('<div>').addClass('highlight') );
}
Working example on jsfiddle
Simply use the jQuery functions:
var byItem = "TEXTz"
$("h2")
.filter(
function() {
if ($(this).html() == byItem) {
return true;
}
return false;
}
)
.next("p")
.andSelf()
.wrapAll($("<section>")
.addClass("highlightitem")
);
Example