select drop down option based on associated text - javascript

I have a drop down with a value and associated text as such:
echo '<option value="'.$row['company_id'].'">'.$row['company_name'].'</option>';
Eventually, the output of the selected option is put into a table, row by row. By each row, there is an edit button to edit that particular row and select a new drop down option. I'm trying to use JavaScript to select the text and when they hit the edit button, the option that is currently set will be the default choice.
So for instance, if the row says the company_name is: ABC Company, when they hit the edit button, the drop down will populate with that option. Since the value and text are different, I need to choose the drop down option based on text. I have tried these 2 options so far with no luck.
To get the row text:
var d = document.getElementById("itable").rows[id].cells[3].innerText;
I have tried the following to pass back the text of the row, and to select the drop down by text.
document.querySelector('#editinsurancepolicymodal select[name=editicompanydropdown]').value = d;
This option just populates the drop down, but no choice is selected.
document.querySelector('#editinsurancepolicymodal').find('option[text="InsuranceB"]').val;
This option selects the first option in the drop down, but doesn't change based on what the 'text' is.
Thank you for your help in advance.

One way will be to iterate over the option elements, selecting the one that has the same text as the text from the row, and un-selecting all the others. This is illustrated in the snippet below (I have inserted a 3 second timeout, so that you can see that the initially selected option (Two) is changed to the option with the text "Three" from the JavaScript code.
window.setTimeout(function () {
var sampleWord = "Three";
var options = document.querySelectorAll("option");
for (var i = 0; i < options.length; i++) {
var option = options[i];
if (option.innerText === sampleWord) {
option.selected = true;
} else {
option.selected = false;
}
}
}, 3000);
<select id="selector">
<option id="option-1" value="1">One</option>
<option id="option-2" value="2" selected>Two</option>
<option id="option-3" value="3">Three</option>
<option id="option-4" value="4">Four</option>
</select>
Alternately, you could store the id for the company as a data-attr attribute on the row. For example (in PHP):
echo "<td data-attr-company-id=".$row['company_id'].">".$row['company_name']."</td>"
Then, you can read the attribute from the table row, and query for the option that has the same value as your attribute value.

var options = document.querySelectorAll("option");
This will select all options from the page. If you want to get the options for a specific drop down, use the following:
var options = document.querySelector('#specificform select[name=specific_drop_down_in_the_specific_form]');
To select the option based on the text and not the value, use this loop:
for (var i=0; i<options.length; i++){
var option = options[i];
if (option.innerText === d){
option.selected = true;
}
}

Related

Is there a way to show the selected option value in the select menu after turbolinks.visit(url)

I have select menu with bunch of options having "url's" as their value. Once user click on the option , it will take them to particular url. I want the selected option to be shown on select menu when taken to the particular url.
Code:
Html:
<div data-controller="dropdown">
<select id="abcMenu" data-action="dropdown#abc">
<option value="/abc">A</option>
<option value="/xyz">B</option>
<option value="/def">C</option>
</select>
</div>
Javscript
abc(){
var elt = document.getElementById('abcMenu');
elt.options[elt.selectedIndex].setAttribute('selected','selected');
var option = elt.options[elt.selectedIndex].value;
Turbolinks.visit(option);
}
Turbolinks will take to next path whereas dropdown option gets preselected to first option. Can anyone please let me know how to fix this.
You can use window.location.pathname to get the path and then set the corresponding option from the select:
function selectOptionByValue(element, value){
for(var i=0; i < element.options.length; i++) {
if(element.options[i].value == value) {
element.selectedIndex = i;
}
}
}
Where element is the select element and value is the path that you want to check.

How to use JQuery to grab the selected option off of a class?

I have a table with a bunch of rows with the same dropdown options. What I want to do is on a button click, grab the selected values for the dropdown that the row that the button is in.
<select class="items" data-value="#item.Id">
<option>None</option>
#foreach (var item in ViewBag.Items)
{
<!option value="#(item)">
#(item.Title)
</!option>
}
</select>
What I have tried to do is:
var button = $(event.target);
var itemClass = button.closest(".items");
var selectedItem = itemClass.options[this.selectedIndex].text;
This does correctly grab the class, but it can't seem to get text of the selected item.

Change select to check boxes using javascript

The reason I would like to do this, is that it will be situational. If a user is logged in, they will see drop downs. If not, they will see a list of text. Ideally just plain text, but I don't know if that's possible, so I was thinking I could convert the <select> to checkboxes and hide the check boxes with CSS.
Basically we don't want a user who isn't logged in to feel they can select anything, because they won't be able to order and this could lead to frustration. But we would still like them to view what options are available for each product as unselectable text. If there is a better way to do this than what I'm thinking, I'd be grateful for suggestions. For now, this is what I've patched together, but it's not changing the select to checkboxes.
I grabbed some code from here to use as a starting point: http://www.w3schools.com/jsref/met_element_setattribute.asp
Also, I can't grab the < select > by id, because this will be on all < select >'s.
<select id="unique_id" class="unique_class" data-attribute_name="unique_attribute_name" name="unique_name">
<option value="" selected="selected">Choose an option</option>
<option class="attached enabled" value="516">5/16"</option>
<option class="attached enabled" value="38">3/8"</option>
</select>
Javascript:
function myFunction() {
document.getElementsByTagName("SELECT")[0].setAttribute("type", "checkbox");
}
Here is a fiddle: https://jsfiddle.net/d4qdekom/
This should convert your select to checkboxes, provided there is an HTML element with an id of "container" to append the new checkboxes.
This is the HTML
<select id="unique_id" class="unique_class" data-attribute_name="unique_attribute_name" name="unique_name">
<option value="" selected="selected">Choose an option</option>
<option class="attached enabled" value="516">5/16"</option>
<option class="attached enabled" value="38">3/8"</option>
</select>
<div id="container"></div>
The JavaScript function to transform the select to checkboxes below
function myFunction() {
var select = document.getElementById('unique_id');
var container = document.getElementById('container');
var i;
for (i = 0; i < select.length; i++) {
var checkbox = document.createElement('input');
checkbox.type = 'checkbox';
checkbox.name = 'option';
checkbox.id = 'randomId' + i;
checkbox.value = select.options[i].text;
var label = document.createElement('label')
label.htmlFor = 'randomId' + i;
label.appendChild(document.createTextNode(select.options[i].text));
container.appendChild(checkbox);
container.appendChild(label);
}
}
You can then go ahead and remove the select from the DOM. I guess all these should be made easier with JQuery
This is an update using getElementsByTagName:
var selects = x.getElementsByTagName('SELECT'); // this is a node list
for (var i = 0; i < y.length; i++) {
var select = selects[i]; // this is a single select element
// You can call the above function on each select here...
}
This is a working jsFiddle
I hope this helps.
If I am understanding your goal correctly, you can just put div's in and hide/show or enable/disable the div's depending on if the user is logged in or not. So wrap your select up in a div and just toggle that.
This would avoid trying to change the html by simply showing/hiding or enabling/disabling what you want the user to see.

HTML/Javascript Set up Two Select Options and redirect once first one is selected

<select id="First DropDown" name="" onchange="javascript:location.href = this.value;">
<option value="/url">Option1</option>
<option value="/url">Option2</option>
<option value="/url">Option3</option>
<option value="/url>Option4</option>
<option value="" selected="selected">Option5</option>'
</select>
<select id="Second DropDown" name="" onchange="javascript:location.href = this.value;">
<option value="/url">Option1</option>
<option value="/url">Option2</option>
<option value="/url">Option3</option>
<option value="/url>Option4</option>
<option value="" selected="selected">Option5</option>'
</select>
That's really all I got. Basically what I want is when someone selects an option (such as option 1) on the first dropdown menu, it then pulls up a specific set of options. So for example, if someone selects "Option 1" on the first drop down menu, then on the second drop down menu options such as "#1" "#2" "3" come up, but if someone selections "Option 2" on the first drop down menu, menu options such as "4" "5" "6" come up. I would also like to know how to set up a search button so that when both the drop downs have a specific set of option selected, it then redirects to a specific page I set. Sorry about all of this.. I know Im not very good
You need to create an event handler on the first text box that fills the second text box with options. A good way to do this is to store your options in a 2D array, so when the first select box is selected, your Javascript code can easily loop over and create the new options.
With HTML like this
<!-- In your own code, do not use onsubmit="return false" -->
<form id="searchForm" action="#" onsubmit="return false">
<input type="text" name="search" value="Search a little"/>
<fieldset>
<label>Search parameters</label>
<select id="first" name="first"></select>
<select id="second" name="second">
<option>-----</option>
</select>
</fieldset>
<input type="submit" value="Search" />
</form>
and Javascript like this:
var options = [
["A","B","C"],
["D","E","F"],
["G","H","I"],
["J","K","L"]
],
first = document.getElementById('first'),
second = document.getElementById('second'),
searchForm = document.getElementById('searchForm'),
searchButton = document.querySelector('input[type="submit"]'),
destination,
option;
// Fill the second text box with options from the array.
function fillSecond() {
// Get the list of options
var secondOptions = options[first.value];
// Clear the previous options
second.innerHTML = '';
// Add each option to the select box
for (var i = 0; i < options[first.value].length; i++) {
option = document.createElement('option');
option.value = secondOptions[i];
option.innerHTML = 'Option ' + secondOptions[i];
second.appendChild(option);
}
// Select the first option by default.
second.firstElementChild.setAttribute('selected','selected');
// update the from
updateFormAction();
};
function updateFormAction() {
searchForm.action = destination = '#' + first.value + second.value;
}
// When the second box is updated, update the second select
// and update the form action
first.addEventListener('change', fillSecond);
// Fill the first select box with options
for (var i = 0; i < options.length; i++) {
option = document.createElement('option');
option.value = i;
option.innerHTML = 'Option ' + i;
first.appendChild(option);
}
// By default select the first element.
first.firstElementChild.setAttribute('selected','selected');
// When search is clicked, alert where the form will take them
searchButton.addEventListener('click', function () {
alert('Sending user to location: ' + destination);
return false;
});
// When the second box is updated, update the form action
second.addEventListener('change', function () {
updateFormAction();
});
// On startup, fill the second box.
fillSecond();
You can change where your form goes to based on which options the user selects from the drop down.
See the demo at this jsFiddle to get yourself started
What you are looking for is called "Chained Select Box" - you can change the options values easy with Jquery, but better you take one Plugin which provides this functionality:
For Example:
http://www.appelsiini.net/projects/chained/demo.html
Or here if you are using a Database (MySQL) and PHP to provide the Content of your Select Boxes
http://www.yourinspirationweb.com/en/how-to-create-chained-select-with-php-and-jquery/

How to populate a form list with buttons using javascript

I made a script that, when you press one button(accessories) the selection(mylist) populates with one array(accessoryData), and when you hit the other button(weapons) the other array(weaponData) populates the selection. However, in the current state of the code the second button press is not re-populating the selection. What is wrong here?
Also if there is a more efficient way to do this, that might be helpful.
Full code
function runList(form, test) {
var html = "";
var x;
dataType(test);
while (x < dataType.length) {
html += "<option>" + dataType[x];
x++;
}
document.getElementById("mylist").innerHTML = html;
}
I believe you are trying to make a <select> element ie the drop down menu, but proper markup is:
<select id="myList">
<option value="1">Option 1</option>
<option value="2">Option 2</option>
<option value="n">Option n</option>
</select>
You forgot to close the <option> tag with innerHTML property.
Using native JS methods:
//create the select element
var select = document.create('select');
//or use getElementById if it's already there
//Assuming your datatype is an Array of string
var opt;
for(var i=0; i<datatype.length; i++){
//create the option element
opt = document.create('option');
opt.textContent = datatype[i]; //innerText works too
//set the value attribute
opt.setAttribute('value',i+1); //+1 or else it would start from 0
//add the option to the select element
select.appendChild(opt);
//conversely use removeChild to remove
}
//at last add it to the DOM if you didn't fetch it from the DOM.

Categories