I am trying to push the object resultOBJ to the array resultArray
when the button "Добавить обозначение" is clicked.
first object has been sent well, the data is the same what I am looking for, but when I push another object the second object is rewriting the previous one, the third object is rewriting the first and the second and so on.
here is my code. Please, tell me what I am doing wrong.
Thanks in advance.
var color = {red:"#ff0000",purple:"#990099",green:"#33cc33",yellow:"#ffff00",blue:"#0000ff",orange:"#ff8000",pink:"#ff0080",
skyblue:"#00ffff",black:"#000000",gray:"#808080",brown:"#4d1f00"};
var diams = ["60","65","68","69","70","75","76","80","81","82","85","90"];
//show hidden elements
$(document).ready(function(){
$("#addRowDDL").click(function(){
$("#DDL,#deleteRowDDl,#useIt").fadeIn("slow");
});
});
var resultOBJ=new Object();
var resultArray = new Array();
var finalobj = {} ;
var obj = new Object();
function addDropDownLists(){
var myObject = $("#htmltoget").children().clone();
$("#DDL").append(myObject);
$.each(diams,function(key,value){
myObject.find(".chooseDiams").append($("<option></option>").attr("value",key)
.text(value));
});
$.each(color,function(key,value){
myObject.find(".chooseColor").append($("<option></option>").attr("value",key)
.text(key));
});
myObject.find(".chooseColor").change(function(){
displayColors(this);
});
myObject.find(".chooseDiams").change(function(){
displayDiams(this);
});
resultArray.push(obj);
}//End of addDropDownLists function
function displayColors(param){
var colorValues = $(param).val();
resultOBJ.color=colorValues;
}
function displayDiams(param){
var diamsValues = $(param).val() || [];
resultOBJ.diams=diamsValues;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<body>
<div id="htmltoget" style="display: none;">
<div class="DDL-Con">
<div class="diams">
<p>Диаметр</p>
<select class="chooseDiams" multiple>
<option selected hidden> Выбрать Диаметр</option>
</select>
</div>
<div class="color">
<p>Цвет</p>
<select class="chooseColor">
<option selected hidden>Выбрать Цвет</option>
</select>
</div>
</div>
</div>
<button type="button" id="addRowDDL" onclick="addDropDownLists()" style="margin-bottom: 20px;">Добавить обозначение</button>
<div id="bigwrapper">
<div id="DDL">
</div>
</div>
</body>
Having a hard time telling what you're trying to accomplish but you push obj which is empty and should be giving you an array of empty objects.
Also, you need to create a new object for each call of addDropDownLists() otherwise you are just passing a reference and the changes will effect every object in the array.
//show hidden elements
$(document).ready(function(){
$("#addRowDDL").click(function(){
$("#DDL,#deleteRowDDl,#useIt").fadeIn("slow");
addDropDownLists();
});
});
var resultArray = new Array();
function addDropDownLists(){
var resultOBJ=new Object();
var myObject = $("#htmltoget").children().clone();
$("#DDL").append(myObject);
$.each(diams,function(key,value){
myObject.find(".chooseDiams").append($("<option></option>").attr("value",key)
.text(value));
});
$.each(color,function(key,value){
myObject.find(".chooseColor").append($("<option></option>").attr("value",key)
.text(key));
});
myObject.find(".chooseColor").change(function(){
resultOBJ.color = $(this).val();
});
myObject.find(".chooseDiams").change(function(){
resultOBJ.diams = $(this).val() || [];
});
resultArray.push(resultOBJ);
console.log(JSON.stringify(resultArray));
}//End of addDropDownLists function
This setup does insert an empty object into the array the first time the button is clicked, or if there is no change. Not sure what you're trying to accomplish though so I left it as is.
Demo: https://jsfiddle.net/3p37znq1/2/
You don't push resultOBJ, you push obj which is always empty as you don't do anything with it after initialization.
When you push obj each time you just push a reference to the same instance instead of creating a new one. Any change to obj will affect all items in resultArray.
In change handler you always update the same instance of resultOBJ and this update always overwrites previous change. Actually, the values in this object mean "last selected color anywhere" and "last selected diam anywhere".
Something like this should work:
var resultArray = [];
function renderOption(value, name) {
var option = document.createElement("option");
option.value = value;
option.innerHTML = undefined === name ? value : name;
return option;
}
function updateResult(index) {
var item = resultArray[index],
node = document.querySelector("#DDL").childNodes.item(index);
item.diam = node.querySelector(".chooseDiams").value;
item.color = node.querySelector(".chooseColor").value;
}
function addDropDownLists() {
var container = document.querySelector("#DDL"),
index = resultArray.length,
changeHandler = updateResult.bind(null, index),
tpl = document.querySelector(".DDL-Con"),
node = tpl.cloneNode(true),
list, key, len
;
list = node.querySelector(".chooseDiams");
for (key = 0, len = diams.length; key < len; key++) {
list.appendChild(renderOption(diams[key]));
}
list.onchange = changeHandler;
list = node.querySelector(".chooseColor");
for (key in color) {
list.appendChild(renderOption(key, color[key]));
}
list.onchange = changeHandler;
container.appendChild(node);
resultArray.push({
diam: null,
color: null
});
updateResult(index);
}
PS: Sorry, I see you use jQuery... I'm too lazy to remember it's API. Haven't used it for a long time. Hope, you'll catch the main idea.
PPS: if you plan to delete items, maybe it's better to bind the whole node and search for it's index via isSameNode() method. Bound indexes will become invalid after removing item, they will shift.
I'm working on a project and there is a point which gives me some troubles.
I have a select form autofilled by a script. My select looks up to an array and add the array's values in the select as options.
But now I want to auto select options according to an array.
So I have my array which has some option name inside. Each index correspond to an option. So I would like to select options corresponding to one of the value in the array.
Here is some code :
var attributeFieldCrm = window.parent.Xrm.Page.getAttribute(fieldcrm);
var checkFieldCrmValue = attributeFieldCrm.getValue();
if (checkFieldCrmValue != null) {
console.log('breakpont hit !!!');
var optionSelected = new Array();
optionSelected = checkFieldCrmValue.split("$#");
console.log('les valeurs ont bien été récupérées : ', optionSelected);
var recceuilDesSelections = "";
var result = [];
var options = select && select.options;
var opt;
for (i in optionSelected) {
}
<select id="selectForm" class="selectpicker" multiple data-live-search="true">
</select>
I imagined something like 2 loop for, one going thought the array and for each index I check every options.
thanks for your help !
regards.
It seems that you didn't provide working code, but still:
var sel = document.getElementById('selectForm');
optionSelected.forEach((o)=>{
for (var i = 0;i < sel.options.length;i++) {
if (o == sel.options[i].value) sel.options[i].selected = true;
}
)}
I have a select tag with options that need to have two values assigned to them like so.
<select id="industry_churn" class="form-control">
<option value="0">Select a Value</option>
<option value="{.70, .05}">Salon/Barber</option>
<option value="{.95, .05}">Painting</option>
</select>
On the JavaScript side of things, I have the following function that makes multiple calculations:
function calculateAll() {
var averageJobs = +document.getElementById("averageJobs").value;
var jobValue = +document.getElementById("jobValue").value;
var yearsOpen = +document.getElementById("yearsOpen").value;
var industry_churn = +document.getElementById("industry_churn").value; /* array item 1 */
var recovery = +document.getElementById("industry_churn").value; /* array item 2 */
var inactive = (averageJobs * 50) * yearsOpen * industry_churn; /* Value 1 */
var missedRevenue = inactive * jobValue;
var jobsRecovered = (averageJobs * 50) * recovery * yearsOpen; /* Value 2 */
var revenueYear = jobsRecovered * jobValue;
document.getElementById("inactive").value = inactive;
document.getElementById("missedRevenue").value = missedRevenue;
document.getElementById("jobsRecovered").value = jobsRecovered;
document.getElementById("revenueYear").value = revenueYear;
}
The variable missedRevenue needs to pull item 1(industry_churn) from the option tag and the variable jobsRecovered needs to pull item 2(recovery) from the option tag.
How can I get my JavaScript to pull the values from the array?
If the format of your value attribute needs to be like that ("{.70, .05}"), then you could use match to turn that value into an array:
var arr = document.getElementById("industry_churn").value.match(/[\d\.]+/g).map(Number);
var industry_churn = arr[0];
var recovery = arr[1];
If however you have control over how the data is attached to the option tags, then consider setting the values to a JSON text:
<select id="industry_churn" class="form-control">
<option value="0">Select a Value</option>
<option value="[0.70, 0.05]">Salon/Barber</option>
<option value="[0.95, 0.05]">Painting</option>
</select>
and then:
var arr = JSON.parse(document.getElementById("industry_churn").value);
var industry_churn = arr[0];
var recovery = arr[1];
Note that with ES6 you can use the destructuring assignment syntax:
var [industry_churn,recovery]=JSON.parse(document.getElementById("industry_churn").value)
for the customerGroup selector I would like the option value to be test[i][1] of the multidimensional array and the text of the options to be test[i][0] of the array. How should I change ng-options?
For example if the 2D array consisted of [1,7],[2,8],[3,9] elements. I would like it to turn into <option value="1">7</option> etc etc
<select ng-model = "selectedGroup" class = "customergroup" ng-options = "val[][0] for val in cgOptions() track by val[][1]">
<option value = "">Select</option>
</select>
Also, on a side note is it possible to pass the function cgOptions later on into another function's parameter with something like exampleFunction(cgOptions)?
$scope.cgOptions = function () {
var test = [];
for (var i = 0; i < 4; i++) {
test[i][0] = i;
test[i][1] = i+10;
}
return test;};
Thank you in advance!
In ng-options when you do val in array, val becomes each element of the array. So, you'd need val[0] for the value, and val[1] for the display:
<select ng-model="selectedGroup"
ng-options="val[0] as val[1] for val in cgOptions()">
<option value="">select</option>
</select>
Also, bear in mind that you cgOptions() function should initialize the array for each iteration.
for (var i = 0; i < 4; i++) {
test[i] = []; // initialize the array first
test[i][0] = i;
test[i][1] = i+10;
}
I have a partial view which has a dropdown in it and I include that partial in my page twice. Here is the dropdown.
<form name="sortbyformtop">
<select onchange="sort('#querystring', this.options[this.selectedIndex].value);" name="sortbyselecttop">
<option value=""></option>
<option value="accommodationtype">Accommodation type</option>
<option value="mostreviewed">Most reviewed</option>
<option value="lowestprice">Lowest price</option>
</select>
</form>
Now, when the page loads, if the querystring contains a key sortby then I would like to take the value of sortby (which will be accommodationtype, mostreviewed, lowestprice i.e. the value of the options). What I'd like to do is set both dropdowns on the page to the option that matches the sortby query string value. I've tried lots of things but nothing is working.
Can you help?
Edit
I tried this but it did not work
$(document).ready(function () {
$("#sortbyselecttop option").filter(function () {
alert($(this).text());
return $(this).text() == "lowestprice";
}).first().prop("selected", true);
});
Not sure if I've read it well, but do you simply want the dropdown to select the value of the query string ?
If so, try this :
$('select[name="sortbyselecttop"]').val('accommodationtype');
It would be better if the select had a class name so you could set both dropdowns with one jQuery command.
here's a fiddle
you can not access a control with name like $("#name") this is a selector to select a DOM with ID only. but still you can set value of the dropdown like
$("select [name='sortbyselectop']").val(value);
assuming value is the variable in which your query string value is
function Querystring(qs)
{
this.params = {};
this.get = Querystring_get;
this.args = {};
qs = qs ? qs.replace(/^#/g, '') : location.search.substring(1, location.search.length);
if (qs.length == 0)
return;
qs = qs.replace(/\+/g, ' ');
this.args = qs.split('&');
for (var i = 0; i < this.args.length; i++)
{
var pair = this.args[i].split('=');
var name = unescape(pair[0]);
var value = (pair.length == 2)
? unescape(pair[1])
: name;
this.params[name] = value;
}
this.joined = function()
{
var join = new Array();
for (var a in this.params)
{
join.push(a + '=' + this.params[a]);
};
return join.join('&');
};
}
function Querystring_get(key, defaultValue)
{
var value = this.params[key];
return (value != null) ? value : defaultValue;
};
try these functions and get value like
var qs = new Querystring().get("sortby", '');
now qs will have your query string value and you can set value of the drop down like
$("select [name='sortbyselectop']").val(qs);
hope this will work.