Jquery getting nested inputs of Div, placing in Object - javascript

I am at my wits end with this nested loop.
I am trying to create an object with nested objects in it grouped by the containing div id.
So far this is what I have:
$('#survey-submit').on('click', function (e) {
var formData = {};
var item = {};
$("div[id^='question-']").each(function () {
var id = '#' + $(this).attr('id');
var $this = $(this);
formData[id] = $this.children('input, select,checkbox').each(function () {
item[this.name] = this.value;
});
//console.debug(formData);
});
console.debug(formData);
return false;
});
The result of the console log is all the input elements of the divs that have the start like question, I get the expected number of new objects all dynamically named, but they all contain the same thing.
The contents of each object are not specific to the this object I am trying to generate it from, any help would be appreciated!

I found a solution to the problem here : jquery how to get form element types, names and values
I wound up doing this:
$("div[id^='question-']").each(function () {
var id = '#' + $(this).attr('id');
var $this = $(this);
var inputs= $(id+' :input').map(function(index, elm) {
return {name: elm.name, value: $(elm).val()};
}).get();
formData[id]=inputs;
});

Related

A function to affect multiple rows to substr and copy with Javascript

So, i have this code, it works:
var curp = document.getElementById("id_sc_field_curp_id_1");
var getcurp = curp.options[curp.selectedIndex].text;
var rfc = getcurp.substr(0, 10);
document.getElementById("id_sc_field_virtual_rfc_1").value = rfc;
It copy the text inside the field (td - CURP) "id_sc_field_curp_id_1", and trim it to put the result in another field (RFC) "id_sc_field_virtual_rfc_1"
Example img
JSFIDDLE: https://jsfiddle.net/90yzgcqe/1/
I want to adapt the code to work with the other rows, witch have an incremental id...
id_sc_field_curp_id_1,id_sc_field_curp_id_2,id_sc_field_curp_id_3, d_sc_field_virtual_rfc_1, d_sc_field_virtual_rfc_2, d_sc_field_virtual_rfc_3...etc
Im making this function, but... i dont know how to make it work...
function rfc() {
for (var i = 0; i <= 19; i++) {
var curp = document.getElementById("id_sc_field_curp_id_" + i);
var getcurp = curp.options[curp.selectedIndex].text;
var rfc = getcurp.substr(0, 10);
document.getElementById("id_sc_field_virtual_rfc_" + i).value = rfc;
}
}
What is wrong?
Some jQuery gets us there fairly easily, first get the matching dropdowns and then interact with them.
$(function() {
//get the list of dropdowns that start with all but the numeral
var lst = $("[id^='id_sc_field_curp_id_']");
$.each(lst, function(idx, elem) {
//lets store the dropdown for use in the loop
let $field = $(elem);
//for example lets print the selected text
console.log($field.find("option:selected").text());
});
});
There are a couple of options from there, you can use the dropdown to create the rfc's id, or use the jQuery function closest() to get it. Once you have the associated rfc's input it should be trivial to get set the value.
EDITED:1
More specific javascript, and a link to a modified jsFiddle
$(function() {
//get the list of dropdowns that start with all but the numeral
var lst = $("[id^='id_sc_field_curp_id_']");
$.each(lst, function(idx, elem) {
//lets store the dropdown for use in the loop
let $field = $(elem);
//for example lets alert the selected text
alert($field.find("option:selected").text().substr(0,10));
$field.closest("[id^='idVertRow']")
.find("[id^='id_sc_field_virtual_rfc_']")
.val($field.find("option:selected").text().substr(0,10));
});
});

jQuery grabbing value of a dynamic data-* attribute

Inside of a jQuery click event listener I have some code like this:
function (evt) {
evt.preventDefault();
var reportbox = $(this).closest('.activityItem');
var id = reportbox.data('questionId');
...
}
This works fine for data-question-id attributes, but I'm generalizing the function now and I need to grab the value from any of the following:
data-question-id
data-answer-id
data-comment-id
data-user-id
data-company-id
What's the best way to do this?
If you know only one of those attributes will be present and you want to retrieve that single value you can use this:
var element = $(el);
var dataAttrs = ['question-id', 'answer-id', 'comment-id', 'user-id', 'company-id'];
var data = getUnknownAttr(element, dataAttrs);
function getUnknownAttr(element, potentialAttrs) {
var $element = element instanceof $ ? element : $(element);
var result = null;
potentialAttrs.forEach(function (attr) {
var temp = $element.data(attr);
if (typeof temp !== 'undefined') {
result = temp;
}
});
return result;
}
As Brian points out, you could access the dataset property to retrieve all the element's data-* attributes:
$('.activityItem').each(function () {
var dataAttributes = this.dataset;
Object.keys(dataAttributes).forEach(function (key) {
console.log(key, dataAttributes[key]); // key, value
});
});
Since you only want the first data attribute, you could simply use:
var dataAttributes = this.dataset;
var id = dataAttributes[Object.keys(dataAttributes)[0]];
It's important to note that the dataset property returns the attribute names in camel case without the data prefix. In other words, data-question-id would be questionId.
If you want to retrieve all of an element's attributes, access the attributes property and check which attributes start with data-* and end with -id. It's definitely more verbose, but it may work better in other scenarios.
$('.activityItem').each(function () {
var attributes = this.attributes;
Object.keys(attributes).forEach(function (key) {
var attribute = attributes[key];
if (/^data-.*-id$/.test(attribute.name)) {
console.log(attribute.name, attribute.value);
}
})
});
I just thought of what I was looking for. I guess my question confused you, but here's what I wanted:
$('#test').children().each(function () {
var reportbox = $(this);
var id = reportbox.data(Object.keys(reportbox.data())[0]);
reportbox.text(id);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="test">
<div data-question-id="1"></div>
<div data-answer-id="2"></div>
<div data-comment-id="3"></div>
<div data-user-id="4"></div>
<div data-company-id="5"></div>
</div>
The line of focus being:
var id = reportbox.data(Object.keys(reportbox.data())[0]);
Edit
Alternatively thanks to #Brian's comment I can rewrite this to:
var id = this.dataset(Object.keys(this.dataset)[0]);

Jquery insert function params into selector

I have a Jquery function that helps with validation over 1 object. I need to expand it so that the function will run over 3 different objects. I am trying to define a function that takes a parameter(whichquote) to insert the appropriate object in the function. Here is my code. What I am doing wrong? I assume I do not have the selector correct as the code works if I put it in.
Original Function that works:
var depends = function() {
var selectorD = $("input[name^='lead[quote_diamonds_attributes]'], select[name^='lead[quote_diamonds_attributes]']");
var vals = '';
selectorD.not(':eq(0)').each(function () {
vals += $(this).val();
});
return vals.length > 0;
};
Function I am trying to create that allows me to use it on other objects. This currently does not work.
var depends = function(whichquote) {
var selectorD = $("input[name^='lead[+ whichquote +]'], select[name^='lead[+ whichquote +]']");**
var vals = '';
selectorD.not(':eq(0)').each(function () {
vals += $(this).val();
});
return vals.length > 0;
};
I think the problem is with my concating in the var selectorD but cannot seem to get the syntax correct.
Your selector isn't actually inputting whichquote because the string concatenation is incorrect.
Try
var selectorD = $("input[name^='lead[" + whichquote + "]'], select[name^='lead[" + whichquote +"]']");

Search in an Object Array with more than one condition jQuery grep()

I have an Object Array with Key-Value pair on jQuery like this
And I am searching in these arrays to find a match with with an id that I will provide so I have
var result = $.grep(records, function(e){ return e.id== id; });
So this looks like, search a record in the array with an id of whatever the value of id that i passed it. It works fine but what if I want to pass two parameters to match the records in the array? let's say columnheader and parent_colheader? What will my previous
var result = $.grep(records, function(e){ return e.id== id; });
syntax should be?
Use multiple variables with &&
var id = 1;
var columnheader = 'test';
var parent_colheader = 'test';
var result = $.grep(records, function(e) {
return e.id == id && e.columnheader == columnheader && e.parent_colheader == parent_colheader;
});

How to assign variable to json object

'I'm trying to assign a variable from a parent div to the json string of a child table and can't seem to get my javascript straight.
What I'd like to see, or some variation of:
{"blocks":[{"id":"115",courses:[{"Semester":"S,F","Credits":"3","Subject":"ACT"}‌​, {"Semester":"F","Credits":"6","Subject":"CSI"}]}]
And the jQuery I have so far.
$('#update').click(function (e){
var table = $('#table').tableToJSON();
var blockId = $('#table').closest('div.Block').attr('id');
table = {"block":table};
document.getElementById('courseList').value = JSON.stringify(table);
}
I'm not sure how to add in the variable that I need in the object? How would I insert blockId?
I'm assuming bracket notation is what you're really looking for :
$('#update').on('click', function(){
var table = $('#table').tableToJSON();
var blockId = $('#table').closest('div.Block').attr('id');
var table2 = {};
table2[blockId] = table;
$('#courseList').val( JSON.stringify(table2) );
});

Categories