Changing the selected text in dropdown? - javascript

I would like to change the selected value of a dropdown onclick of a button. There are a few dropdowns in a div with class = '.WHERE', I want to append a parenthesis to the first dropdown and to the second to last dropdown
The button calls this function:
//add parenthesis to the first child, and to the second to last child
function addParens(){
var len = $(".WHERE").children('div > select').length;
len -= 1;
var firstDropdown = $('.WHERE').children().first(); //the first child
var lastDropdown = $('.WHERE').children().eq(len); //the second to last child
//attempting here to append left parenthesis to the first dropdown
var text = firstDropdown.val(); //the old selected option
text = '(' + text; //new text with left parenthesis
console.log(text); //prints out correctly
firstDropdown.text(text); //tried ,doesn't work
var firstId = firstDropdown.attr('id'); //grab id firstDropdown
$('#'+firstId).val(text); //doesn't work by grabbing id first
firstDropdown.val(text); //also tried this, doesn't work
}
Afterwards if I print firstDropwdown.val() it prints null, and the dropdown has nothing selected.
here is a sample of what one of the dropdown looks like, it is created dynamically

function addParens() {
var len = $(".WHERE").children('div > select').length;
len -= 1;
var children = $('.WHERE').children();
var firstDropdown = children.first().find("option:selected"); //the first child
var lastDropdown = children.eq(len).find("option:selected"); //the second to last child
firstDropdown.text('(' + firstDropdown.text() + ')');
lastDropdown.text('(' + lastDropdown.text() + ')');
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="WHERE">
<select>
<option></option>
<option>Article.Author</option>
<option>Article.Editor</option>
<option>Article.Publisher</option>
<option>Article.Title</option>
<option>Article.BookTitle</option>
<option>Article.Year</option>
</select>
<select>
<option></option>
<option>Article.Author</option>
<option>Article.Editor</option>
<option>Article.Publisher</option>
<option>Article.Title</option>
<option>Article.BookTitle</option>
<option>Article.Year</option>
</select>
<select>
<option></option>
<option>Article.Author</option>
<option>Article.Editor</option>
<option>Article.Publisher</option>
<option>Article.Title</option>
<option>Article.BookTitle</option>
<option>Article.Year</option>
</select>
<select>
<option></option>
<option>Article.Author</option>
<option>Article.Editor</option>
<option>Article.Publisher</option>
<option>Article.Title</option>
<option>Article.BookTitle</option>
<option>Article.Year</option>
</select>
</div>
<button onClick="addParens();">
DO IT
</button>

Related

Multiple select tags to filter list in pure JavaScript

I am using an onchange function for my select tag to filter a list of items based on the select option value.
The code I have currently have only works for a single select tag but I want it to be able to work for multiple select tags, which would require each select option value to cooperate.
For example, if I have "Departments" and "Locations" as tags for each item in the list and I choose Department -> IT and Location -> New York in the select tags, I only want to see a list of IT departments in New York.
I am having a hard time understanding how I would do this properly. I would assume some sort of for loop to get each select tag and then get the value of the current option in each select tag and only show the list items if they meet the select option value criteria.
I would appreciate any help of how I could achieve this!
HTML:
<select class="filterTags" id="filterDepartment">
<option>All</option>
<option>IT</option>
<option>Marketing</option>
</select>
<select class="filterTags" id="filterLocation">
<option>All</option>
<option>New York</option>
<option>Washington</option>
</select>
<div class="tags-container">
<div class="tags tags-departments">
<span class="department tag">IT</span>
<span class="department tag">Marketing</span>
</div>
<div class="tags tags-locations">
<span class="location tag">New York</span>
<span class="location tag">Washington</span>
</div>
</div>
JavaScript:
var selectClass = document.getElementsByClassName("filterTags")
selectClass = selectClass[0]
selectClass.onchange= function() {
var filterOptions, tags, i, span;
filterOptions = this.options[this.selectedIndex].value
tags = document.getElementsByClassName("tags-departments")
span = document.querySelectorAll(".department")
for (i = 0; i < tags.length; i++) {
if (span) {
if (span[i].innerHTML.indexOf(filterOptions) > -1) {
span[i].parentNode.parentNode.parentNode.style.display = ""
} else {
span[i].parentNode.parentNode.parentNode.style.display = "none"
}
if(filterOptions == "All") {
span[i].parentNode.parentNode.parentNode.style.display = ""
}
}
}
}
Well, I would suggest the following logic, add a function to the onchange event of both selection elements, the function would:
Detect the ID of the selection element that triggered the event.
Based on the selection element that triggered the change, loop over the corresponding span elements.
For each span, based on the selected value in the selection, check if it should be displayed or not.
Here is a fully working code and a working example with it:
//Iterate the selection elements and add the function to the 'change' event
sels = document.getElementsByTagName('select');
for(i=0; i<sels.length; i++)
{
sels[i].addEventListener('change', function() {
//get the selection id of the selected that was change - this returns the selection element
selectionID = this.id;
if(selectionID === "filterDepartment")
{
//the value of the selected department
var selectedDepartment = document.getElementById("filterDepartment").value
//we will iterate the departments spans and check their text value agains the selected department value (or if the value is 'All' we dont need to check//
var spans = document.getElementsByClassName('tags tags-departments')[0].getElementsByTagName('span');
for(var i = 0; i < spans.length; i++)
{
if(selectedDepartment == "All" || spans[i].innerText == selectedDepartment)
{
spans[i].style.display = "block";
}
else
{
spans[i].style.display = "none";
}
}
}
if(selectionID === "filterLocation")
{
var selectedLocation = document.getElementById("filterLocation").value;
var spans = document.getElementsByClassName('tags tags-locations')[0].getElementsByTagName('span');
for(var i = 0; i < spans.length; i++)
{
if(selectedLocation == "All" || spans[i].innerText == selectedLocation)
{
spans[i].style.display = "block";
}
else
{
spans[i].style.display = "none";
}
}
}
}, false);}

How Can I keep the dropdown last selected on refresh page

I have this HTML
<select id="drpRequestCategories" class="form-control" Width="100%">
<option value="-1">All</option>
</select>
and here is the function I fill the Select from it
function filldropdownlistcategory(res) {
var test = $.parseJSON(res.d);
$("#drpRequestCategories").empty();
$(test).each(function () {
var option = $('<option />');
option.attr('value', this.ServiceID).text(this.ServiceName);
$('#drpRequestCategories').append(option);
});
}
when I click on Search button on my page
1-it clear this dropdownlist but I need to keep the last selected value.
2- I call this function on every treeview node change so when I remove this
$("#drpRequestCategories").empty();
it doesn't remove the old dropdown values but append the new values to the old .
Ok first using localstorage set a key holding the last selected item ,while every node change first empty the select box and use the localstorage item to fill the box again
//Add the onchange listener for the select box
$("#drpRequestCategories").on('change',function(evt){
var optionSelected=evt.target.value;
localStorage.setItem("recent",optionSelected);
}
//Now your function
function filldropdownlistcategory(res){
//empty the box
$("#drpRequestCategories").empty();
$(test).each(function () {
var option = $('<option />');
option.attr('value', this.ServiceID).text(this.ServiceName);
$('#drpRequestCategories').append(option);
});
//Once U have appended the options attach the previous list to the select box
var prevOptions=JSON.parse(localStorage.getItem("options"));
for(var key in options){
var option=$('<option />')
option.attr("value",options[key]).text(options[key])
$("#drpRequestCategories").append(option)
}
//Now Select the Last selected option
var lastSelected=localStorage.getItem("recent");
$("#drpRequestCategories").val(lastSelected);
//Once all the options are populated call the storeOptions Function
storeOptions();
}
//Function to store the options
function storeOptions(){
var options=$("#drpRequestCategories").children();
var obj={};
for(var i=0;i<options.length;i++){
var optionText=options[0].value || options[0].innerHTML //Depends on what you want
//update the obj
obj["option"+i]=optionText;
}
//Now Store them in localStorage
localStorage.setItem("options",JSON.stringify(obj))//stringify will convert the object into a string
}

How to select an item just by click on it in combobox in javascript?

My situation is i have a comb-Box which i fill with items that are integer values dynamically through javascript.
The problem is when i click on item to select it , It is still not selected , after clicking at that item, again i need to click outside the combo box to get it selected. I don't know why ?
My code to do so is (it's inside table) :
<body onload="loadView();">
<table>
<tr>
<td>
<select id="mydropdown" name="mydropdown" onblur="comboItemselect(this)"></select>
</td>
</tr>
</table>
</body>
And how i fill the item in combo is like this :
function loadView()
{
var sel = document.getElementById('mydropdown') // find the drop down
for (i = 1; i <= 50; i++) { // loop through all elements
var opt = document.createElement("option"); // Create the new element
opt.value = i; // set the value
opt.text = i; // set the text
sel.appendChild(opt); // add it to the select
}
}
/*When an item is selcted from CoboBox*/
function comboItemselect(item)
{
var selectedItem = item.options[item.selectedIndex];
alert("selected item is : " +selectedItem);
}
What i have done before in wpf or any other application was , i just clicked on the item to be selected in combobox and it was selected, but why i need to click once on the item and then again click outside the combobox to get it selected ?
How to select item just by clikinng once on that combo box item
Change event from onblur to onclick. it will work fine
function loadView() {
var sel = document.getElementById('mydropdown') // find the drop down
for (i = 1; i <= 50; i++) { // loop through all elements
var opt = document.createElement("option"); // Create the new element
opt.value = i; // set the value
opt.text = i; // set the text
sel.appendChild(opt); // add it to the select
}
}
/*When an item is selcted from CoboBox*/
function comboItemselect(item) {
var selectedItem = item.options[item.selectedIndex];
alert("selected item is : " + selectedItem.value);
}
<body onload="loadView();">
<table>
<tr>
<td>
<select id="mydropdown" name="mydropdown" onchange="comboItemselect(this)"></select>
</td>
</tr>
</table>
</body>
You were close. All you need to do is change
var selectedItem = item.options[item.selectedIndex];
to
var selectedItem = item.value;
for any elemt you can access the attributes like id and value just by using
<variable>.id
<variable>.value
and as for the clicking outside, it is because you have it onBlur which means after losing focus. So it will call the function after you click off the the select box. What you can do is add it to the .click function. JQuery would be even better for this operation as you can do an onClick event to initialize your select and an onChange event to get the selected item

Updating listbox selected index

I have a google script which reads and writes between a google spreadsheet and a google form. It's basically a form to access a materials database.
When first accessing the form, it shows all the fields blank, a populated 'selector' listbox of material id's (CW_ID) and an option for "New" part in the selector listbox. If user stays on "New", the fields stay blank for user to populate them manually and appends it as a new item in the database. If user scrolls through the 'selector' listbox and selects a CW_ID, it will pull from the spreadsheet and populate the fields with data corresponding to the selected CW_ID, for the user to then edit (modify a detail about a part).
Because I am using a SQL structure for my database, I have a couple linked tables:
materials table (which holds most information about the part, including an ID for manufacturer [manufacturer_ID])
manufacturers table (which is linked to the materials.manufacturer_ID)
Right now, the form only uses the materials sheet to populate the fields, so in the field for 'manufacturer', it only shows the ID number. For user purposes, I want the script to check the manufacturer_ID shown in the materials sheet, go into manufacturers sheet, find a match and have the manufacturers listbox show it as the currently selected index. (Or just have the name of the manufacturer show up in the field)
This is part of my script so far:
(Scroll to bottom for "//****THIS IS THE PART I'M WORKING ON")
function doGet() {
var ss = SpreadsheetApp.openByUrl("https://docs.google.com/something")
var materialsSheet = ss.getSheetByName('materials');
var manufacturersSheet = ss.getSheetByName('manufacturers');
var vendorsSheet = ss.getSheetByName('vendors');
var usersSheet = ss.getSheetByName('users');
var projectApp = UiApp.createApplication();
projectApp.setTitle("Materials Form");
var activeEmail = Session.getActiveUser().getEmail();
//I create the vertical panel.
var panel = projectApp.createVerticalPanel().setId('face');
//Here is where I actually create the drop down menu, and assign the function "goSelection" to be activated whenever a selection is made.
var selector = projectApp.createListBox(true);
selector.setName('selectionBox').setId('selectionBox').addItem('New');
var materialsData = materialsSheet.getDataRange().getValues();
//do until row is less than length of
for (var i=0; i < materialsData.length; i++){
if (materialsData [i][1] == "Email"){
//if row in Column B does not equal gmail, skip to i++
continue;
}
//add Column C (CW_ID) of current row to the selector list
selector.addItem(materialsData [i][2]);
}
selector.setSelectedIndex(0);
var selectHandler = projectApp.createServerHandler('goSelection');
selectHandler.addCallbackElement(panel);
selector.addChangeHandler(selectHandler);
//Here is where I create the drop down menu to show list of manufacturers from manufacturers sheet
var manufSelectorLabel = projectApp.createHTML("<br><b>Manufacturer</b><br>").setWidth('100%');
var manufSelector = projectApp.createListBox(true);
manufSelector.setName('manufSelectionBox').setId('manufSelectionBox').addItem('New');
var manufacturersData = manufacturersSheet.getDataRange().getValues();
//do until row is less than length of
for (var i=0; i < manufacturersData.length; i++){
if (manufacturersData [i][1] == "Email"){
//if row in Column B does not equal gmail, skip to i++
continue;
}
//add Column C (Manufacturers) of current row to the selector list
manufSelector.addItem(manufacturersData [i][3]);
}
manufSelector.setSelectedIndex(0);
var manufSelected = manufSelector.SelectedItem;'
//**I am unsure whether this should have it's own function
//var manufSelectHandler = projectApp.createServerChangeHandler('goManuf');
//manufSelectHandler.addCallbackElement(panel);
//manufSelector.addChangeHandler(manufSelectHandler);
var gmailLabel = projectApp.createHTML("<br><b>Gmail:</b><br>").setWidth('100%');
var gmailField = projectApp.createTextArea().setSize('100%', '25px');
gmailField.setName('gmailArea').setId('gmailArea');
gmailField.setText(activeEmail);
var savedLabel = projectApp.createLabel('Thank you for your submission.');
savedLabel.setVisible(false).setId('sLabel');
//At this point, I'm actually declaring the variables for all the fields and text for the actual form.
var selectorLabel = projectApp.createHTML("<br><b>Select CW_ID from list.</b>").setId('selectLabel');
var descriptionLabel = projectApp.createHTML("<br><b>Description</b><br>").setWidth('100%');
var descriptionField = projectApp.createTextArea().setSize('100%', '100px');
descriptionField.setName('descriptionArea').setId('descriptionArea');
var manufacturerLabel = projectApp.createHTML("<br><b>Manufacturer</b></br>").setWidth('100%');
var manufacturerField = projectApp.createTextArea().setSize('100%x', '25px');
manufacturerField.setName('manufacturerArea').setId('manufacturerArea');
var manufacturerListLabel = projectApp.createHTML("<br><b>ManufacturerList</b></br>").setWidth('100%');
var manufacturerListField = projectApp.createTextArea().setSize('100%x', '25px');
manufacturerListField.setName('manufacturerListArea').setId('manufacturerListArea');
var modelnumberLabel = projectApp.createHTML("<br><b>Model Number</b><br>").setWidth('100%');
var modelnumberField = projectApp.createTextArea().setSize('100%', '25px');
modelnumberField.setName('modelnumberArea').setId('modelnumberArea');
//Next, i create the save button and assign the function "saved" to be activated whenever the button is pressed.
var saveButton = projectApp.createButton('Save');
var saveHandler = projectApp.createServerHandler('saved');
saveHandler.addCallbackElement(panel);
saveButton.addClickHandler(saveHandler);
//Now that all the componentes of the form have been declared and set up, I'm going to assemble them on the panel.
panel.setSpacing(6);
panel.add(nameLabel);
panel.add(nameField);
panel.add(gmailLabel);
panel.add(gmailField);
panel.add(selectorLabel);
panel.add(selector);
panel.add(descriptionLabel);
panel.add(descriptionField);
panel.add(manufSelectorLabel);
panel.add(manufSelector);
panel.add(manufacturerLabel);
panel.add(manufacturerField);
panel.add(modelnumberLabel);
panel.add(modelnumberField);
panel.add(saveButton);
panel.add(savedLabel);
projectApp.add(panel);
return projectApp;
}
//This function looks to see what has been selected in the drop down menu, and then pulls the appropriate data from the spreadsheet to display in the fields.
function goSelection(e){
var activeEmail = Session.getActiveUser().getEmail();
var app = UiApp.getActiveApplication();
var gmailField = app.getElementById('gmailArea');
var nameField = app.getElementById('nameArea');
var chosen = e.parameter.selectionBox;
var ss = SpreadsheetApp.openByUrl("https://docs.google.com/something")
var materialsSheet = ss.getSheetByName('materials');
var manufacturersSheet = ss.getSheetByName('manufacturers');
var vendorsSheet = ss.getSheetByName('vendors');
var materialsData = materialsSheet.getDataRange().getValues();
var manufacturersData = manufacturersSheet.getDataRange().getValues();
var vendorsData = vendorsSheet.getDataRange().getValues();
var panel = app.getElementById('face');
var standardpartField = app.getElementById('standardpartArea');
var descriptionField = app.getElementById('descriptionArea');
var manufacturerField = app.getElementById('manufacturerArea');
var manufacturerListField = app.getElementById('manufSelectionBox');
var modelnumberField = app.getElementById('modelnumberArea');
if (chosen != 'New') {
for (var i=1; i < materialsData.length; i++){
if (materialsData [i][1] == "Email"){
//if row in Column B does not equal gmail, skip to i++
continue;
}
if (materialsData [i][2] != chosen){
continue;
}
nameField.setText(materialsData [i][0]);
gmailField.setText(materialsData [i][1]);
standardpartField.setText(materialsData [i][3]);
descriptionField.setText(materialsData [i][4]);
//****THIS IS THE PART I'M WORKING ON
//set manufacturerField to manufacturer of current row
//loop through manufacturer sheet until row matches with manufacturersField
//when a match is found, selector box index to same row
manufacturerField.setText(materialsData [i][5]);
for (var i=1; i < manufacturersData.length; i++){
if (manufacturersData [i][1] == "Email"){
//if row in Column B does not equal Email, skip to i++
continue;
}
if (manufacturersData [i][2] != manufacturerField){
continue;
}
manufacturerListField.setSelectedIndex(i);
}
modelnumberField.setText(materialsData [i][6]);
}
}
This makes sense to me, but it doesn't work. I click on a part in the selector listbox, and all the info populates into the fields, as I want it to. However, the manufacturer listbox does not jump to the proper manufacturer (as populated in the manufacturer field), it just sits there and stays as is.
(See image to get an idea of what the form looks like)
http://oi61.tinypic.com/6h6tqp.jpg
Manufacturer listbox and field show up, but right now, only the manufacturer field changes to show the data when a part is selected)
Any help would be GREATLY appreciated! :)
Here is some HTML that can get you started with the HTML Service:
Input Form HTML
<div>
<div>
Name:
<select>
<option value="one">One</option>
<option value="two">Two</option>
<option value="three">Three</option>
<option value="four">Four</option>
</select>
</div>
<br/>
<div>
Gmail:
<select>
<option value="one">One</option>
<option value="two">Two</option>
<option value="three">Three</option>
<option value="four">Four</option>
</select>
</div>
<br/>
<div>Select_CW_ID_From List:</div>
<select name="CW_ID" multiple>
<option value="one">One</option>
<option value="two">Two</option>
<option value="three">Three</option>
<option value="four">Four</option>
</select>
</div>
<br/>
<div>Standard Part</div>
<input type="text"/>
<br/>
<br/>
<div>Description</div>
<textarea rows="4" cols="50" name="comment" form="usrform">
Enter text here...</textarea>
</div>
<script>
function onSuccess(argReturnValue) {
alert('was successful ' + argReturnValue);
}
google.script.run.withSuccessHandler(onSuccess)
.nameOfFunctionInGS_File();
</script>
Download Notepad++: Notepad plus plus
And design your HTML in that. Then create an HTML file in your Apps Script project.
Your doGet() should just have the code that serves the HTML.
Code.gs
function doGet() {
return HtmlService.createTemplateFromFile('myHTML_File_Name_Here')
.evaluate() // evaluate MUST come before setting the NATIVE mode
.setTitle('Materials Form')
.setSandboxMode(HtmlService.SandboxMode.NATIVE);
};
Create another .gs file for dealing with the data. That's where all your code for writing data to the spreadsheet will go.
If you need to populate select boxes, you can do that with JavaScript in a script tag of the HTML.
With what I've given you, you should be able to create a Stand Alone Apps Script HTML Service app. Publish it, and run it. You probably did that with your current project.

Detect multiple drop-down selections and paragraph content dynamically with jQuery and JavaScript

I've created a madlib style paragraph with multiple drop-down selections for synonyms of various words. Here's an example:
<p id="the-text">This is an example paragraph containing many
<select class="selector">
<option>selections</option>
<option>dropdown thingies</option>
<option>option choosers</option>
</select>that I would like to be able to
<select class="selector">
<option>click on</option>
<option>select</option>
<option>choose</option>
</select>and then know what the
<select class="selector">
<option>final</option>
<option>selected</option>
<option>variable</option>
</select>paragraph text is.
<select class="selector">
<option>It would be great</option>
<option>It would be nice</option>
<option>It'd be delightful</option>
</select>, and
<select class="selector">
<option>useful</option>
<option>helpful</option>
<option>interesting</option>
</select>to dynamically create paragraphs like this.</p>
<textarea id="text-area" rows="4" cols="110">This is where the text should appear...
</textarea>
Here is a live example: http://jsfiddle.net/T4guG/2/
Using jQuery and Javascript, I am trying to get the selected (and surrounding) text to appear in the text area.
It's kind of working, but there are two problems:
1) SOLVED: There was a problem with punctuation, but replacing:
if (element == "{") {
content_array[i] = foo[j];
j++;
}
with
if (element.indexOf('{') >= 0) {
content_array[i] = foo[j];
j++;
}
allows { to be detected consistently
2) SOLVED: you only can change the options once.
Is there a more elegant solution than what I have come up with? Here is the code:
function updateTextArea() {
//get all of the text selections, and put them in an array
var foo = [];
$('.selector :selected').each(function (i, selected) {
foo[i] = $(selected).text();
});
//get the paragraph content, and store it
var safe_content = $('#the-text').html();
//delete all the options
$('.selector').text('');
//get the text without the dropdown options
var content = $('#the-text').html();
//create a regex expression to detect the remaining drop-down code
var pattern = "<select class=\"selector\"></select>",
re = new RegExp(pattern, "g");
//replace all the drop-down selections with {
content = content.replace(re, "{");
//turn the content into an array
content_array = content.split(" ");
//go through the array, and if a element is {, go to "foo" and replace it with the selected option
var length = content_array.length,
element = null;
var j = 0;
for (var i = 0; i < length; i++) {
element = content_array[i];
if (element == "{") {
content_array[i] = foo[j];
j++;
}
}
//turn the array back into a paragraph
new_content = content_array.join(" ");
//replace the text with the origionanl text
$('#the-text').html(safe_content);
//put the new content into the text area
$('#text-area').val(new_content);
}
$(document).ready(function () {
updateTextArea();
});
$(".selector").change(function () {
updateTextArea();
});
You are splitting text based on " " (using space) and replacing element { with array value but text is. {, and contains comma i.e., {, is not equal to {. Add space after element {. This solves your first problem.
As you are removing and adding select options dynamically in function updateTextArea(). You have to use .on() to attach event handler for dynamically created elements.
Try:
$( document ).on("change",".selector",function() {
updateTextArea();
});
Instead of
$(".selector").change(function () {
updateTextArea();
});
DEMO FIDDLE

Categories

Resources