Use jQuery to serialize DIV attributes and send to AJAX POST - javascript

I know serialize works with <FORM> but can it work for DIVs as well?
<div class="row" shortname="1"></div>
<div class="row" shortname="2"></div>
<div class="row" shortname="3"></div>
<div class="row" shortname="4"></div>
How can I grab all the DIV and its shortname attribute and pass everything to an AJAX post?
Like shortname=1&shortname=2&shortname=3
Thanks!

you can create an array and pass it as a JSON,
var data=new Array();
$('div.row').each(function(){
data.push($(this).attr('shortname'))
})
var jsonString=JSON.stringify(data);

No, it cannot work with divs so you'll have to create a solution. If I can assume that these divs are wrapped in a parent div, then this code will work
var queryString = '';
var x = 0;
$('#parentdiv div').each(function(){
if(x) queryString += '&';
else x = 1;
queryString += 'shortname[]=' + $(this).attr("shortname");
});
If they are not wrapped in a div, and you want to find all the divs that have the shortname attribute, change the loop to this.
$('div').find('[shortname]').each(function(){
// same stuff
});
note: I'm thinking you want the shortname to be an array. If you constuct without brackets, you may be overwriting the value of "shortname" over and over.

You can build an array with the values and pass that array as part of an object to the $.ajax data option.
var shortnames = $('[shortname]').map(function(){
return $(this).attr('shortname');
}).get();
ajax({
....
data:{shortname:shortnames},
....
});

You can do something like this...
FIDDLE
var serialized = '';
$('#serializeme div').each(function(){
serialized = serialized + 'shortname=' + $(this).attr('shortname') + '&';
});

Related

Splitting a JavaScript string from XML and wrapping in HTML element

I'm working on displaying an RSS feed in a website through the use of jQuery and AJAX. One of the strings from the source XML file are wrapped in a <category> tag, and there are multiple of these returned. I'm getting the source data like follows:
var _category = $(this).find('category').text();
Because there are multiple categories returned with this method, say the following:
<category>Travel</category>
<category>Business</category>
<category>Lifestyle</category>
I'm getting strings returned like so:
TravelBusinessLifestyle
My end goal is to see each of these separate strings returned and wrapped in individual HTML elements, such as <div class="new"></div>.
I did end up trying the following:
var _categoryContainer = $(this)
.find('category')
.each(function () {
$(this).wrap( "<div class='new'></div>" );
});
among quite a few other variations.
This is all being appended to a HTML structure similar to the following.
// Add XML content to the HTML structure
$(".rss .rss-loader")
.append(
'<div class="col">'
+ <h5 class="myClass">myTitle</h5>
+ _category
+ "</div>"
);
Any suggestions would be much appreciated!
if it's a simple html which is mentioned in a question. you can use something like below.
var html="<category>Travel</category><category>Business</category><category>Lifestyle</category>"
var htmlObj=$.parseHTML(html);
var container=$("#container")
$.each(htmlObj,function(i,o){
container.append("<div class='new'>"+o.innerText+"</div>")
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id='container'></div>
Same as first answer, but without jquery
let container = document.querySelector('div#container');
document.querySelectorAll('category').forEach(element => {
let div = document.createElement('div');
div.innerText = element.innerText;
container.appendChild(div);
})
<category>Travel</category><category>Business</category><category>Lifestyle</category>
<div id="container"></div>

How can I add data params to an HTML string and get a string back?

I got a string like this:
var select_string = '<select><option>1</option><option>2</option></select>';
I need to add some data params to select in this string and get this string back in order to get the following:
select_string = '<select data-param1="param1" data-param2="param2"><option>1</option><option>2</option></select>';
I tried to use jQuery functions like .html() or .text() but it did not work. Like this:
select_string = $(select_string).data('param1', 'param1').html() //or .text()
Any ideas how to make it work would be helpful. Thank you.
You can use attr to add that attributes to the element
var select_string = '<select><option>1</option><option>2</option></select>';
var select = $(select_string).attr({
'data-param1': 'param1',
'data-param2': 'param2'
});
console.log(select.prop('outerHTML'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
Since your attribute name starts with data-, if you want to get the value, you can use:
select.data('param1'); // param1
select.data('param2'); // param2
EDIT: Titulum is right, jquery is not needed here.
But here is the working example usign jquery
var selectString = '<select><option>1</option><option>2</option></select>';
var $select = $(selectString);
$select.attr("prop_key","prop_value");
var selectChanged = $select.prop('outerHTML');
console.log(selectChanged)
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
You don't need jQuery for this:
const myElement = document.createElement('div');
myElement.innerHTML = "<select><option>1</option><option>2</option></select>";
const selectElement = myElement.getElementsByTagName("select")[0];
selectElement.setAttribute("data-param1", "param1");
selectElement.setAttribute("data-param2", "param2");
You could use indexOf and substr() to split it into 2 parts, insert your new text, and put it back together again.
var first_half = select_string.substr(0, select_string.indexOf('>'));
var second_half = select_string.substr(select_string.indexOf('>'));
select_string = first_half + ' data-param1=\"param1\" data-param2=\"param2\" ' + second_half;

Place elements in a single div in jQuery

I am new to jQuery and I am working with an API to do the following.
Get Multiple values from the API like name, place, weather forecast etc.
I have a bootstrap structure with the following code:-
<div id="place_here" class="row">
</div>
I want to place the data that I get from the API in this DIV.
Only thing that I want to do is get put all that data into a single div and place that div into above row div to create a beautiful table like structure. Something like this:-
var str = '<div class="col-md-4">' + newoverview + '</div>';
(newoverview is a string from JSON that I get. However that is only a single value that I want to place in my div class = "col-md-4" tag above. I want to insert more values as well.
Problems:-
I cannot(or don't know) how to use global variable in JQuery. Whenever I log a variable value in console it give me a null . I know that's because JSON is asynchronous but I don't know a work around this.
I tried using multiple functions and passing values one by one and adding div by div. However that is not doing what I want to do and gives a messed up structure.
How can I collect all the required values that I get in a JSON and combine them in a single div and place it in a div in my HTML structure.
Edit:- Code
$(document).ready(function(){
$("#Search_Button").click(function() {
var name;
name = $("#value").val();
if(!name){
console.log("Enter a name");
}
search(name);
});
function search(name){
var url = "url_here";
$.getJSON(url,function(data){
$.each(data.results,function(i,j){
displayImage(j.path);
displayOverview(j.id);
});
});
}
function displayOverview(id){
var url = "url_here";
$.getJSON(url,function(data){
var overviewx = data.overview;
var newoverview='';
for(var x=0;x<overviewx.length && x<100 ;x++){
newoverview+=overviewx[x];
}
var str = '<div class="col-md-4">' + newoverview +
'</div>';
$("#place_here").append(str);
});
}
function displayImage(id){
var url = "url_here";
var str = '<img src="' + url + '"</img>';
$("#place_here").append(str);
console.log(str);
}
});
I want to place both(and maybe more) tags in a single div from displayOverview and from displayImage and place that div into my main HTML Structure.
This is just an exemple !
to prevent asynchronous processing,we use callbacks
function getItem(){
var dfd = jQuery.Deferred();
var url_to_json = 'json/test.json';
$.getJSON(url_to_json, function(data) {
dfd.resolve(data);
});
return $dfd.promise();
}
when you need a the response you just :
getItem.done(function(data){
console.log(data);
});

Get the id numbers (separatly) from the url and use it to select the id with that ID number (using jquery)

I am working on a website where I dont have any control on the code (functionality side. however even if I had the access I wouldn't be able to make any changes as I am a front end designer not a coder..lol). The only changes I can make is CSS, js.
What I am tring to do:
I got the url on the page like this:
www.test.com/#box1#box3#box5
(I am not sure if I can have more than one ID in a row. please advice. However thats how the developer has done it and I dont mind as there are no issues yet)
the page html
<div id="box1"></div>
<div id="box2"></div>
<div id="box3"></div>
<div id="box4"></div>
<div id="box5"></div>
I would like to take different ids from the URl and use it to hidhlight the divs with that ID (by addding a class name "highlight")
The result should be like this:
<div id="box1 highlight"></div>
<div id="box2"></div>
<div id="box3 highlight"></div>
<div id="box4"></div>
<div id="box5 highlight"></div>
I would like to learn the smart way of taking just the id numbers from the url and use it to select the div with that paticulat no.
just a quick explanation:
var GetID = (get the id from the URL)
$('#box' + GetID).addClass('highlight');
Try This...
var hashes =location.hash.split('#');
hashes.reverse().pop();
$.each(hashes , function (i, id) {
$('#'+id).addClass('highlight');
});
Working fiddle here
var ids = window.location.hash.split('#').join(',#').slice(1);
jQuery(ids).addClass('highlight');
or in plain JS:
var divs = document.querySelectorAll(ids);
[].forEach.call(divs, function(div) {
div.className = 'highlight';
});
There are various way to resolve this issue in JavaScript. Best is to use "split()" method and get an array of hash(es).
var substr = ['box1','box2']
// Plain JavaScript
for (var i = 0; i < substr.length; ++i) {
document.getElementById(substr[i]).className = "highlight"
}
//For Each
substr.forEach(function(item) {
$('#' + item).addClass('highlight')
});
//Generic loop:
for (var i = 0; i < substr.length; ++i) {
$('#' + substr[i]).addClass('highlight')
}
Fiddle - http://jsfiddle.net/ylokesh/vjk7wvxq/
Updated Fiddle with provided markup and added plain javascript solution as well -
http://jsfiddle.net/ylokesh/vjk7wvxq/1/
var x = location.hash;
var hashes = x.split('#');
for(var i=0; i< hashes.length; i++){
var GetID = hashes[i];
//with jQuery
$('#box' + GetID).addClass('highlight');
//with Javascript
document.getElementById('box' + GetID).className = document.getElementById('box' + GetID).className + ' highlight';
}

Count html elements in ajax returned data

I've got a jquery $.ajax call that returns a set of html from data.html which is like;
<div class="blah"><li>test</li></div>
<div class="blah"><li>test</li></div>
<div class="blah"><li>test</li></div>
<div class="blah"><li>test</li></div>
I'd like to count the amount of elements that have a class of .blah and i'm not sure how to do this.
I've tried:
data.html.getElementsByClassName('blah').length
but that obviously doesn't work!
Any suggestions gratefully received!!
Try utilizing .hasClass()
var data = {};
data.html = '<div class="blah item item-wrapper print"></div>'
+ '<div class="blah item item-wrapper digital"></div>';
var len = $.grep($.parseHTML(data.html), function(el, i) {
return $(el).hasClass("blah")
}).length;
$("body").html(len);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js">
</script>
You should be able to do this using either .filter() or .find(), depending on the exact format of your returned HTML. If the format is is exactly as you have stated, then the following should work:
$.get("data.html", function(data) {
var length = $(data).filter(".blah").length;
});
If there is some sort of wrapper element around your items with class blah, then you would use .find():
$.get("data.html", function(data) {
var length = $(data).find(".blah").length;
});
$('.blah','context').length
Replace context by object in which you want to search

Categories