Loop that will select all elements in a dropdownlist - javascript

I went in and created id tags for each dropdown. I tried creating a loop to select each manufacturer in the drop down without having to write 300+ lines of code since there are many options in some of the dropdowns. I tried and couldn't figure out a way. The second drop down for example is "source_manufacturer".
This is what i tried:
var expected = ['COMFORT-AIRE', 'Daewoo', 'GE'];
var els = element.all(by.id('source_manufacturer'));
for (var i = 0; i < expected.length; ++i) {
expect(els.get(i).getText()).toEqual(expected[i]);
}
Here is the html code:
<select id="source_manufacturer" ng-class="{'btn btn-default' : !$root.isMobile.iOS()}" class="form-control ng-valid btn btn-default ng-not-empty ng-touched ng-dirty ng-valid-parse" ng-model="manufacturer" ng-options="m.name for m in manufacturers">
`<option selected="selected" value="object:439" label="COMFORT-AIRE">COMFORT-AIRE</option>
....
<option value="object:443" label="Whirlpool">Whirlpool</option></select>`
This is the error message: Failed: Index out of bound. Trying to access element at index: 1, but there are only 1 elements that match locator By(css selector, *[id="source_manufacturer"]). I want to test if each one can be selected and that it actually changes.
The expected shows every element in the list instead of a single one.
This is how i would go about clicking each individual element in the list:
element(by.id('source_manufacturer')).click().
element(by.cssContainingText('option', 'GE')).click();

First of all, you should make sure you really have multiple select elements with source_manufacturer id. Then, you should be using each() instead of a regular for loop. And, I would use an elegant abstraction over the select-option structure suggested here:
var expected = ['COMFORT-AIRE', 'Daewoo', 'GE']
var selects = element.all(by.id('source_manufacturer'));
selects.each(function (select, index) {
var selectWrapper = SelectWrapper(select);
selectWrapper.selectByPartialText(expected[index]);
expect(selectWrapper.getSelectedOptions().first().getText()).toEqual(expected[index]);
});

Related

How to dynamically add more elements to a dropdown list with vanilla JS

I can't use Jquery or anything else, just Vanilla Javascript.
My initial approach was to have an array in global scope storing every registered item and then using a foreach to append an <option> child to the <select>, but apparently this only creates one option and renames it
HTML
<label for="productList">Show Products</label>
<select name="products" id="productList">
</select>
JS
let productArray = [];
let dropdown = document.getElementById("productList");
dropdown.addEventListener("click", initializeList());
function initializeList(){
//initializing with an example
productArray.push("PROD1");
productArray.push("PROD2");
productArray.push("PROD3");
productArray.forEach( item => {
option = document.createElement("option");
option.text = item;
dropdown.appendChild(option)
});
}
Unfortunately, this is not a very efficient approach since I'd have to manually create a variable every time I want to add something. I am going to create a method where you just pass an option name and it gets added to the dropdown options. It seems that even though it's a forEach, every option being added is the same. How can I avoid this?
When you setup the addEventListener, you need to send the function itself, not the return value.
You also need to test whether the select list has already been created before running the initializeList function. That way you only initialize it once.
let productArray = [];
let dropdown = document.getElementById("productList");
dropdown.addEventListener("click", initializeList); // send initializeList not initializeList()
function initializeList() {
if (productArray.length != 0) { // Don't initialize more than once
return;
}
//initializing with an example
productArray.push("PROD1");
productArray.push("PROD2");
productArray.push("PROD3");
productArray.forEach(item => {
option = document.createElement("option");
option.text = item;
dropdown.appendChild(option)
});
}
<label for="productList">Show Products</label>
<select name="products" id="productList">
</select>

Option value doesnt showup in dropdown - jquery

I am trying to add new options in a dropdown based on the other dropdown value.
the new added option doesnt appear in the dropdown on my custom webkit browser.
When I try to debug it the values are present in the dropdown, just it doesnt show up in the front end.
I have attached the code but its working in jsbin :(
When I click the empty dropdown and then click New button value doesnt show up but if I dont click the empty dropdown and click new button directly values appear normally.
https://jsbin.com/kikicuhabo/1/edit?html,css,js,output
It is a good practice to write HTML in lower case, and to close the tags.
If you want to use jQuery I recommend to select elements alway with the "$('')" instead of mixing with the "document. ... "
Since yours it is a custom browser I would try a solution in Vanilla JS.
function AddToCB(p_oCB, p_sText) {
var oSelect = document.querySelector(p_oCB);
var iNewLast = oSelect.length;
var sDisplay = p_sText + (iNewLast + 1);
var oNewItem = document.createElement('option');
oNewItem.innerHTML = sDisplay;
oNewItem.setAttribute('value', sDisplay)
oSelect.appendChild(oNewItem);
oSelect.selectedIndex = iNewLast;
return iNewLast;
}
function AddOption() {
var select = document.querySelector("#cmb");
var text = select.options[select.selectedIndex].value;
AddToCB('#list', text);
}
<select name="cmbColor" id="cmb">
<option>AA</option>
<option>BB</option>
<option>CC</option>
</select>
<input type="button" class="float-right" VALUE="New" onClick="AddOption()" >
<select name="list" id="list">
</select>

jquery, get value of different select list

I have a lot of select list (hundreds) like this (they have all the same name and id (I think my problem comes from here... but I can't change it):
<select name="custom_element_grid_class" id="custom_element_grid_class" class="select-size">
<option value="normal">normal</option>
<option value="square">square</option>
<option value="wide">wide</option>
<option value="tall">tall</option>
</select>
I want to get value of each list when an user change the value. I made this script but it only works on my fist select list...
jQuery("#custom_element_grid_class").change(function(){
var element = jQuery(this);
var selected = element.find('option:selected');
var size = selected.val();
var sclass = size + " element isotope-item";
jQuery(element).closest('.element').attr('class',sclass);
});
How can I make it works for all my select form?
EDIT: each select list comes from an ajx call, that's the reason I've got the same ID, but only in the futur DOM.
You cannot have double ID's.
So my suggestion in calling a function by inline onchange in the select.
For example:
<select name="custom_element_grid_class" id="custom_element_grid_class" onchange="func(this)" class="select-size">
And then your function:
function func(el){
var element = el;
var size = element.value;
var sclass = size + " element isotope-item";
jQuery(element).closest('.element').attr('class', sclass);
};
Demo here
I would suggest adding a first option with no value, so that, as you say "when an user change the value" you can read in case he took the first value.
If you can help it avoid duplicate IDs in exchange for classes. If this isn't an option use an attribute selector. Modifying the above code slightly.
Document Ready
$(function()
{
$('[name=custom_element_grid_class]').change(function(){
var $element = $(this);
var size = $element.val();
var sclass = size + " element isotope-item";
$element.closest('.element').attr('class',sclass);
});
});
Fiddle

How do set select element array index when it is in array and bind to blur event

I have array of select dom and input textbox . On blur event of input(of perticular index) want to set the element in select dom value of same index.
My bind is working but after each blur event for different input box it is retiurning 0.
I am not able to set the select value i.e. (drop down)as per given index
JSFiddle
My code is following.
$(document).ready(function (){
var i =1;
$('#addme').on('click', function(){
var test = '<tr class="employee"><td><input type="text" id="emp_id['+i+']" /></td><td><select id="emp_name['+i+']" '
test += '<option value="-1" >Please Select </option><option value="e0001" >James Smith</option><option value="e0002" >Roger Sm</option>'
test +='<option value="e0003" >Elina Lobo</option></select></td></tr>'
$('#addme').after(test);
i++;
});
$(".employee input").live('blur',function(){
var inputIndex = $(this).index();
var inputValue = $(this).val();
alert("Input Index is :" + inputIndex + ' and value is ' + inputValue);
$('#emp_name[inputIndex]').each(function(){
if(this.value == inputValue){
$('#emp_name[inputIndex]').val($(this).val());
return false;
}
alert("Please iput valid value");
$('#emp_name[inputIndex]').val('-1');
});
});
});
</script>
<table />
<tr class="employee">
<td><input class="employee" type="text" id="emp_id[0]" /></td>
<td><select id="emp_name[0]" name="emp_name">
<option value="-1" >Please Select </option>
<option value="e0001" >James Smith</option>
<option value="e0002" >Roger Sm</option>
<option value="e0003" >Elina Lobo</option>
</select></td>
</tr>
<input type="button" id="addme" value="ADD ME"/>
</body>
</html>
You would need to delegate the events as you are adding the elements dynamically on the click of the button..
So $(".employee input").live('blur',function(){
should look something like this
$(staticContainer).on('blur',".employee input", function(){
staticContainer is the element that is already in the DOM when the elements are bound with the element.
Closer the container better the performance.
Also you have multiple issues with your code..
It is a better idea to append the rows to the table, so that the selector returns the right element inside the table.
$('#addme').after(test);
Supposed to be
$('table').append(test);
Next this selector does not replace the index value
$('#emp_name[inputIndex]')
supposed to be
$('#emp_name[' + inputIndex + ']')
Lastly the way you are accessing the indexes is completely wrong.
You are trying to get the current input with respective to the other elements . So
var inputIndex = $(this).index();
supposed to look like
var inputIndex = $('input').index(this); // which will give the right value.
Check Fiddle
First,jQuery .Index() means find the index of e's all siblings,not the index of the selector field,if you want to do so,you need a selector parameter.
So
var inputIndex = $(this).index();
should change to
var inputIndex = $(this).index(".employee input");
then your index part will work fine.
Second,I actually don't understand your blur event code part.You said you want to set the same index of select dom,why you compare the value?And you use the jQuery attribute selector and I didn't see any match element.I guess you try to select all select doms,and you try to alert on loop?I don't think it's a good idea.
I think you should rebuild this part,it has no logic and very hard to read now.

<Select> with onChange working only once, and setting values with getElementsByName

I have various forms on a page, and a PHP-generated select on the top of the page.
What I want to do is:
The user selects an option from the form.
The value of the option is put into all of the inputs with a specific name.
The user can select another option, and the value of that option would replace the old value of the input.
The code I have so far (that doesn't work):
It doesn't work as in the onChange only fires the first time you select an option, and the values of the inputs aren't updated to the chosen option's value.
The select: (It can have more or less than three options, depending on the user.)
<select name="example" onchange="setexample()" id="exampleID">
<option value="1">Default Example</option>
<option value="12">User-created Example #2</option>
<option value="8">User-created Example #1</option>
</select>
This is part of one of the forms around the page:
<form action="[URL]" method="get">
<input type="hidden" name="exampleform" id="example1" value="">
// Other inputs //
</form>
JavaScript:
<script>
function setexample(){
setexample = document.getElementById("exampleID").options[document.getElementById("exampleID").selectedIndex].value;
document.getElementsByName("exampleform").value = setexample;
}
</script>
I don't want to use jQuery. This is just JavaScript.
Thank you in advance.
In your code:
> function setexample(){
> setexample = document...
The assignment to setexample overwrites the existing value (which is the function setexample). Declare the variable inside the function:
var setexample = document...
For the rest, see nnnnnn's answer.
The getElementsByName() method returns a list of elements, so you can't just directly set the value property that belongs to the individual elements in the list. You need to loop through the list (it's an HTMLCollection but for this purpose you can treat it like an array):
var els = document.getElementsByName("exampleform");
for(var i = 0; i < els.length; i++)
els[i].value = setexample;
For the rest, see RobG's answer.
You have these issues:
You're overwriting the name of your function and should use a local variable of a different name.
You're reference a single element form getElementsByName when it returns an array.
Try this:
<script>
function setexample(){
var item = document.getElementById("exampleID");
var val = item.options[item.selectedIndex].value;
var list = document.getElementsByName("exampleform");
for (var i = 0; i < list.lenth; i++) {
list[i].value = val;
}
}
</script>

Categories

Resources