Get control attributes with jQuery and create json - javascript

I have multiple checkboxes in a view and each one has some data attributes, example:
Once the button is clicked I'm iterating through all the checkboxes which are selected and what I want to do is get the data-price and value fields for each selected checkbox and create JSON array.
This is what I have so far:
var boxes2 = $("#modifiersDiv :checkbox:checked");
var selectedModifiers = [];
var modifierProperties = [];
for (var i = 0; i < boxes2.length; i++) {
for (var k = 0; k < boxes2[i].attributes.length; k++) {
var attrib = boxes2[i].attributes[k];
if (attrib.specified == true) {
if (attrib.name == 'value') {
modifierProperties[i] = attrib.value;
selectedModifiers[k] = modifierProperties[i];
}
if (attrib.name == 'data-price') {
modifierProperties[i] = attrib.value;
selectedModifiers[k] = modifierProperties[i];
}
}
}
}
var jsonValueCol = JSON.stringify(selectedModifiers);
I'm not able to get the values for each checkbox and I'm able to get the values only for the first one and plus not in correct format, this is what I'm getting as JSON:
[null,"67739",null,"1"]
How can I get the correct data?

You can use $.each to parse a jquery array, something like:
var jsonValueObj = [];
$("#modifiersDiv :checkbox:checked").each(function(){
jsonValueObj.push({'value':$(this).val(),'data-price':$(this).attr('data-price')});
});
jsonValueCol = JSON.stringify(jsonValueObj);
Please note it's generally better to use val() than attr('value'). More information on this in threads like: What's the difference between jQuery .val() and .attr('value')?
As for your code, you only had one answer at most because you were overwriting the result every time you entered your loop(s). Otherwise it was okay (except the formatting but we're not sure what format you exactly want). Could please you provide an example of the result you would like to have?

if you want to get an object with all checked values, skip the JSON (which is just an array of objects) and make your own....
var checked =[];
var getValues = function(){
$('.modifiers').each(function(post){
if($(this).prop('checked')){
checked.push({'data-price':$(this).attr('data-price'),'value':$(this).attr('value')});
}
});
}
getValues();
sure i'm missing something obvious here.. but mind is elsewhere

This should give an array with values (integers) and prices (floats):
var selected = [];
$("#modifiersDiv :checkbox:checked").each(function()
{
var val = parseInt($(this).val(), 10);
var price = parseFloat($(this).data("price"));
selected.push(val);
selected.push(price);
});
Edit: Updated answer after Laziale's comment. The $(this) was indeed not targeting the checked checkbox. Now it should target the checkbox.

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));
});
});

get the values of the options in the dropdown after moving them from one to another

I have 2 drop downs and I can move the objects from one to another using the buttons. I want to get the updated values after I am done with moving them from one drop down to another. the values in the array is coming out to be null.
How can I get the updated value of all the options in an array. I need to pass the updated values to the controller from one function like function AddFiles(iniIdArray,afterIdArray)
http://jsfiddle.net/678hmujh/1/
var varInitialId = document.getElementById('iniId');
for (i = 0; i < varInitialId.options.length; i++) {
iniIdArray[i] = varInitialId.options[i].value;
}
var varAfterId = document.getElementById('afterId');
for (i = 0; i < varAfterId.options.length; i++) {
afterIdArray[i] = varAfterId.options[i].value;
}
You could use map: http://jsfiddle.net/678hmujh/4/
$('#listButton').on('click', function() {
var first = $('#iniId option').map(function(){ return this.value; });
var second = $('#afterId option').map(function(){ return this.value; });
console.log( first.toArray() );
console.log( second.toArray() );
});
By doing first.toArray() or second.toArray() you can get a basic javascript array of what was built.
$('select#iniId > option').each(function() {
$(this).text(); //is your option text
$(this).val(); //is your option value
});

how to give $('inputs') each function as to store data as key value pair in asp.net

$("#btnSubmit").click($('#form1 input'), function() {
var data = new Object();
for (var i =1; i < form1.length-1; i++) {
data[i] = form1[i].name + ":" + form1[i].value ;
}
document.write(JSON.stringify(data));
How to avoid view state and how to get string json output?
$("#btnSubmit").click($('#form1 input'), function() {
var data = [];
for (var prop in form1) {
data.push(form1[prop]);
}
document.write(data);
});
jsfiddle
An easy way to select only desired input elements is, to put a class on them then select elements based on that class. $('#form1 input.post').each(...)
Another way is to select all input elements and keep a not selector for those which you want to exclude.
To parse array back from json string you can use $.parseJSON(jsonString)
You can see the sample fiddle here.

How do I apply different changes to each control when selecting by class?

I've got a series of checkboxes with the same class. I want to get all the checkboxes with that same class as a collection and extract their id and checked status. But all the select by class examples I've seen just apply a single change to all elements of that class. I need to get a collection/array of all the checkbox elements with that class so I can iterate over them.
Ok, I've tried some of the suggestions and had no luck.
This throws an Object Expected error in IE8:
var checkboxes = document.querySelectorAll("input[type='checkbox'].chkRoles");
And this gives me an empty array every time, regardless of what's checked.
var mandatoryRoleIDs = [];
$('input.chkRoles[type="checkbox"]').each(function (i, checkbox)
{
if ($(checkbox).attr('checked'))
mandatoryRoleIDs.push($(checkbox).attr('id'));
});
Since your question is tagged with jQuery, here's how you can do it with jQuery's each() function:
$('input.someClass[type="checkbox"]').each(function(i,el){
var $this = $(el),
id = $this.attr('id'),
checked = $this.attr('checked');
/* do stuff with id and checked */
});
var checkboxes = document.getElementsByClassName('classname');
Then iterate over it to do what you need.
for(var i = 0; i < checkboxes.length; i++) {
var current = checkboxes[i];
// stuff on current
}
Using jQuery is not necessary in this simple case, and querySelectorAll is not totally supported by older browser; Vanilla JS is the best way to do it!
Since you need to support IE8(damn Microsoft) you should do something like this:
var inputs = document.getElementsByTagName('input'),
className = "classname";
for (var i = 0; i < inputs.length; i++) {
var current = inputs[i];
if (current.type !== 'checkbox' || current.className.indexOf(className) === -1) continue;
//do stuff with current
}
See a working JSFiddle example of this snippet.

How do you write to a span using jQuery?

I'm trying to populate a <span></span> element on the page load with jQuery.
At the moment the value that gets populated into the span is just an integer count.
Here I have named my span userCount:
Users<span id = "userCount"></span>
I am trying to write the value of the span with no success.
$(document).ready(function () {
$.post("Dashboard/UsersGet", {}, function (dataset) {
var obj = jQuery.parseJSON(dataSet);
var table = obj.Table;
var countUsers;
for (var i = 0, len = table.length; i < len; i++) {
var array = table[i];
if (array.Active == 1) {
var name = array.Name;
}
countUsers = i;
}
userCount.innerHTML = countUsers.toString();
});
});
You don't have any usercount variable. Use $(selector) to build a jquery object on which you can call functions like html.
$('#userCount').html(countUsers);
Note also that
you don't need to convert your integer to a string manually.
if you don't break from the loop, countUsers will always be table.length-1.
you have a typo : dataSet instead of dataset. Javascript is case sensitive.
you don't need to parse the result of the request
you don't need to pass empty data : jQuery.post checks the type of the provided parameters
So, this is probably more what you need, supposing you do other things in the loop :
$.post("Dashboard/UsersGet", function (dataset) {
var table = dataset.Table;
var countUsers = table.length; // -1 ?
// for now, the following loop is useless
for (var i=0, i<table.length; i++) { // really no need to optimize away the table.length
var array = table[i];
if (array.Active == 1) { // I hope array isn't an array...
var name = array.Name; // why ? This serves to nothing
}
}
$('#userCount').html(countUsers);
});
Use .html()!
Users<span id = "userCount"></span>
Since you have assigned an id to the span, you can easily populate the span with the help of id and the function .html().
$("#userCount").html(5000);
Or in your case:
$("#userCount").html(countUsers.toString());
Change:
userCount.innerHTML = countUsers.toString();
to:
$("#userCount").html(countUsers.toString());
Instead of:
userCount.innerHTML = countUsers.toString();
use:
$('#userCount').html(countUsers.toString());
You could use
$('#userCount').text(countUsers);
to write data to span
The call back argument should be dataSet rather than dataset?

Categories