Retrieving xml namespace child element value using jquery - javascript

Folks.
I am new to jquery and I checked out alot of the postings here when it comes to parsing namespace formatting .xml using jquery. After going over my code and looking at the examples I am struggling grabbing a value from a nested child element. Below is my xml snippet:
<offers:offer-bundle>
<cash:offer lang="EN" offer-type="Cash">
<cash:cash>
<cash:cannot-be-combined-with></cash:cannot-be-combined-with>
<cash:cash-amount>1000</cash:cash-amount>
<cash:requires-tfs-financing>false</cash:requires-tfs-financing>
<cash:stackable-with-apr>false</cash:stackable-with-apr>
<cash:stackable-with-lease>false</cash:stackable-with-lease>
<cash:sub-type-labels>Cash Back</cash:sub-type-labels>
</cash:cash>
<cash:tfs-calculator>false</cash:tfs-calculator>
<cash:offer-label>Cash Back</cash:offer-label>
<cash:offer-label-num>7</cash:offer-label-num>
<cash:series-list></cash:series-list>
<cash:offer-id>cash_1433205220095</cash:offer-id>
<cash:start-date>2015-06-02</cash:start-date>
<cash:end-date>2015-07-06</cash:end-date>
<cash:title>2015 Cash Back Offer</cash:title>
<cash:use-for-email>false</cash:use-for-email>
<cash:description>I can get this value</cash:description>
<cash:offer-image/>
<cash:offer-image-alt/>
<cash:offer-image-disclaimer/>
<cash:offer-card>...</cash:offer-card>
<cash:bullets>...</cash:bullets>
<cash:disclaimers>
<cash:disclaimer>
**I NEED TO GET THIS CHILD ELEMENT VALUE.**
</cash:disclaimer>
</cash:disclaimers>
</offers:offer-bundle>
I am able to get the value of <cash:offer-card>, <cash:offer-id> etc. since it does not have any nested children. I am struggling with getting the child node of <cash:disclaimers>.
Here is what I've written so far:
$.ajax({
type : "GET",
url : webServiceURL,
dataType : "xml",
success : function (xml) {
$(xml).find('offers\\:offer-bundle, offer-bundle').each(function(index, value) {
var $incentive;
var $offer;
var $offerDescription;
var $offerDisclaimer;
//Do Cash: Condition code is executing, incentive is hard coded to 'cash'
if (incentive == 'cash') {
$incentive = $(this);
$offer = $incentive.find('cash\\:offer, offer');
$offerDescription = $offer.find('cash\\:description, description').text();
$offer.find('cash\\:disclaimers, disclaimers').each(function (i, v) {
console.log ("here executing" + $(i).find('cash\\:disclaimer, disclaimer').text() );
My console window prints out a blue little circle with the number 2 in it along with "here executing" and no value. Even if I use
$(this).find('cash\:disclaimers, disclaimers').each(function (i, v) { }) versus $offer.find('cash\:disclaimers, disclaimers').each(function (i, v) {
I get the same results in my console window. Any ideas or knowledge sharing would be greatly appreciate it.

Related

Populate items into SELECT with Jquery

I'm having trouble populating a SELECT with jquery, when the user writes the zipcode or part of it, it searches the database and returns this:
{"success":1,"id":"50","street":"Central One"},{"success":1,"id":"60","street":"Central Two"}
One success for each street it finds. For a single street and using a text input I'm using this
UPDATE 1 - FULL CODE
$(document).ready( function() {
$('#zip').blur(function(){
$.ajax({
url : '../../controller/zip.php',
type : 'POST',
data: 'zip=' + $('#zip').val(),
dataType: 'json',
success: function(data){
if(data.sucesso == 1){
$('#id').val(data.id);
$('#street').val(data.street);
}
}
});
return false;
})
});
How can I change this so I can populate a select box.
Thanks
What is being passed back for a single address is a single object from which you can grab the information. When there are multiple responses you need to go through each of them and handle them.
When we look at MDN's article it shows that we need a parent <select> tag and then we need to populate the children. The process would look like this:
Find / create parent select
[Optional] Remove previous child <option> tags
Loop through responses
Create a new <option> element
Populate the <option> with the appropriate value and content
Append it to the parent <select>
Some things to be aware of, if you're clearing the previous addresses each time you get a response from the database you'll want to remove these previous <option>s. This can be done either by .empty() if there are no other children in the parent or starting with the parent <select> and removing all child <options>.
Use this for adding items to select box dynamically:
var $selectBox = $('#selectboxId');
$selectBox.empty();
$.each(data, function (idx, val) {
if (val.success) {
$selectBox.append($('<option>', {
value: val.id,
text: val.street
}));
}
});
I would not encourage to do so; you're better off using a html-templating engine like mustache or handlebars.
Doing this kind of stuff in plain JS (string concatenation) is gross. It pollutes your sourcecode.
Anyways, this would do the trick to generate the necessary HTML:
function generateHTML(data){
return data.reduce(function(o,n){
return o+"<option value='"+n.id+"'>"+n.street+"</option>";
},"");
}
Here is the Fiddle to play with. If you need to filter for success, you could add a filter()
function generateHTML(data){
return data.filter(function(x){
return !!x.success;
}).reduce(function(o,n){
return o+"<option value='"+n.id+"'>"+n.street+"</option>";
},"");
}
You could easily use $("#selectBoxId").html(generateHTML(data)) to insert it to the DOM.
To fit it into your codebase, you should add it in the success handler:
success: function(data){
function generateHTML(data){
return data.reduce(function(o,n){
return o+"<option value='"+n.id+"'>"+n.street+"</option>";
},"");
}
$("select").html(generateHTML(data))
}
For the inner workings of Array.prototype.reduce() take a look at MDN and for Array.prototype.filter()
If the JSON being returned is a list [{...}, ..., {...}], then you can use Array.forEach. Here is the success callback:
function(data) {
data.forEach(function(item) {
if (item.success) {
// use item.id and item.street
}
});
}
If you have a <select> element, then you will want to be populating it with <options>, by appending an <option> element under each successful "if" branch in the forEach.
Assuming you already have the select element on the page and the data that is coming back from the server is an array of objects, this should work:
$.ajax({
url : '../../controller/zip.php',
type : 'POST',
data: 'zip=' + $('#zip').val(),
dataType: 'json',
success: function(data) {
var $items = [];
$.each(data, function(street) {
if(data.success === 1) {
$items.push($('<option />').attr({
value: street.id
}).text(street.street));
}
});
$('#your-select-element').append($items);
}
});
Notice this isn't setting the value for one option, it is creating <option> tags for each of the response's streets and appending them to a <select> element.

difficulty getting list of values from series of input elements inside table rows

I'm completely stumped. Granted, in java script i'm like that kid trying to jam a square peg into a round hole.
My high level objective: The admins want the ability to edit text surrounding some text boxes, as well as the ability to add and remove 'paragraph'. The reporters and users want the values that are in the textboxes to be used in comparisons, etc (which is the original functionality).
My Solution: This project uses a pretty messy value - attribute table (called an EAV?), which now has fields with associated fields and is self referencing. I decided to leverage this to minimize changes to the database, so the admin essentially creates a string, denotes the places a text box belongs using '{}', and assigns a name to the attribute into text boxes that appear directly below the paragraph.
My Problem: Textboxes generate fine, as soon as the admin stops typing the "{}" count is checked client side, and the correct number of textboxes are added/removed in rows below. However, when the "change" mode (and thereby save the new string) I also want to save the attribute names they selected. I can't seem to get the actual value out of the input. The java script below sends null to elementList. Closer inspection indicates that var fieldNames is getting two elements of "undefined" so it makes sense that I'm getting null. Its also apparent that Its hitting something, becuase the number aligns with there being two 'nameField' rows.
DOM (Hemed down to the essentials)
<tr data-editMode="TextMode" data-ordinal="0">
....
<td>
<a class="changeMode">
<tr class="nameField">
<td colspan='4'>
<input type="text" value="Testing">
<tr class="nameField">
....
Javascript
function getAssociatedTr(row) {
var associatedRows = [];
associatedRows.push(row);
row = row.next('tr');
var hasAnother = true;
while (hasAnother == true) {
if (row != null && row.hasClass("nameField")) {
associatedRows.push(row);
row = row.next('tr');
} else {
hasAnother = false;
}
}
return associatedRows;
}
$(".changeMode").live("click", function () {
var options = $(this).data("options");
var theRow = $(this).closest('tr');
var rows = getAssociatedTr(theRow);
var fieldNames = new Array();
rows.splice(0, 1);
for (var index = 0; index < rows.length; index++) {
{
fieldNames.push(rows[index].next('.nameField').val());
}
}
$(".modal-header", c.rowsModal).html("<h3>Changing edit mode" + options.table + "</h3>");
c.rowsModal.modal("show");
$.ajax({
type: "POST",
traditional: true,
data: { "Name": options.table, "Ordinal": options.row, "EditMode": options.editMode, "ElementNames": fieldNames },
url: "/contracts/changeeditmode/" + c.id.val(),
success: function (data) {
theRow.replaceWith(data);
$.validator.unobtrusive.parse("#supplementForm");
c.rowsModal.modal("hide");
for (j = rows.length - 1 ; j >= 0; j--) {
rows[j].remove();
}
}
});
});
Server side
public ActionResult ChangeEditMode(long id, AddTrackedRowViewModel model,
string editMode, List<string> elementNames)
{
}
As a side note, I'm open to constructive criticism on the JavaScript.
EDIT
I have updated the line to
fieldNames.push(rows[index].nextAll('input').first().val());
But still getting undefined.
SOLUTION
fieldNames.push(rows[index].find("input[type=text]").val());
In this line:
fieldNames.push(rows[index].next('.nameField').val());
you are using the selector ".nameField", but this get a "tr" element, if you want the textbox you need this:
fieldNames.push(rows[index].next('.valid').val());
or using other selector that give you the textbox.

Trying to get Jquery working with dynamic select forms in Rails and Active Admin

I'm trying to update a select box based on another..
In my active admin resource, I did the following just for some test data:
controller do
def getcols
list = new Hash
list = {"OPTION1" => "OPTION1", "OPTION2" => "OPTION2"}
list.to_json
end
end
In active_admin.js I have the following
$('#worksheet_type').change(function() {
$.post("/admin/getmanifestcols/", { ws_type: $(this).val() }, function(data) {
populateDropdown($("#column_0"), data);
});
});
function populateDropdown(select, data) {
 select.html('');
alert('hi');
$.each(data, function(id, option) {
select.append($('<option></option>').val(option.value).html(option.name));
});      
}
The above is working in the sense that when my primary select box is changed, the jquery is called and I even get the alert box of 'hi' to be called. However, it's not replacing the contents of the select box with my test OPTION1 and OPTION2 data.
I think I'm passing in the JSON wrong or something, or it's not being read.
What am i missing?
It looks to me as if you're not properly iterating over the map.
What about:
$.each(data, function(value, name) {
select.append($('<option></option>').val(value).html(name));
});
?

Dynamically updating html.listBox in MVC 1.0?

The client will choose an item from a dropDown list, this newly selected value will then be used to find assets linked to that selected item, these assets will then be loaded into the listBox.
This sounds simple enough, and I'm aware I could use a partial View but it seems overkill for just updating one component on a form.
Any
I've done this in MVC 1.0 myself. I used an onchange on the first drop down which called an action using the value selected. That action returned a JSON result. The jQuery script which called that action then used the JSON to fill the second drop down list.
Is that enough explanation, or would you like help writing the javascript, the action, or both?
Inside your view:
<%= this.Select("DDLName").Attr("onchange", "NameOfJavascriptFunction();") %>
<%= this.MultiSelect("ListBoxName") %>
The javascript will look like this:
function NameOfJavascriptFunction() {
var ddlValue = $("DDLName").val();
jQuery.ajax({
type: 'GET',
datatype: 'json',
url: '/Controller/Action/' + dValue,
success: updateMultiSelect
});
}
function updateMultiSelect(data, status) {
$("#ListBoxName").html("");
for(var d in data) {
$("<option value=\"" + data[d].Value + "\">" + data[d].Name + "</option>">).appendTo("#ListBoxName");
}
}
Finally, the action is something like this (put this in the controller and action from the first javascript):
public ActionResult Action(int id) //use string if the value of your ddl is not an integer
{
var data = new List<object>();
var result = new JsonResult();
this.SomeLogic.ReturnAnEnumerable(id).ToList().ForEach(foo => data.Add(new { Value = foo.ValueProperty, Name = foo.NameProperty }));
result.Data = data;
return result;
}
Feel free to ask follow up questions if you need any more explanation.

How to go trough JavaScript array?

I have this output from ajax call:
"total":"3",
"data":[{ "id":"4242",
"title":"Yeah Lets Go!",
"created":"1274700584",
"created_formated":"2010-07-24 13:19:24",
"path":"http:\/\/domain.com\/yeah"
}]
So there is three that kind of items in that array and I would need to go that through and print actual html out of it. So on page it would be:
Yeah Lets Go! (which is a link to http:www.domain.com/yeah)
Created: 2010-07-24 13:19:24
I'm clueles with this one.
Edit 1:
Also atm I get that raw output after clicking link. How can I get it to show on page load? Or it does that ajax call when I click link atm.
Edit 2:
I got it to output everything at once. But still I have a prolem with putting it actual html. The output atm is:
"total":"3",
"data":[{
"id":"4242",
"title":"Yeah Lets Go!",
"created":"1274700584",
"created_formated":"2010-07-24 13:19:24",
"path":"http:\/\/domain.com\/yeah"
}
{
"id":"4242",
"title":"Yeah Lets Go!222",
"created":"1274700584",
"created_formated":"2010-07-24 13:19:24",
"path":"http:\/\/domain.com\/yeah222"
}
{
"id":"4242",
"title":"Yeah Lets Go!333",
"created":"1274700584",
"created_formated":"2010-07-24 13:19:24",
"path":"http:\/\/domain.com\/yeah333"
}
]}
I would like to get that into list with title and link and creation day.
Edit 3 after answer from Luca Matteis:
Hmm, now im even more confused.
That JSON string comes out of this:
$('a.link').click(function() {
var item_id = $(this).attr("href").split('#')[1];
$.get(base_url+'/ajax/get_itema/'+item_id+'/0/3/true',
null,
function(data, status, xhr) {
$('#contentCell').html(data);
}
);
So I would need to do for that is something like:
var html = eval(data);
and then I would do what Luca Matteis suggest?
First off, that's a JSON string, you need to un-serialize the string into a real JavaScript object (look at json.org for this).
Once you have the native JavaScript data, something like this should work:
var html = '';
for(var i=0; i < obj.data.length; i++) {
html += ''+obj.data[i].title+'<br>';
html += 'Created: '+ obj.data[i].created;
}
Hmm, now im even more confused.
That JSON string comes out of this:
$('a.link').click(function() {
var item_id = $(this).attr("href").split('#')[1];
$.get(base_url+'/ajax/get_itema/'+item_id+'/0/3/true', null, function(data, status, xhr) {
$('#contentCell').html(data);
});
So I would need to do for that is something like:
var html = eval(data);
and then I would do what Luca Matteis suggest?

Categories