Javascript dropdownlist - javascript

How can I get the previous selected index on change event of dropdown list using Javascript.

No, it is not possible, but you can use a variable inside onchange event that tracks the previous selection
Example:
var previousSelected;
function track(d){
if(typeof previousSelected != 'undefined'){
alert("Previous selected value " + previousSelected );
}
previousSelected = d.selectedIndex;
alert("selected value " + d.selectedIndex);
}

Place a meta variable in the ul or ol object that is the index of the last selected item so that when you goto the item again you can just ask for that property again and, presto, you know the index of the last selected item.
A common way of placing a meta variable inside an object is by adding a class to the last item that was selected with javascript and then finding the list item with that class when you want to see which one was selected. I see JQuery users doing this alot (btw you should be using JQuery to help with all of your javascript).
For example, to mark the last item as selected:
$('ul li:last').addClass('selected');
Then to find it again:
$('ul li.selected')
Its actually a pretty easy way of tracking this kind of code.

You could have a javascript global variable which will track this value. So when the change event is trigerred you would have the new value and the old one. Then you would update the global variable with the new value.
Here's an example pseudo code:
var selectedValue = '';
document.getElementById('someId').onchange = function() {
var newValue = this.value;
// TODO: compare with the old value
selectedValue = newValue;
};

Related

Search key in json object based on value

I populate the options of a select input field based on json data I get from a php-script.
This works fine, but I want to show some extra info, based on the selected option.
Basically, I'm looking for a way to find the key that goes with the selected option:
$("#code").html(result[whichkey]["uniquecode"]);
This fiddle hopefully makes my question a bit more clearer.
Any help is much appreciated!
Given that the option element is created with the uniquecode of the object as its value, why do you even need to access the object again? You can just retrieve the value property of the selected option...?
Assuming this is just because you've oversimplified your example, and the objects within the array do hold other useful data which is not held in the option element itself, then you can use $.grep to filter the array of objects by the selected uniquecode, like this:
var json = '[{"uniquecode":"b32dez2","name":"John Doe","foo":"bar"},{"uniquecode":"a2df32","name":"Adam Smith","foo":"buzz"}]';
var result = JSON.parse(json);
var $sel = $('#names').change(function() {
var value = this.value;
var obj = $.grep(result, function(e) {
return e.uniquecode == value;
});
$("#code").html(obj[0].uniquecode + ' / ' + obj[0].foo)
});;
result.forEach(function(obj) {
$('<option value="' + obj.uniquecode + '">' + obj.name + '</option>').appendTo($sel)
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="names"></select>
<div id="code"></div>
Note that I added the foo property to the object to show you how to access properties of the object outside of those placed directly on the option element.
Also note that I simplified the code that generates the option elements as well. If you're going to use jQuery once in your project, you may as well use it everywhere.

How in XPages CSJS should I select a ComboBox value?

I am using CSJS in the 'onChange' Event in a ComboBox, and when a user selects a value, I want an EditBox and a second ComboBox to be set (The second ComboBox value is one that is already in the list, I just want to select it).
To set the EditBox in my 'onChange' Event I used:
XSP.getElementById("#{id:fldEditBox}").value = newEditBoxValue;
But selecting a value in the ComboBox was much harder. At first I used the EditBox method:
XSP.getElementById("#{id:fldComboBox2}").value = selectedComboBoxValue;
The on screen value changed, and the ComboBox functioned normally, when the document was saved it still had the old value.
I tried all sorts of things like selectedIndex but nothing worked. Eventually I found that this:
document.getElementsByName("#{id:fldComboBox2}")[0].value = selectedComboBoxValue;
meant the change was saved, but was not visible on screen, so in my final production code I used both and it works:
XSP.getElementById("#{id:fldComboBox2}").value = selectedComboBoxValue;
document.getElementsByName("#{id:fldComboBox2}")[0].value = selectedComboBoxValue;
This seems ugly to me, there must be a better way of doing this in CSJS, does anybody know?
The way you set the value of a select element (combobox) in vanilla JavaScript is to loop through the elements options property to find the option you want to select:
var comboBox = document.getElementById("#{id:comboBox}");
for (var i=0; i < comboBox.options.length; i++) {
if (comboBox.options[i].value == "ValueYouWantSelected") {
comboBox.options.selectedIndex = i;
break;
}
}
If you have JQuery available you can do it more elegantly:
var xpageID = "#{id:comboBox}".replace(/:/gi, "\\:");
var valueYouWantSelected = "someValue";
$('#' + xpageID + ' option[value="' + valueYouWantSelected + '"]').prop('selected', true);
The xpageID variable is there because you have to escape the ':' characters that XPages puts in the generated IDs for it to work with the JQuery selector engine.

Remove option from selected list based of index?

I have two select lists and based off the selected index of either one I need to remove the option at that index from both lists.
I have seen example of doing this for the currently selected option using the remove() function but that would only work for one list as the other list might have a different option selected or none at all.
Knowing just the index value is it possible to do this with JavaScript / jQuery? I already have the code that figures out which list to pull the index from and get that index value. I just have not found a way to specify an index value for the removal.
Code developed based off comment:
function RemoveCode(codeType)
{
var selectedProjectsField = $("#SelectedProjects");
var selectedProjectCodesField = $("#SelectedProjectCodes");
var selectedTasksField = $("#SelectedTasks");
var selectedTaskCodesField = $("#SelectedTaskCodes");
var selectedOptionIndex;
if (codeType == "Project")
{
selectedOptionIndex = $("#SelectedProjects :selected").index();
}
else
{
selectedOptionIndex = $("#SelectedTasks :selected").index();
}
alert(selectedOptionIndex);
selectedProjectsField.eq(selectedOptionIndex).remove();
selectedTasksField.eq(selectedOptionIndex).remove();
}
Using The :eq() Selector
You could use the :eq() selector to target a specific element by it's index and then call remove() to remove it from the DOM :
// Syntax Example: This will remove then (index)th option element
$('select option:eq(index)').remove();
So in your case, you would simply want to concatenate your selectedOptionIndex into the selector to target selector using one of the following :
// Remove a specific option of your SelectedProjects element
$('#SelectedProjects option:eq(' + selectedOptionIndex + ')').remove();
Example
You can see an interactive example here and demonstrated below :
This code should work:
$('#SelectedProjects option')[index].remove();
$('#SelectedTasks option')[index].remove();
or
selectedProjectsField.find('option')[selectedOptionIndex].remove();
selectedTasksField.find('option')[selectedOptionIndex].remove();

Can't access JavaScript variable inside function

I'm making an extension for selected text search in different search engines. One of the menu items changes if the selected string is a particular one. I have this done so far and it does what I want, except I can not make the "title" of the menu change. How do I give value to the variable "myTitle" in if statement inside the function?
Thanks in advance.
var myTitle; // if I give value here it does work, but I need the value based on the if statement bellow.
function myFunction(selectedText) {
if(selectedText.match (/someString|SomeOtherString/)) {
var myURL1 = 'https://someURL' + selectedText;
chrome.tabs.create({url: myURL1});
myTitle = "title1"; //I can not make the variable to get this value here
}else{
var myURL2 = 'https://someOtherURL' + selectedText;
chrome.tabs.create({url: topicCall});
myTitle = "title2"; //I can not make the variable to get this value here
}
}
chrome.contextMenus.create({
**"title": myTitle,** // this should change based on the selection
contexts:["selection"],
onclick: function (info)myFunction(info.selectionText);}
});
You have "cause and effect" mixed up. When chrome.contextMenus.create is called, myFunction has not executed yet and the value of myTitle has not been assigned.
Perhaps, you can use chrome.contextMenus.update, after the page is loaded. You could create the menu, with default titles, but with unique IDs. Then use the above method, based on whatever the "selectedText" is, and use the IDs to replace the titles.

Local storage not working issues with for loop

I am using local storage to allow the user to return to a form after it has been submitted and amend with previous values persisting.
I succeeded in using the jQuery Storage Api (for set() and get()) but only by writing out long hand for each form element, not ideal. Instead I wanted to push all the form element ids to an array and loop through the array. First part, pushing to the array, works like a charm but the for loop I used is not working.
I intend to use jQuery .each() function but want to understand why my loop is not working first. Thanks.
(function() {
var selectArray = [];
// Getting select ids
$("select").each(function() {
selectArray.push($(this).attr("id"));
});
// Using Local Storage Api
var storage = $.localStorage;
for (var i = 0; i < selectArray.length; i++){
// Get select element
$("#" + selectArray[i]).val(storage.get(selectArray[i]));
// Set select element
$("#" + selectArray[i]).change(function() {
var selectValue = $("#" + selectArray[i]).val();
storage.set(selectArray[i], selectValue);
});
// Check loop is working
console.log(i + ". " + selectArray[i]);
}
}());
Resources:
jQuery v1.11.0
jQuery Storage API
Just change the change event handler like this, avoid reference to i. variable i is getting dangled here.
$("#" + selectArray[i]).change(function() {
var selectValue = $(this).val();
storage.set($(this).attr('id'), selectValue);
});
This should work.
Example
You are right, inside the change handler function you refer to the loop variable 'i'. When the change handler is actually called, 'i' is dereferenced and always contains the last value: selectArray.length

Categories