Get the option value in select in javascript [duplicate] - javascript

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
How to get the selected value of dropdownlist using JavaScript?
How to get the value of a selected text in javascript
<select id="short_code">
<option value="12">First</option>
<option value="11">Second</option>
<option value="10">Third</option>
<option value="9">Fourth</option>
</select>
I need to do this:
if(document.getElementById("short_code").options.item(document.getElementById("short_code").selectedIndex).text)== "First")
//get the value of the option Fist , how to get the value?

var elem = document.getElementById("short_code"),
selectedNode = elem.options[elem.selectedIndex];
if ( selectedNode.value === "First" ) { //...

How about this:
var select = document.getElementById('short_code');
var options = select.options;
var selected = select.options[select.selectedIndex];
//which means that:
console.log(selected.value || selected.getAttribute('value'));//should log "12"
console.log(selected.innerHTML);//should log(First);
Loop through all the options (either creating a reference variable, like I did with options, or plain for (var i=0;i<select.options.length;i++)) and you can get all info you need

Related

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('_');

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

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/

Javascript function to return a variable [duplicate]

This question already has answers here:
Is there a way to access a javascript variable using a string that contains the name of the variable?
(4 answers)
Closed 8 years ago.
I am trying to use a drop down box to update some data. what I would like to do is use a function to return the variable ds,ds1 depending on what the user selects. For example. if they select ds from the dropdown box I want the function to return the actual var ds and not the ds value, since I want to reference the variable ds in another bit of code depending on the selection. Hope this makes sense.
Thanks for your help,
<div >
<select id="dropdown" onchange="updateData()">
<option value="ds">ds</option>
<option value="ds1">ds1</option>
</select>
</div>
var ds = [[{x:0,y:72}],[{x:0,y:28}]];
var ds1 = [[{x:0,y:2}],[{x:0,y:50}]];
function myVar() {
return (dropdown.value);} //I want this to be the variable ds i.e. var ds //[[{x:0,y:72}], [{x:0,y:28}]]; not the value.
var arr = {};
arr["ds"] = [[{x:0,y:72}],[{x:0,y:28}]];
arr["ds1"] = [[{x:0,y:2}],[{x:0,y:50}]];
function myVar() {
return (arr["dropdown.value"]);
}

Alert using the select object [duplicate]

This question already has answers here:
Get selected value in dropdown list using JavaScript
(33 answers)
Closed 9 years ago.
I have tried using the select object with JavaScript but it dosent seem to be going. do anyone know what am talking about
this is what I have tried
var x = document.getElementById("mySelect").selectedIndex;
var u = document.getElementsByTagName("option")[x].value;
        document.getElementById("demo").innerHTML=u;
var sel = document.getElementById("mySelect"); //reference the select
var index = sel.selectedIndex; //find the index that was picked
var option = sel.options[index]; //select the option that was picked
document.getElementById("demo").innerHTML = option.value; //read the value
if you want the text and not the value use .text
document.getElementById("demo").innerHTML = option.text; //read the value
What this sample code does not do is deal if nothing is selected. That would be a selectedIndex equal to -1.

Categories

Resources