Extract value from dropdown in jquery need only numeric value - javascript

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

Related

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/

Getting value of selected checkbox with jquery from checkboxes without id's

I have a number of checkboxes that are generated from a JavaScript API call from a database. I need to be able to pass the values of the checkboxes which are then selected by the user, and sent to the processing page. The issue is that the checkboxes don't have ID's associated with them(or this wouldn't be a problem) They all have the same name, but no ID's.
What is the best way to find which check boxes are selected, and pass their values to the following page?
One way I started was with an array:
var options = ["option1","option2","option3"];
var option 1 = [0];
var option 2 = [1];
var option 3 = [2];
On the processing page, using:
var option1 = getFromRequest('option1') || '';
var option2 = getFromRequest('option2') || '';
var option3 = getFromRequest('option3') || '';
Is there a better way of doing this?
I've changed the implementation to the following:
var values = []
$("input:checkbox.subIndustry").each(function(){
values.push(this.value);
});
passing the values to the success page with
window.location.href = REGISTER_SUCCESS +'&values='values.join(",")
which should then get the value with
var variablname = getFromRequest('values') || "";
This is returning Undefined. Any help?
An easy way to select them would be something like $("input[type=checkbox]:checked")
However, if you wanted to keep up with them as they are checked, even if they are added after you load, you could create a variable, then asign a delegation to the "change" state of each input that is a checkbox and update this variable on each change.
It's as simple as:
var checked, checkedValues = new Array();
$(function() {
$(document).on("change", "input[type=checkbox]", function(e) {
checked = $("input[type=checkbox]:checked");
// if you wanted to get an array of values of the checked elements
checkedValues = checked.map(function(i) { return $(this).val() }).get();
// make a string of the values as simple as joining an array!
var str = checkedValues.join(); // would return something like: value1,value2,ext...
});
})
Working Example
Since all your checkboxes have the same name, you can retrieve the checked ones using a variation of:
var checked = $('input[name=ckboxname]:checked');
see: :checked selector for more information
you can simply get the values of checked checkboxes by using
$('input[name=checkboxname]:checked').val();
this will give you the value of checkbox which is checked and for all values simply use
each function of jquery.
Turns out, the answer was to utilize indexOf in the underscore.js library. The solution had to be applied in the API being used to send data.
(_.indexOf(values, '9') != -1 ? 1 : '0'),

Populate dropdown select with array-with multiple options

So I'm trying to populate a dropdown with the states, the value for the option should be the two characters value, and the text for the option should be the full state's name, using the code below is returning a value of 0,1,2,3... and returning all the options in the var as the text.
var states = ["Select State","","Alabama","AL","Alaska","AK","Arizona","AZ","Arkansas","AR",...];
$.each(states, function(val, text) {
$('#selector').append( $('<option> </option>').val(val).html(text) )
});
Try this, using an object for states instead of an array. Same results, but it's more clear what's what and you're less likely to have problems if you accidentally skip a name or abbreviation:
var states = {
"Select State":"",
"Alabama":"AL",
"Alaska":"AK",
"Arizona":"AZ",
"Arkansas":"AR"
};
var val, text;
for (text in states) {
val = states[text];
$('<option/>').val(val).text(text).appendTo($('#selector'));
};
http://jsfiddle.net/g59U4/
The problem is that the callback function provided to .each results in val containing the index of the current iteration (e.g. 0, 1, 2 etc.) and text containing the value of that index of the array.
To achieve what you are trying to, you would probably be better off with a normal for loop:
for(var i = 0; i < states.length; i+=2) {
$("#selector").append($('<option> </option>').val(states[i+1]).html(states[i]));
}
You would be even better off caching the jQuery object containing #selector outside of your loop, so it doesn't have to look it up every iteration.
Here's a working example of the above.
Another option would be to use an object instead of an array, using the state name or abbreviation as the keys, and the other as the values. Edit: just like #mblase75 has done
Well you have the jQuery.each function arguments confused. The first is the index of the value in the array, and the second in the value itself. What you need to do is something like:
$.each(states, function(index) {
if(index%2 > 0) {
//continue, basically skip every other one. Although there is probably a better way to do this
return true;
}
$('#selector').append( $('<option> </option>').val(states[index+1]).html(states[index]) )
});
That would be really straightforward if your array had two dimensions. Considering you really need to use the one-dimensional array you presented, you could do this:
var states = ["Select State","","Alabama","AL","Alaska","AK","Arizona","AZ","Arkansas","AR"];
for(var i=1; i<states.length; i+=2) {
$('#selector').append( $('<option value="' + states[i] + '">' + states[i-1] + '</option>').val(val).html(text) )
}
If you changed your array to be an array of objects, you could do something like this -
var states = [{"text":"Select State","val":""},{"text":"Alabama","val":"AL"}]; //etc
$.each(states, function(val, statedata) {
$('#selector').append( $('<option> </option>').val(statedata.val).html(statedata.text) )
});
This change passes a JavaScript object in to the callback each time. The object has text and val properties and is passed in to the callback as the statedata parameter. The val parameter holds the current index position of the array so it is not required to populate the select box.
Demo - http://jsfiddle.net/sR35r/
I have a similar situation populating a select list with a two-dimensional array as the result of an $.ajax callback ....
JSON ...
[["AL","Alabama"],["AK","Alaska"],["AS","American Samoa"],["AZ","Arizona"] ...
var stateOptions = $('#state');
var html ='';
for (var i =1; i<data.length; i++){
html+= '<option value="' +data[i][0]+ '">' +data[i][1]+ '</option>';
}
stateOptions.append(html);
<form name="form" id="form">
<select name="state" id="state">
<option value=''>State</option>
</select>
</form>

Generic way to fill out a form in javascript

I'm looking for a really generic way to "fill out" a form based on a parameter string using javascript.
for example, if i have this form:
<form id="someform">
<select name="option1">
<option value="1">1</option>
<option value="2">2</option>
</select>
<select name="option2">
<option value="1">1</option>
<option value="2">2</option>
</select>
</form>
I'd like to be able to take a param string like this: option1=2&option2=1
And then have the correct things selected based on the options in the query string.
I have a sort of ugly solution where I go through children of the form and check if they match the various keys, then set the values, but I really don't like it.
I'd like a cleaner, generic way of doing it that would work for any form (assuming the param string had all the right keys).
I'm using the prototype javascript library, so I'd welcome suggestions that take advantage of it.
EDIT: this is what I've come up with so far (using prototype for Form.getElements(form))
function setFormOptions(formId, params) {
params = params.split('&');
params.each(function(pair) {
pair = pair.split('=');
var key = pair[0];
var val = pair[1];
Form.getElements(form).each(function(element) {
if(element.name == key) {
element.value = val;
}
});
});
}
I feel that it could still be faster/cleaner however.
If you're using Prototype, this is easy. First, you can use the toQueryParams method on the String object to get a Javascript object with name/value pairs for each parameter.
Second, you can use the Form.Elements.setValue method (doesn't seem to be documented) to translate each query string value to an actual form input state (e.g. check a checkbox when the query string value is "on"). Using the name.value=value technique only works for text and select (one, not many) inputs. Using the Prototype method adds support for checkbox and select (multiple) inputs.
As for a simple function to populate what you have, this works well and it isn't complicated.
function populateForm(queryString) {
var params = queryString.toQueryParams();
Object.keys(params).each(function(key) {
Form.Element.setValue($("someform")[key], params[key]);
});
}
This uses the Object.keys and the each methods to iterate over each query string parameter and set the matching form input (using the input name attribute) to the matching value in the query params object.
Edit: Note that you do not need to have id attributes on your form elements for this solution to work.
Try this:
Event.observe(window, 'load', function() {
var loc = window.location.search.substr(1).split('&');
loc.each(function(param) {
param = param.split('=');
key = param[0];
val = param[1];
$(key).value = val;
});
});
The above code assumes that you assign id values as well as names to each form element. It takes parameters in the form:
?key=value&key=value
or
?option1=1&option2=2
If you want to keep it at just names for the elements, then try instead of the above:
Event.observe(window, 'load', function() {
var loc = window.location.search.substr(1).split('&');
loc.each(function(param) {
param = param.split('=');
key = param[0].split('_');
type = key[0];
key = key[1];
val = param[1];
$$(type + '[name="' + key + '"]').each(function(ele) {
ele.value = val;
});
});
This code takes parameters in the form of:
?type_key=value&type_key=value
or
?select_option1=1&select_option2=2
You said you're already going through the elements and setting the values. However, maybe this is cleaner that what you have?
function setFormSelectValues(form, dataset) {
var sel = form.getElementsByTagName("select");
dataset.replace(/([^=&]+)=([^&]*)/g, function(match, name, value){
for (var i = 0; i < sel.length; ++i) {
if (sel[i].name == name) {
sel[i].value = value;
}
}
});
}
You could then adapt that to more than just select elements if needed.
Three lines of code in prototype.js:
$H(query.toQueryParams()).each(function(pair) {
$("form")[pair.key].setValue(pair.value);
});
You can get form data in JavaScript object using formManager .

Categories

Resources