How to Set Dropdown Value with dom-repeat - polymer

I am trying to select the second option form a dropdown if specific conditions are met, am having problems with the selectedIndex
<select id="contact" on-change="selectContact">
<option value="-1" selected>Select Contact</option>
<template is="dom-repeat" items="[[contacts]]" as="contact" index-as="index">
<option value="[[contact]]">[[contact]]</option>
</template>
</select>
<select id="name" on-change="selectName">
<option value="-1" selected>Select Name</option>
<template is="dom-repeat" items="[[names]]" as="name">
<option value="[[name]]">[[name]]</option>
</template>
</select>
...
selectContact() {
for (let i = 0; i < this.customerTable[0].length; i++) {
if(true) {
array[i] = this.customerTable[0][i]['name'];
}
}
this.names = this.$.util.utilFn(array);
if(this.names.length == 1) {
this.shadowRoot.querySelector('#name').selectedIndex = 2;
}
}
How can I select the second child of a dom-repeat dropdown?

In selectContact(), you're setting this.names (to which the second <dom-repeat>.items is bound) and immediately attempting to select the first item of that <dom-repeat> before the DOM has actually updated.
You actually need to wait until the next render frame with Polymer.RenderStatus.afterNextRender() before selecting the item:
selectContact() {
this.names = ['John'];
if (this.names.length === 1) {
Polymer.RenderStatus.afterNextRender(this, () => {
this.shadowRoot.querySelector('#name').selectedIndex = 1;
});
}
}
demo

Related

Matching two ID attributes from cloned dependent dropdown list

In this code I have 2 dependent dropdown lists and a button to duplicate/clone the form. The color selection changes based on what is selected in item. When I duplicate the dropdown list the function didn't work. I tried changing the id of the duplicated dropdown list but still can't manage to match the id of 2 dropdown list. Is there any solution? Thanks.
var count = 1;
var duplicate_div = document.getElementById('duplicate_1');
function addRecord() {
var clone = duplicate_div.cloneNode(true);
clone.id = "duplicate_" + ++count;
duplicate_div.parentNode.append(clone);
var cloneNode = document.getElementById(clone.id).children[0];
$(clone).find("*[id]").each(function() {
$(this).val('');
var tID = $(this).attr("id");
var idArray = tID.split("_");
var idArrayLength = idArray.length;
var newId = tID.replace(idArray[idArrayLength - 1], count);
$(this).attr('id', newId);
});
}
$(document).ready(function() {
$("#item_" + count).change(function() {
var val = $(this).val();
if (val == "shirt") {
$("#color_" + count).html("<option>Black</option> <option>Gray</option>");
} else if (val == "pants") {
$("#color_" + count).html("<option>Blue</option> <option>Brown</option>");
} else if (val == "shoe") {
$("#color_" + count).html("<option>White</option> <option>Red</option>");
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form class="select-form">
<div class="duplicate" id="duplicate_1">
<br>
<label>item</label>
<select id="item_1">
<option value="template" disabled selected></option>
<option value="shirt">Shirt</option>
<option value="pants">Pants</option>
<option value="shoe">Shoe</option>
</select>
<label>color</label>
<select id="color_1">
<option disabled selected>Select item first</option>
</select>
</div>
</form>
<br><br>
<button type="button" id="add-button" onclick="addRecord()">add</button>
Since you've imported jQuery into the project, I suggest you fully use it.
It's recommended to use jQuery's .on method instead of onclick attribute.
The change event will not work on the dynamically created elements.
You should instead use "event delegation".
Last but not least, you can remove the ids if they serve as selectors. You can use jQuery to easily transverse the DOM
Try this
$(document).ready(function() {
var $cloned = $('.duplicate').first().clone(true);
var $container = $('.select-form');
$('#add-button').click(function() {
$container.append($cloned.clone());
})
$('.select-form').on('change', '.item', function() {
var val = $(this).val();
var $color = $(this).closest('.duplicate').find('.color');
if (val == "shirt") {
$color.html("<option>Black</option> <option>Gray</option>");
} else if (val == "pants") {
$color.html("<option>Blue</option> <option>Brown</option>");
} else if (val == "shoe") {
$color.html("<option>White</option> <option>Red</option>");
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form class="select-form">
<div class="duplicate">
<br>
<label>item</label>
<select class="item">
<option value="template" disabled selected></option>
<option value="shirt">Shirt</option>
<option value="pants">Pants</option>
<option value="shoe">Shoe</option>
</select>
<label>color</label>
<select class="color">
<option disabled selected>Select item first</option>
</select>
</div>
</form>
<br><br>
<button type="button" id="add-button">add</button>

Jquery check if multiple drop down list has any selected option

I am trying to display in console a message when a user removes all options from a multiple drop down list. My current code creates a JSON object when there are options selected and encodes the items into a URI string component.
How can I display a message when the user removes all selected options?
<div class="form-group row">
<label class="col-sm-3 col-form-label">Customer</label>
<div class="col-sm-9">
<select id="Customers" class="js-select2-custom custom-select" name="CustomerID" multiple size="1" style="opacity: 0;" asp-for="CustomerID" onchange="getSelects()"
data-hs-select2-options='{
"minimumResultsForSearch": "Infinity"
}'>
#{
var selectedCustomer = Model.CustomerList.Where(x => Model.SelectedCustomers.Any(c => c.CustomerID == x.CustomerID));
var Customers = Model.CustomerList.Where(x => !Model.SelectedCustomers.Any(c => c.CustomerID == x.CustomerID));
}
#foreach (var item in selectedCustomer)
{
<option value="#item.CustomerID" selected>#item.CustomerName</option>
}
#foreach (var item in Customers)
{
<option value="#item.CustomerID">#item.CustomerName</option>
}
</select>
</div>
</div>
function getSelects() {
$('#selectedText').val('');
var items = $("#Customers > option:selected").map(function () {
var opt = {};
$('#Customers > option:selected').each(function() {
if ($(this).not(':selected')) {
alert('Yes')
}
});
return opt;
}).get();
$('#selectedText').val(encodeURIComponent(JSON.stringify(items)));
console.log($('#selectedText').val());
}
How about something like this? Press and hold the "Ctrl" key to select/deselect multiple:
$('#cars').change(function(){
// get selected values:
var values = $(this).val();
console.log('selected values: ', values);
// send alert if none are selected:
if (!values.length) alert('No values selected!');
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<label for="cars">Choose a car:</label>
<select name="cars" id="cars" multiple>
<option value="volvo">Volvo</option>
<option value="saab">Saab</option>
<option value="opel">Opel</option>
<option value="audi">Audi</option>
</select>

Html select keystroke timeout

I'm creating a standard html select dropdown with a hundred or so entries. My users would like to be able to type in the value to get to the proper selection faster. While this is supported natively, the keystroke timeout is very quick, so if you don't type the string quickly, you end up with the wrong selection. Is there a way to increase the timeout? Or has anyone written code to do this manually?
Here's a jsFiddle to illustrate the issues. JsFiddle
label for="title">Choose your poison</label>
<select id="title" name="title">
<option value="Cider" selected>Apple Cider</option>
<option value="Juice">Apple Juice</option>
<option value="Curacao">Curacao</option>
<option value="Jack">Jack's Hard Cider</option>
<option value="Jake">Jake's Hard Cider</option>
<option value="James">James' Hard Cider</option>
<option value="Jamison">Jamison Irish Whiskey</option>
<option value="Kool">Kool Ade</option>
<option value="Lemonade">Lemonade</option>
<option value="Prune">Prune Juice</option>
</select>
Try selecting the Jack's or Jake's by slowly typing and see if you end up selecting Curacao or Kool Ade.
You could use a <datalist> instead. It's supported in IE10 and higher. MDN Page
DEMO
<label for="poison">Choose your poison</label>
<input id="poison" name="poison" list="poisons" />
<datalist id="poisons">
<option value="Cider" selected>Apple Cider</option>
<option value="Juice">Apple Juice</option>
<option value="Curacao">Curacao</option>
<option value="Jack">Jack's Hard Cider</option>
<option value="Jake">Jake's Hard Cider</option>
<option value="James">James' Hard Cider</option>
<option value="Jamison">Jamison Irish Whiskey</option>
<option value="Kool">Kool Ade</option>
<option value="Lemonade">Lemonade</option>
<option value="Prune">Prune Juice</option>
</datalist>
If you have a small number of entries, the answer using datalist is fantastic. However, my users were using lists that had over a hundred entries and the datalist won't scroll. So, I built a utility class for use in a few places.
To use it, create the listFilter and initialize it with your list of choices. Then hook up keyUp and keyPress and use the return values. The class uses a 2-second time out and actually filters the answers. Using the delete key, you can clear the filtering. Be sure to check for a null return value in the keyUp, since that only handles the delete key. Note that the dropdown must be unexpanded for you to get the key events to work.
var listFilter = {
originalListToHold: [],
time1: 1,
search: "",
initialize: function(originalListToCopy) {
this.originalListToHold = [];
for (var i = 0; i < originalListToCopy.length; i++) {
this.originalListToHold[i] = originalListToCopy[i];
}
},
isInOriginalList: function(member) {
return this.originalListToHold.indexOf(member) > 1;
},
keyUpEvent: function(event) {
var keyCode = event.keyCode;
if (keyCode == 46) {
var filtered = this.filterList("");
this.search = "";
event.stopPropagation();
return filtered;
} else {
return null;
}
},
keyPressEvent: function(event) {
//The delete key will reset the list. See the key up event above.
var val = String.fromCharCode(event.which).toUpperCase();
var timenow = event.timeStamp;
var timeDiff = timenow - this.time1;
if (!isNaN(timeDiff)) {
//If the time difference is < 2 seconds (2000 ms), then we
//will search the options.
if (timeDiff > 2000) {
//Reset the search string
this.search = "" + val;
} else {
this.search = this.search + val;
}
} else {
this.search = "" + val;
}
this.time1 = timenow;
//Now, let's filter the options by the search string.
var filtered = this.filterList(this.search);
event.stopPropagation();
return filtered;
},
filterList: function(filter) {
var newList = [];
for (var i = 0; i < this.originalListToHold.length; i++) {
if (this.originalListToHold[i].indexOf(filter) > -1) {
newList.push(this.originalListToHold[i]);
}
}
return newList;
}
}

Multiple dropdown menu filter in html

Assume I have two dropdown Menu, is it possible to filter menu b by using HTML code only?
If not, which method can be apply for this case with simply code.
menu a with A B
menu b with A1 A2 B1 B2
You can do this with the help of Javascript.
Suppose you have one dropdown with some values as "Colours, Shapes, Names" with html as:
Dropdown1:
<select id="ddl">
<option value=""></option>
<option value="Colours">Colours</option>
<option value="Shapes">Shapes</option>
<option value="Names">Names</option>
</select>
And you want to filter another one based on first dropdown selected value
Dropdown2:
<select id="ddl2">
</select>
Then Apply below Javascript code:
Filter out:
function configureDropDownLists(ddl1,ddl2) {
var colours = new Array('Black', 'White', 'Blue');
var shapes = new Array('Square', 'Circle', 'Triangle');
var names = new Array('John', 'David', 'Sarah');
switch (ddl1.value) {
case 'Colours':
ddl2.options.length = 0;
for (i = 0; i < colours.length; i++) {
createOption(ddl2, colours[i], colours[i]);
}
break;
case 'Shapes':
ddl2.options.length = 0;
for (i = 0; i < shapes.length; i++) {
createOption(ddl2, shapes[i], shapes[i]);
}
break;
case 'Names':
ddl2.options.length = 0;
for (i = 0; i < names.length; i++) {
createOption(ddl2, names[i], names[i]);
}
break;
default:
ddl2.options.length = 0;
}
}
And create option runtime for second dropdown:
function createOption(selBox, text, value) {
var opt = document.createElement('option');
opt.value = value;
opt.text = text;
selBox.options.add(opt);
}
Apply:
onchange="configureDropDownLists(this,document.getElementById('ddl2'))" in first dropdown, as:
<select id="ddl" onchange="configureDropDownLists(this,document.getElementById('ddl2'))">
<option value=""></option>
<option value="Colours">Colours</option>
<option value="Shapes">Shapes</option>
<option value="Names">Names</option>
</select>
So dropdown 2 gets filter based on first selected value.
Please refer to fiddle for live demo
Hope this will help you :)

HTML Multiselect Limit

Is it possible to set limit to multipleselect?
Below is an example code where user can select more than 1 value.
<select multiple="multiple" name="choose">
<option value="1">Value 1</option>
<option value="2">Value 2</option>
<option value="3">Value 3</option>
<option value="4">Value 4</option>
<option value="5">Value 5</option>
<option value="6">Value 6</option>
</select>
But, how to limit user to select not more than 3 value.
Any idea?
You can use jQuery
$("select").change(function () {
if($("select option:selected").length > 3) {
//your code here
}
});
You would do this via javascript on the client side, and then add a check on the server side as well in case the client has disabled javascript.
Here is some basic client side code to give you an idea:
<html>
<body>
<form onsubmit="validate()">
<select multiple="multiple" id="choose" name="choose">
<option value="1">Value 1</option>
<option value="2">Value 2</option>
<option value="3">Value 3</option>
<option value="4">Value 4</option>
<option value="5">Value 5</option>
<option value="6">Value 6</option>
</select><br>
<input type="submit">
</form>
<script>
function validate()
{
var selectChoose = document.getElementById('choose');
var maxOptions = 2;
var optionCount = 0;
for (var i = 0; i < selectChoose.length; i++) {
if (selectChoose[i].selected) {
optionCount++;
if (optionCount > maxOptions) {
alert("validation failed, not submitting")
return false;
}
}
}
return true;
}
</script>
</body>
</html>
Script that will disallow more than 3 elements to be selected (as opposed to just validating it at submit time).
http://jsfiddle.net/v33sszgp/
var verified = [];
document.querySelector('select').onchange = function(e) {
if (this.querySelectorAll('option:checked').length <= 3) {
verified = Array.apply(null, this.querySelectorAll('option:checked'));
} else {
Array.apply(null, this.querySelectorAll('option')).forEach(function(e) {
e.selected = verified.indexOf(e) > -1;
});
}
}
Note there's some additional complexity related to preventing the item from actually being selected on the select and that it rather validates a user's actions and reverts it if it's invalid.
RedFilter has the right idea with validating by javascript. Haven't tested, but you could do something like:
var options = document.all.tags("option");
var selectedCounter = 0;
for (var i=0; i < options.length; i++) {
if (options[i].selected) {
selectedCounter++;
}
checkCounter();
}
function checkCounter() {
//disable all options here
}