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));
});
});
Related
Here is my fiddle : DEMO
Under the "Rules" Tab, on click of "+" a group of form-fields are cloned i.e, Join operator, Attributes, Operator & Threshold.
The attribute drop down is populated using a json (called expressionDetails) created using the relationship between contracts and thresholds variables.
Based on the choice of attributes, the thresholds field will be populated.
I could achieve this for the non-cloned Attribute and Threshold. However, due to class/ id duplication I am not able to pick up the cloned attribute's value as all the clones attributes hold the same class and their values are getting concatenated (in var z1).
//Appending option to "cloned" thresold field based on choice of attribute
$('.attributeExpr').on('change', function(e) {
$('.thresholdExpr').empty();
var z1 = $(".attributeExpr option:selected").text();
console.log(z1);
var a1 = expressionDetails[z1];
console.log(a1);
for (var i1 = 0; i1 < a1.length; i1++) {
var b1 = a1[i1].name;
// alert(b1);
var opt1 = $("<option>").text(b1);
// console.log(opt1);
$('.thresholdExpr').append(opt1);
}
});
Is there a different approach for this? Also, it should work for every cloned group thereafter as I will be using all of these values to create the "Expression" field.
Any help would be much appreciated. Thank you.
Replace the line 3 in above code with this. it will only return selected value.
var z1 = $("option:selected",$(this)).text();
Have you tried something like:
var z1 = $(this).find('option:selected').text();
Instead
var z1 = $(".attributeExpr option:selected").text();
Try this, I have tested it in your fiddle DEMO and it is working.
$('.attributeExpr').on('change', function(e) {
var index = $(this).index('.attributeExpr');
$('.thresholdExpr:eq( '+index+' )').empty();
var z1 = $(this).find("option:selected").text();
console.log(z1);
var a1 = expressionDetails[z1];
console.log(a1);
for (var i1 = 0; i1 < a1.length; i1++) {
var b1 = a1[i1].name;
// alert(b1);
var opt1 = $("<option>").text(b1);
// console.log(opt1);
$('.thresholdExpr:eq( '+index+' )').append(opt1);
}
});
I have added index so it can target the current element.
First thing you should do to make it work properly specially such complex implementation is to make the expressionsBuilder formgroup option fields to be dynamic, means it is being populated by JavaScript and not hard-coded in your HTML.
Then, you will assign the change event listener for each individual fields you created, this way you can control every form-group's behavior.
example click here
by populating it programatically you have total control of the fields behavior. You can then get each and every value of fields by iterating expressions variable like this:
for (var i = 0; i < expressions.length; i++)
{
var id = expressions[i];
var theAttribute = $("#" + id).find("[name='attribute']").val();
var theOperator = $("#" + id).find("[name='operator']").val();
var theThreshold = $("#" + id).find("[name='threshold']").val();
}
Hope that helps
===
ALSO heads up, it appears you are creating such complex application. I am suggesting you should make use for JavaScript frameworks to ease up maintainability of your code. This approach will become very hard to maintain in the long run
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.
I currently have the following code that looks at an unordered list and selects a random item. I want to make sure the same 'li' doesn't get selected twice in a row, or even better, don't select a repeat li until all of them have been selected.
var list = $('#headshots li:visible').toArray();
var elemlength = list.length;
var randomitem = list[Math.floor(Math.random() * elemlength)];
Full code:
function sawpHomepageAgencyHeadshots() {
var fullList = [1,2,3,4,5,6,7,8,9,10];
window.setInterval(function(){
var random = fullList.slice(0).sort(function() {
return .5 - Math.random();
});
$('#headshots li').each(function() {
var i = parseInt($(this).css('background-image').replace(/\D+/, ''));
random = $.grep(random, function(value) { return value != i; });
});
var list = $('#headshots li:visible').toArray();
var elemlength = list.length;
var randomitem = list[Math.floor(Math.random()*elemlength)];
$(randomitem).css({'background-image': 'url("' + absoluteDomainPath + 'images/headshots/headshot-' + random[0] + '.jpg")'});
}, 3000);
}
Added fiddle: http://jsfiddle.net/MBP2t/
remove the random item from the list variable, then it can not be selected again.
Take a look at this fiddle where I use an interval to select each item randomly.
http://jsfiddle.net/ghcNM/
var list = $('#headshots li:visible');
var loop = setInterval(doit, 500);
function doit(){
if(list.length){
randomitem = list.splice(Math.floor(Math.random() * list.length), 1)
$(randomitem).css('background', '#ff0000');
}else{
clearInterval(loop);
}
}
You need to maintain state somewhere in your application, so there are two basic options here:
Do it in memory:
Keep an array of visited items, then, when you pull an item, check if it's in the list you've already seen. If it's not, add it to the list. If it is, randomly pick again.
Do it in the DOM:
Do you search for a node like this: $('#headshots li:visible').not('.seen')
After you've found an item, do item.addClass('seen') to mark it as seen, then continue.
Once your jQuery selector returns no values, you can remove the seen class from all elements.
For what it's worth, the second option is pretty gross.
I've been trying this for a while now and could not find anything online...
I have a project, where tablerows get added to a table. Works fine.
Now I want to save the Table in the localStorage, so I can load it again. (overwrite the existing table).
function saveProject(){
//TODO: Implement Save functionality
var projects = [];
projects.push($('#tubes table')[0].innerHTML);
localStorage.setItem('projects', projects);
//console.log(localStorage.getItem('projects'));
The problem is the Array "projects" has (after one save) 2000+ elements. But all I want is the whole table to be saved to the first (or appending later) index.
In the end I want the different Saves to be listed on a Option element:
function loadSaveStates(){
alert('loading saved states...');
var projects = localStorage.getItem('projects');
select = document.getElementById('selectSave'); //my Dropdown
var length = projects.length,
element = null;
console.log(length);
for (var i = 0; i < length; i++) {
element = projects[i];
var opt = document.createElement('option');
opt.value = i;
opt.innerHTML = 'project ' + i;
select.appendChild(opt);
}
}
Can anyone tell me what I am doing wrong?
You can easily do this by jquery, are you interested in this, if yes.. then try following code
For setting the value
$.jStorage.set("projects", $.trim(projects));
For Getting the data
$.jStorage.get("projects");
For deleting the data with key
$.jStorage.deleteKey("projects");
I coose to stay with localStorage, but insted of using an Array I just let the user give every project a name and create a new Item for every Save:
function saveProject(){
//TODO: Implement Save functionality
var pname=prompt("Please enter your project name:","projectname")
var text = $('#mainTable')[0].innerHTML;
//console.log(text);
localStorage.setItem(pname, text);
//console.log(localStorage.key(2));
loadSaveStates();
}
function loadProject(){
var selected = $('#selectSave')[0].selectedIndex
//console.log(selected);
if (localStorage.key(selected) == 'jStorage'){
selected++;
}
var innerHTMLTable = localStorage[localStorage.key(selected)];
//console.log(innerHTMLTable);
$('#mainTable')[0].innerHTML = innerHTMLTable;
updateHandlers();
}
function deleteProject(){
var selected = $('#selectSave')[0].selectedIndex
var pname = $('#selectSave')[0].options[selected].value
$('#selectSave')[0].remove(selected);
localStorage.removeItem(pname);
//console.log(pname);
loadSaveStates();
}
I have 2 arrays, one with cities, and another array with ID's...
I would like to loop both, and then output some HTML
Right now im only looping cities, and then appending some HTML to a as following:
if ($jq(".area").length > 0) {
var region = $jq(".hiddenFieldRegion").val();
var cityIDs = $jq(".hiddenFieldChosenAreas").val();
var strcities = $jq(".hiddenFieldChosenCities").val();
//var cities = strcities.split('|');
//Set region to be marked
if (region) {
$jq(".mapdk").attr("class", region);
}
//Appending to searchform
if (strcities) {
$jq.each(strcities.toString().split("|"), function (k, v) {
var v = v.split("|");
$jq("<option selected />").text(v[0]).appendTo("select.chosen-cities");
});
}
}
I would like the place where im appending to the searchform, add an attribute value, with an ID from the cityIDs array...
So i get some HTML like:
<option value="XXX">CityName</option>
Is that possible?
Assuming your cities IDs and your cities names are orderred in the same way, you can access each name/id by this index in the arrays :
var cityIDs = $jq(".hiddenFieldChosenAreas").val();
var strcities = $jq(".hiddenFieldChosenCities").val();
var cityIDs_array = cityIds.split("|");
var strcities_array = strcities.split("|");
....
if (strcities) {
$jq.each(strcities_array, function (k, v) {
//var v = v.split("|"); Unnecessary if strcities is like "city1|city2|city3"
$jq("<option value='"+cityIDs_array[k]+"' />").text(v).appendTo("select.chosen-cities");
});
}
In this, way, you can access each city ID in your loop.
But I think you should store city name and city id in the same string. For example "city1:1|city2:2|city3:3". Then, with some use of split function, you'll get id and name.
Assuming the order is the same in both arrays you can use the index parameter (k) of the each function:
if (strcities) {
var aCityIDs = cityIDs.split("|");
$jq.each(strcities.toString().split("|"), function (k, v) {
var v = v.split("|");
var id = aCityIDs[k];
$jq("<option selected value='"+id+"' />").text(v[0]).appendTo("select.chosen-cities");
});
}
This is easy enough if your two arrays are in parity with one another with regards to indexing - loop over one, then look up a value in the other array at the same index.
//simulate environment
var strcities = 'one|two|three',
cityIDs = '1|2|3';
//main code
var ids = cityIDs.split('|');
$.each(strcities.toString().split("|"), function (index, val) {
var opt = $("<option />", {value: ids[index], text: val}).appendTo("select.chosen-cities");
/* if (index == 2) opt.prop('selected', 'selected'); /*
});
A few points of note:
you were splitting on | once in the $.each and again inside it. Since this would be illogical (any | would have disappeared after the first split) I removed it.
you were adding selected to each option. If you simply want the first option to be selected, you don't need to add anything in. If you want a specific option to be selected, see the line I commented out, which selects the 3rd element.
http://jsfiddle.net/DhH3U/
Another example:
var strict = ('aaa|eeee|dddd').split('|');
var id = ('1|2|3').split('|');
$.each(strict, function (k) {
$("<option selected />").text(strict[k]).appendTo("select.chosen-cities").attr('value',id[k]);
});