Jquery - Use HTML :selected to fetch an array with the same name - javascript

I have this select input in my HTML
<select class="" id="countries" name="Country">
<option value="AL">
Albania
</option>
<option value="HR">
Croatia
</option>
<option value="BG">
Bulgaria
</option>
<option value="MK">
Macedonia
</option>
<option value="MT">
Malta
</option>
<option value="MD">
Moldova
</option>
<option value="RO">
Romania
</option>
<option value="RS">
Serbia
</option>
<option value="SI">
Slovenia
</option>
</select>
In Jquery I have arrays with same name as this select values. The arrays are filled with data which is irrelevant.
var Albania = [];
var Croatia = [];
var Bulgaria= [];
...
Depending on which country is selected, another select input should be filled with array with the same country name. This other select is #cepsp
$( "#countries").change(function() {
$('#cepsp').empty();
var option = '';
for (var tt=0;tt<Albania.length;tt++)
{option += '<option value="'+Albania[tt]+'">'+Albania[tt]+'</option>';}
$('#cepsp').append(option);
});
Notice how I used Albania array in Jquery and this is working fine. But I want this for other countries as well.
I tried:
$( "#cepsp option:selected" ).text()[tt]
But of course that would never work.
How do I transfer text of selected input to variable name?

If you change the structure of your arrays into an object thus:
var countriesArra ={
Albania:[],
Croatia:[],
Bulgaria:[],
....
}
You can now select the correct array based on it's name:
$( "#countries").change(function() {
// get name that macthes array name, i.e. the text not the value
var countryName = $(this).text();
//countryName should be "Albania" not "AL"
$('#cepsp').empty();
var option = $('<option>');
for (var tt=0;tt<countriesArra[countryName].length;tt++)
{
//variable prevents querying the array twice, so this should be more efficent
var countryNameFromArra = countriesArra[countryName][tt];
option.val(countryNameFromArra).html(countryNameFromArra);
}
$('#cepsp').append(option);
});
this works because you can access an object's properties by the string of the property name.
So countriesArra['Albania'] returns the "albania" array. You then iterate your tt variable as normal on this array, e.g. countriesArra['Albania'][0] returns the first item in the albania array of the object.
Brief fiddle
I've also tided up your option creation. So I create an "option" object using jquery var option = $('<option>');. I can then access it's methods and properties as a jquery object, rather than string concatenating it.
option.val(countriesArra[countryName][tt]).html(countriesArra[countryName][tt]);

Without modifying your array structure, you can try the eval instruction will can do some "variable name as a variable" behaviour for your purpose. To be more precise the eval function evaluate expression and/or instruction wich may contain variable, for example you can define two variable var a = 1 var b = 2 and run eval("a+b") wich will result 3.
JS
var Albania = ["ALBANIA", "ALBANIA2"];
var Croatia = ["CROATIA", "CROATIE2"];
var Bulgaria= ["BULGARIA", "BULGARIA2"];
$( "#countries").change(function()
{
$('#cepsp').empty();
var option = '';
var name = $("#countries option:selected").text();
for (var tt=0;tt<eval(name).length;tt++)
{
option += '<option value="'+eval(name)[tt]+'">'+eval(name)[tt]+'</option>';
}
$('#cepsp').append(option);
});

You can use eval to craft variable from string
var Albania = ["a","b","c"];
var Croatia = ["d","e","f"];
var Bulgaria= ["g","h","j"];
$( "#countries").change(function() {
var countryName = $(this).find(":selected").text();
$('#cepsp').empty();
var country = eval(countryName);
var option = '';
for (var tt=0; tt < country.length; tt++)
{option += '<option value="'+country[tt]+'">'+country[tt]+'</option>';}
$('#cepsp').append(option);
});
http://jsfiddle.net/rerich/1ze1og8L/

Related

Slicing nodes within array

When I first select two options from the 2nd select menu, the array becomes is populated with those two selections. What I want is for the second selected option to replace the first, so even if I do begin by selecting two options from the 2nd select menu, the array's length will remain at one, dynamically changing between those selections. I hope you understand. Thanks for any help. I know I could just make it one function and this problem wouldn't exist but for my use of it I can't do that.
var select1 = document.getElementById('select1');
var select2 = document.getElementById('select2');
var array = []
function myFunct1() {
var one = select1.options[select1.selectedIndex].value;
array.splice(0, 1, one);
console.log(array);
}
function myFunct2() {
var two = select2.options[select2.selectedIndex].value;
array.splice(1, 1, two);
console.log(array);
}
<select id = 'select1' onchange = 'myFunct1()'>
<option disabled selected value> -- select an option -- </option>
<option value = 'Dog'>ONE</option>
<option value = 'Cat'>TWO</option>
<option value = 'Bear'>THREE</option>
</select>
<select id = 'select2' onchange = 'myFunct2()'>
<option disabled selected value> -- select an option -- </option>
<option value = 'Dog'>ONE</option>
<option value = 'Cat'>TWO</option>
<option value = 'Bear'>THREE</option>
</select>
use Array.prototype.unshift() to add value at first place. You can check if element exists in array
using includes().And instead of creating two functions you can create same function and pass different parameters to it.
var array = [];
function myFunct(val){
if(!array.includes(val)) array.unshift(val);
console.log(array);
}
<button onclick = 'myFunct("One")'>ONE</button>
<button onclick = 'myFunct("Two")'>TWO</button>
If you want to replace the new value with first value use this code
function myFunct(val) {
array.unshift(val);
array = [... new Set(array)];
console.log(array);
}
Update:
var select1 = document.getElementById('select1');
var select2 = document.getElementById('select2');
var array = [];
let sel1 = false;
function myFunct1() {
var one = select1.options[select1.selectedIndex].value;
if(array.length === 1 && !sel1) array.unshift(one);
else array.splice(0,1,one);
console.log(array);
sel1 = true;
}
function myFunct2() {
var two = select2.options[select2.selectedIndex].value;
array.splice(sel1, 1, two);
console.log(array);
}
Try This:
var array = [];
function myFunct() {
if(array.indexOf('One') === -1 ) { array.unshift('One') ; }
console.log(array);
}
function myFunct2() {
if(array.indexOf('Two') === -1 ) { array.push('Two') ; }
console.log(array);
}
<button onclick = 'myFunct()'>ONE</button>
<button onclick = 'myFunct2()'>TWO</button>

Extract value from dropdown in jquery need only numeric value

Hello everyone I am getting the value from dropdownlist using jquery
here is my jquery code
var priceValue = $("#ddlprice option:selected").text();
and i am getting value
Valvet ($100)
but i want only 100 from this value so how can I extract the exact value from it.
Thanks
Use regular expression to get the number
/\d+/g this will search for number in a given string
var priceValue = "Valvet ($100)";
console.log(/\d+/g.exec(priceValue)[0]);
if the value is 100 like this
<select id="ddlprice">
<option value="100">Valvet ($100)</option>
</select>
then you get the value using val() like this $("#ddlprice").val(); to get the value
if your option is written like this <option>Valvet ($100)</option> or like this <option value="Valvet ($100)">Valvet ($100)</option>
then you can use the function below from SO which will print only the numbers in a string.
function getNumbers(inputString){
var regex=/\d+\.\d+|\.\d+|\d+/g,
results = [],
n;
while(n = regex.exec(inputString)) {
results.push(parseFloat(n[0]));
}
return results;
}
var priceValue = $("#ddlprice option:selected").text();
console.log(getNumbers(priceValue));

Remove prefix from value

I have a lot of similar values inside a select:
<select id="selectbairro" name="selectbairro">
<option value="AC_Itapetininga_Text1"></option>
<option value="AC_Itapetininga_Text2"></option>
<option value="AC_Itapetininga_Text3"></option>
</select>
I want to create a var that gets the current selected value WITHOUT the prefix (Text1, Text2, Text3) and insert it inside that:
$("#selectbairro").change(function() {
var id = $(this).val();
// here //
});
Like I showed below var id = $(this).val();, I have a var that gets the current selected option value WITH THE PREFIX, so I need something starting from this.
Thanks.
var id = $(this).val().split("_").pop()
this splits your string into an array by underscore and then pops off the last one as someone just mentioned add join to turn the array (with the last thing popped off) into a string
var id = $(this).val().split("_").pop().join("_");
I found the answer. Thanks.
var id = $(this).val().split('_',2).join('_');

Select tag with array as value, how to choose array item 1 vs item 2 using JavaScript?

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)

Using multidimensional array to set value and text of options using ng-option

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

Categories

Resources