Remove prefix from value - javascript

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

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

How to remove multiple select options based on dynamic value

I have 2 select boxes, with the second showing a subset of all options based on the category in the first box. The second box contains ids and names, where the option value equals the id. I already filtered out the id's I am interested in and have them in an array. This will change each time and can be different sizes (filtering all users by groups). What I would like to do is take a clone of the complete options and then only show those whos id (or value) is present. So, compare the array of filtered values to the complete set. I did see a couple ways to remove options, but most were for only one value at a time or for fixed values, so it didn't exactly fit what I need and I can't figure out how to do this last step! Looks like the following:
<select id = 'doctor_select' >
<option value = '1' > John Doe </option>
<option value = '2' > Jane Doe </option>
.... etc
edit: solved for now by hiding all and doing a for each loop to enable the ones I need.
I wouldn't do it like this, but you could clone the original combo and simply remove the unnecessary options from the DOM. Something like:
var newDoctorSelect=$("#doctor_select").clone();
$(newDoctorSelect).children("option").each(function() {
if(some condition) $(this).remove();
});
$("#somewhere").append(newDoctorSelect);
But I'd recommend either using AJAX or storing the options in an object and populating the select when needed.
var optionsByCategory={
"1":{"1":"One","3":"Three"},
"2":{"2":"Two"}
};
$("#categorySelect").on("change",function() {
var options=optionsByCategory[$(this).val()];
//OR some AJAX call to retreive the options from the server instead
$("#doctor_select option").remove();
for(var k in options) $("#doctor_select").append($("<option>").val(k).text(options[k]));
});
You could do this:
var options = getElementsByTagName("option"),
elem,
length = options.length;
for (var i = 0; i<length; i++) {
if (!((elem = options[i]).value === IDYouWantToMatch)); elem.parentNode.removeChild(elem);
}
I think you want something like the following using filter()
var $sel = $('#doctor_select'),
$opts = $sel.children();
var $filteredOpts = $opts.clone().filter(function(){
return someArray.indexOf(this.value)>-1;
})
$sel.empty().append($filteredOpts);
The stored $opts can now be re-used for future changes

Using phantomsjs, how to get a value and assign it to an element of an array?

The following piece of code when ran produces "undefined".
var getList = document.getElementById('lbExercises').option;
console.log(getList);
The HTML I wish to get the data from is as follows:
<select id="lbExercises" class="listBox" style="height:400px;width:350px;"
name="lbExercises" size="4">
<option value="1270">Value I want to Extract 2</option>
The issue is with my JS code - if it helps I'm running my code by using
phantomsjs filename.js
You could get the first value of the first option like this:
var getList = document.getElementById('lbExercises');
console.log(getList.options[0].value);
See jsFiddle:
http://jsfiddle.net/3LLBS/
This is how you would assign it to an element of an array:
var anArray = new Array();
anArray[0] = 123;
anArray[1] = 456;
anArray[2] = 789;
// assign the new value
anArray[1] = getList.options[0].value;
console.log(anArray[1]);
See jsFiddle:
http://jsfiddle.net/3LLBS/1/

How to make two select forms of different ids and names return their ids using $(this)?

I have an html form with two select dropdown lists. Each one has the same sites that you leave from/go to. I'm trying to grab the ID of each one and store them as separate variables, but each time I select a new option, the variables reset to undefined. My code looks like this:
$('select[name=Depart], select[name=Return]').change(function(){
var id = $(this).attr('id');
var depart_id;
var return_id;
// Grabs the place you left from
var dep = $('select[name=Depart] option:selected').val();
// Grabs the place you traveled to
var ret = $('select[name=Return] option:selected').val();
// Grabs the day in the log as a string
var day_id_raw = $(this).closest('tr').attr('id');
// Creates a jQuery object from the string above
var day_id = $('#' + day_id_raw);
// Creates a substring of the string above cutting it off at the day number in the log. E.g. "Day 1" in the log becomes the number "1".
var day_num = day_id_raw.substring(3, day_id_raw.length);
//Creates a jQuery object for the miles of the day table column
var miles_today = $('#miles_day' + day_num);
if($(this).is($('select[name=Depart]'))){
depart_id = id;
}
if($(this).is($('select[name=Return]'))){
return_id = id;
}
// Checks if the place you left from contains a column to output how many miles you traveled that day.
if(day_id.has(miles_today)){
miles_today.text(depart_id + "\n" + return_id);
}
)};
The last if statement is just for debugging purposes. miles_today is a blank div that I'm writing content to in order to test if the variables are actually working. Like I said earlier, each time I change an option on either select input, the alternate variable is cleared. Thanks in advance.
EDIT: Sorry for the late reply and ambiguous wording. Here is a working example of what I have: http://jsfiddle.net/8xVuX/2/
Just enter 1 or 2 in the 'Number of days' field and it should add a new row. If you click the select menu for 'Departed From' and choose an option, it'll output its id in the field to the left, but undefined for the other field 'Returned To's id. I want to have both ids displayed when the select options are changed.
Get them outside the change function, and use them wherever you'd like :
var depart_id = $('select[name=Depart]').prop('id'),
return_id = $('select[name=Return]').prop('id');
$('select[name=Depart], select[name=Return]').on('change', function(){
miles_today.text(depart_id + "\n" + return_id);
});
but are you sure you should'nt be getting the value ?

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