I'm trying to capitalize each first letter in a simple JS array,
the code works fine in the console log - but not on the output
Thanks.
<select id="selectId">
<option value="hello">one</option>
<option value="hello">two</option>
<option value="hello">three</option>
var arr=[];
$("#selectId >option").each(function() {
arr.push(this.text.substr(0,1).toUpperCase() + this.text.substr(1));
});
var i, len, text;
for (i = 0, len = arr.length, text = ""; i < len; i++) {
console.log(arr[i]);
$("#select").text(arr[i]);
}
fiddle
var arr=[];
$("#selectId >option").each(function() {
arr.push(this.text.substr(0,1).toUpperCase() + this.text.substr(1));
});
var i, len, text;
for (i = 0, len = arr.length, text = ""; i < len; i++) {
console.log(arr[i]);
$("#select").text(arr[i]);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.1/jquery.min.js"></script>
<select id="selectId" style="text-transform: capitalize;">
<option value="hello">one</option>
<option value="hello">two</option>
<option value="hello">three</option>
Add one class in css
.capitalize{text-transform: capitalize;}
and in HTML add whereever you want to capitalize.
Use substring instead of substr. Substring is understood in more browsers .
Another solution :
function capitalizeFirstLetter(string) {
return string.charAt(0).toUpperCase() + string.slice(1);
}
You need to edit each option text, not the "text of the select" which does not mean anything in fact.
$("#selectId > option").each(function() {
$(this).text(
this.text.substr(0,1).toUpperCase() + this.text.substr(1)
);
});
I removed your intermediate array for simplicity.
honestly you dont need a lib like jquery for this:
var arr = Array.prototype.map.call(document.querySelector("#selectId").options, function (option) {
var text = option.textContent;
return option.textContent = text.substr(0, 1).toUpperCase() + text.substr(1);
});
console.log(arr);
<select id="selectId">
<option value="hello">one</option>
<option value="hello">two</option>
<option value="hello">three</option>
</select>
<select name="selectId">
<option value="hello">one</option>
<option value="hello">two</option>
<option value="hello">three</option>
first select all dropdown value in a array
var selected = $('select[name="selectId"]').map(function(){
if ($(this).val())
return $(this).val();
}).get();
now use String.toUpperCase()
var upperCasedArray = $.map(selected , function(item, index) {
return item.toUpperCase();
});
Heres's how you capitalize every word
function capitalize(string) {
return typeof string === 'string'
? string.toLowerCase().replace(/(^\w|\s\w)/g, m => m.toUpperCase())
: string
}
Related
I want to stock multiples choices in a input hidden when I change my select (example I select the last option then the first option) I get in my input the same order .
$('select').change(function() {
var str = "";
// For multiple choice
$("select option:selected").each(function() {
str = $(this).val() + str + " ";
});
alert(str);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select name="brands[]" class="chosen selectbrands fixed-width-xl" id="brands[]" multiple="multiple">
<option value="1">BASTIEN test0</option>
<option value="2">BASTIEN test1</option>
<option value="3">BASTIEN test2</option>
</select>
Now If I change for example
(BASTIEN test1/BASTIEN test2/BASTIEN test0)
when I run my code I get
(BASTIEN test0/BASTIEN test1/BASTIEN test2)
this my code work fine but when I select the last then the second the problem here Is when I select the third one they don't work and I don't get the value of my option inside my var
If I understood you correctly this may help:
Target options directly with click event and save them in order in array.
With e.target.selected ? you make sure push is made on selected only.
remove function will remove element from array if deselected.
var str = []
$('select#brands option').on("click", function(e) {
let l = $(e.target).parent().find("option:selected").length
console.clear()
if (l > 1) {
e.target.selected ? str.push(e.target.value) : remove(str, e.target.value);
} else if (l === 1 && str.length != 2) {
str = [e.target.value]
} else if (l === 1 && str.length === 2) {
remove(str, e.target.value)
} else if (l === 0) {
str = []
}
console.log(str)
});
function remove(str, item) {
var index = str.indexOf(item);
if (index !== -1) {
str.splice(index, 1);
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select name="brands[]" class="chosen selectbrands fixed-width-xl" id="brands" multiple="multiple">
<option value="1">BASTIEN test1</option>
<option value="2">BASTIEN test2</option>
<option value="3">BASTIEN test3</option>
<option value="4">BASTIEN test4</option>
</select>
Like this. When you select from the beginning, the options array is reset.
var str = "";
$('select').change(function() {
//alert($(this).find("option").length);
if($(this).find("option").length < str.split(" ").length){
str = "";
}
// For multiple choice
str = $(this).find("option:selected").val() + str + " ";
alert(str);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select name="brands[]" class="chosen selectbrands fixed-width-xl" id="brands[]" multiple="multiple">
<option value="1">BASTIEN test0</option>
<option value="2">BASTIEN test1</option>
<option value="3">BASTIEN test2</option>
</select>
I have this drop down that I compare with an array. If a value in the array matches the text of one of the options in the dropdown, then it is selected:
JS -Step One:
var topicArray = ['Apples', 'Tomatoes'];
populateExistingDropDowns ('topicSelect',topicArray);
Dropdown
<select class="topicSelect" multiple>
<optgroup label="Crops">
<option selected="" value=""></option>
<option value="Apiculture">Apiculture</option>
<option value="Apples">Apples</option>
<option value="Aquaculture">Aquaculture</option>
<option value="Blueberries">Blueberries</option>
</optgroup>
<optgroup label="Add Option" class="youOwn">
<option value="own">Add Your Option</option>
</optgroup>
</select>
JS - Step Two:
function populateExistingDropDowns(dd, array) {
var select = document.getElementsByClassName(dd);
for (var d = 0; d < array.length; d++) {
for (var i = 0; i < select[0].options.length; i += 1) {
if (select[0].options[i].text === array[d]) {
select[0].options[i].selected = true;
}
}
}
}
Here comes my issue: The the code showed above works just fine, but I would like to be able to add a new option if an option with the same array value doesn't exist. In the example shown above, there are two values ('Apple' and 'Tomatoes") values in the array. When I iterate through the array and the dropdown, the 'Apple' option is selected, but, how can I then add a new 'Tomatoes' options, and then select it also? Thanks in advance, please let me know if more details are needed.
I would like to be able to add a new option if an option with the same array value doesn't exist..
you can clone an option node modify it and append it to parent node,
in the snippet I added a dedicated function;
function populateExistingDropDowns(dd, array) {
var select = document.getElementsByClassName(dd);
outer:
for (var d = 0; d < array.length; d++) {
for (var i = 0; i < select[0].options.length; i += 1) {
if (select[0].options[i].text === array[d]) {
select[0].options[i].selected = true;
continue outer;
}
//if you haven't matched and are in last loop
if ( i === select[0].options.length - 1) {
addOpt(array[d], select[0].options[i])
}
}
}
}
function addOpt(x,clone){
var node = clone.cloneNode();
node.selected= true;
node.value= node.innerHTML= x;
clone.parentNode.appendChild(node)
}
var topicArray = ['Apples', 'Tomatoes'];
populateExistingDropDowns ('topicSelect',topicArray);
<select class="topicSelect" multiple>
<optgroup label="Crops">
<option selected="" value=""></option>
<option value="Apiculture">Apiculture</option>
<option value="Apples">Apples</option>
<option value="Aquaculture">Aquaculture</option>
<option value="Blueberries">Blueberries</option>
</optgroup>
<optgroup label="Add Option" class="youOwn">
<option value="own">Add Your Option</option>
</optgroup>
</select>
One approach, using ES6 syntax is the following:
function populateExistingDropDowns(dd, array) {
// using 'let' rather than 'var' to declare variables,
// using document.querySelector(), rather than
// getElementsByClassName(), because d.qS has support
// in IE8 (whereas it does not support
// getElementsByClassName()); however here we get the
// first element that matches the selector:
let dropdown = document.querySelector('.' + dd),
// retrieving the collection of option elements,
// HTMLSelectElement.options, and converting that
// collection into an Array using Array.from():
options = Array.from(dropdown.options);
// iterating over each of the topics in the passed-in
// array, using Array.prototype.forEach():
array.forEach(function(topic) {
// filtering the array of <option> elements to keep
// only those whose text property is equal to the
// current topic (from the array):
let opts = options.filter(opt => topic === opt.text);
// if the opts Array has a truthy non-zero length:
if (opts.length) {
// we iterate over the returned filtered Array
// and, using Arrow function syntax, set each
// node's selected property to true:
opts.forEach(opt => opt.selected = true);
} else {
// otherwise, if the current topic returned no
// <option> elements, we find the <optgroup>
// holding the 'Crops' and append a new Child
// using Node.appendChild(), and the new Option()
// constructor to set the option-text, option-value
// default-selected property and selected property:
dropdown.querySelector('optgroup[label=Crops]')
.appendChild(new Option(topic, topic, true, true));
}
});
}
var topicArray = ['Apples', 'Tomatoes'];
populateExistingDropDowns('topicSelect', topicArray);
function populateExistingDropDowns(dd, array) {
let dropdown = document.querySelector('.' + dd),
options = Array.from(dropdown.options);
array.forEach(function(topic) {
let opts = options.filter(opt => topic === opt.text);
if (opts.length) {
opts.forEach(opt => opt.selected = true);
} else {
dropdown.querySelector('optgroup[label=Crops]')
.appendChild(new Option(topic, topic, true, true));
}
});
}
var topicArray = ['Apples', 'Tomatoes'];
populateExistingDropDowns('topicSelect', topicArray);
<select class="topicSelect" multiple>
<optgroup label="Crops">
<option value="Apiculture">Apiculture</option>
<option value="Apples">Apples</option>
<option value="Aquaculture">Aquaculture</option>
<option value="Blueberries">Blueberries</option>
</optgroup>
<optgroup label="Add Option" class="youOwn">
<option value="own">Add Your Option</option>
</optgroup>
</select>
JS Fiddle demo.
To recompose the above, using ES5:
function populateExistingDropDowns(dd, array) {
// using 'var' to declare variables:
var dropdown = document.querySelector('.' + dd),
// using Array.prototype.slice(), with
// Function.prototype.call(), to convert the collection
// of <option> element-nodes into an Array:
options = Array.prototype.slice.call(dropdown.options, 0);
array.forEach(function(topic) {
// using the anonymous functions available to the
// Array methods, rather than Arrow functions,
// but doing exactly the same as the above:
var opts = options.filter(function(opt) {
return topic === opt.text
});
if (opts.length) {
opts.forEach(function(opt) {
opt.selected = true;
});
} else {
dropdown.querySelector('optgroup[label=Crops]')
.appendChild(new Option(topic, topic, true, true));
}
});
}
var topicArray = ['Apples', 'Tomatoes'];
populateExistingDropDowns('topicSelect', topicArray);
function populateExistingDropDowns(dd, array) {
var dropdown = document.querySelector('.' + dd),
options = Array.prototype.slice.call(dropdown.options, 0);
array.forEach(function(topic) {
var opts = options.filter(function(opt) {
return topic === opt.text
});
if (opts.length) {
opts.forEach(function(opt) {
opt.selected = true;
});
} else {
dropdown.querySelector('optgroup[label=Crops]')
.appendChild(new Option(topic, topic, true, true));
}
});
}
var topicArray = ['Apples', 'Tomatoes'];
populateExistingDropDowns('topicSelect', topicArray);
<select class="topicSelect" multiple>
<optgroup label="Crops">
<option value="Apiculture">Apiculture</option>
<option value="Apples">Apples</option>
<option value="Aquaculture">Aquaculture</option>
<option value="Blueberries">Blueberries</option>
</optgroup>
<optgroup label="Add Option" class="youOwn">
<option value="own">Add Your Option</option>
</optgroup>
</select>
JS Fiddle demo.
References:
Array.from().
Array.prototype.filter().
Array.prototype.forEach().
Arrow functions.
document.querySelector().
HTMLOptionElement.
HTMLSelectElement.
let statement.
Node.appendChild().
Option() Constructor.
var statement.
Thank you all that responded to my question. I ended up using this instead:
function populateExistingDropDowns(dd, array) {
var select = document.getElementsByClassName(dd);
var opt = document.createElement('option');
for (var d = 0; d < array.length; d++) {
for (var q = 0; q < select[0].length; q++) {
if (select[0].options[q].text !== array[d]) {
opt.value = array[d];
opt.text = array[d];
select[0].children[1].appendChild(opt);
opt.selected = true;
} else {
select[0].options[q].selected = true;
}
}
}
}
Fiddle
I'm having issues with adding and removing items from my list on click. The removal function works only once.
HTML
<h1 id="show-list></h1>
<ul id="my-list>
<li data-itemname="C1">C1</li>
<li data-itemname="B23">B23</li>
<li data-itemname="D52">D54</li>
...
JS
$('#my-list').each(function() {
var $widget = $(this),
$itemname = $(this).attr('data-itemname'),
...
$widget.on('click', function() {
$currentlist = document.getElementById('show-list').innerHTML;
// create current list array
var str = $currentlist; // C1, B23, D54, etc
var array = str.split(',');
// convert item number to string
var itemtocheck = $itemname.toString(); // works OK
// check if value in array
var result = $.inArray(itemtocheck, array); // so far so good
if (result == 0) {
selecteditems = $currentlist.replace(itemtoremove+',', '');
$('#show-list').html(selecteditems); // Works only once
return false;
} else {
$('#show-list').append($itemname+','); // will add OK
return false;
}
});
...
Also I feel that this function can be simplified?
EDIT: Rewrote it
var $showList = $('#show-list');
$('#my-list').find('li').click(function () {
var $this = $(this);
var itemName = $this.data('itemname');
var showListText = $showList.text();
var showListItems = showListText.split(',');
var itemIndex = showListItems.indexOf(itemName);
if (itemIndex > -1) {
// remove item
showListItems.splice(itemIndex, 1);
} else {
// append item
showListItems.push(itemName);
}
showListText = showListItems.filter(function (a) { return !!a; }).join(',');
$showList.text(showListText);
});
jsfiddle
EDIT 3:
Just from a best practices stand point I prefix jQuery objects with $ and nothing else. I feel like it makes the code much more readable and allows you to give a variable a "type" so you always know what's what.
Is this what you are needing? I'd skip converting to an array first. Also, what's $itemname in your code?
<html>
<head>
<script>
function removeItemFromList(listName, itemName) {
var selectobject=document.getElementById(listName);
for (var i=0; i<selectobject.length; i++){
if (selectobject.options[i].value == itemName) {
selectobject.remove(i);
}
}
}
function addItemToList(listName, itemName, itemValue) {
var selectobject=document.getElementById(listName);
var found = false;
for (var i=0; i<selectobject.length; i++){
if (selectobject.options[i].value == itemValue) {
found = true;
// already in list, don't re-add
break;
}
}
if (!found) {
var option = document.createElement("option");
option.text = itemName;
option.value = itemValue;
selectobject.add(option);
}
}
</script>
</head>
<body>
<select id="show-list">
<option value="volvo">Volvo</option>
<option value="saab">Saab</option>
<option value="mercedes">Mercedes</option>
<option value="audi">Audi</option>
</select>
<br/>
<input type="button" value="remove volvo" onclick="removeItemFromList('show-list', 'volvo');" />
<input type="button" value="remove saab" onclick="removeItemFromList('show-list', 'saab');" />
<input type="button" value="add delorean" onclick="addItemToList('show-list', 'DeLorean', 'delorean');" />
</body>
</html>
I have this dropdown list with property name and id defined and I also call a function.
<select id="myid" name="myid" onClick="sortlist(this.id)">
<option value="volvo">b</option>
<option value="saab">c</option>
<option value="mercedes">a</option>
<option value="audi">d</option>
<option value="audi">s</option>
<option value="audi">f</option>
</select>
I want to sort it alphabetically when user click (or not) and for that I found this algorithm
function sortlist(selElem) {
var tmpAry = new Array();
for (var i=0;i<selElem.options.length;i++) {
tmpAry[i] = new Array();
tmpAry[i][0] = selElem.options[i].text;
tmpAry[i][1] = selElem.options[i].value;
}
tmpAry.sort();
while (selElem.options.length > 0) {
selElem.options[0] = null;
}
for (var i=0;i<tmpAry.length;i++) {
var op = new Option(tmpAry[i][0], tmpAry[i][1]);
selElem.options[i] = op;
}
return;
}
I pass the element id to function because I want to use the same function to other dropdownlists, but that isn't working.
Can you please open my eyes for what am I doing wrong?
Check jsfiddle here: http://jsfiddle.net/u5YZp/
this is how you have to do it. JSFiddle.
You need to pass elem, not id, and your function should be global
<select id="myid" name="myid" onClick="sortlist(this)">
Try this
HTML
<select id="myid" name="myid" >
<option value="volvo">Volvo</option>
<option value="saab">Saab</option>
<option value="mercedes">Mercedes</option>
<option value="audi">Audi</option>
</select>
Script
var mylist = $('#myid');
var listitems = mylist.children('option').get();
listitems.sort(function(a, b) {
var compA = $(a).text().toUpperCase();
var compB = $(b).text().toUpperCase();
return (compA < compB) ? -1 : (compA > compB) ? 1 : 0;
})
$.each(listitems, function(idx, itm) { mylist.append(itm); });
DEMO
Here's a way to do it in plain JavaScript:
Demo: http://jsfiddle.net/u5YZp/4/
var select = document.getElementById('myid');
var sortSelect = function(select) {
var toArray = function(x) {
return [].slice.call(x);
};
var options = toArray(select.children);
var sorted = options.sort(function(a, b) {
return a.value > b.value;
});
sorted.forEach(function(op) {
select.appendChild(op);
});
sorted[0].selected = true;
};
sortSelect(select);
I need to create input fields on the basis of which number was chosen from select menu,
like this code:
<select id="inputs" style="width:60px;">
<option>1</option>
<option>2</option>
<option>3</option>
<option>4</option>
<option>5</option>
<option>6</option>
<option>7</option>
<option>8</option>
<option>9</option>
<option>10</option>
</select>
When we select 10, input fields will increase to 10 at the same time, When I select 2, it doesn't decrease from 10 to 2 :(
I think the best way might be to use replace() with a loop; unfotunately I couldn't get a solution.
$(document).ready(function() {
var scntDiv = $('#add_words');
var wordscount = 0;
var i = $('.line').size() + 1;
$('#inputs').change(function() {
var inputFields = parseInt($('#inputs').val());
for (var n = i; n < inputFields; ++ n){
wordscount++;
$('<div class="line">Word is ' + wordscount + '<input type="text" value="' + wordscount + '" /><a class="remScnt" href="#">Remove</a></div>').appendTo(scntDiv);
i++;
}
return false;
});
// Remove button
$('#add_words').on('click', '.remScnt', function() {
if (i > 1) {
$(this).parent().remove();
i--;
}
return false;
});
});
Could you help me please?
Try
$(function(){
$('#inputs').change(function(){
for(i=0; i < $("select option:selected").text; i++)
{
$('#divIdHere').append('<input blah blah />');
}
})
});
obviously change to suit :)
I realise that you already accepted an answer for this question, but I wasn't content to just leave the question as-is. Also: I was a little bored. Make of that what you will...
So! Here's my (belated) answer.
The benefits of my approach, or the reasoning behind it, are:
You can use the select to remove, and add, rows.
When removing rows using the select to remove rows it first removes those lines with empty inputs, and then removes whatever number of filled in input-containing rows from the end.
It allows you to use the .remScnt links as well.
Hopefully this is of some, even if only academic, use or interest to you:
function makeRow() {
var div = document.createElement('div'),
input = document.createElement('input'),
a = document.createElement('a');
t = document.createTextNode('remove');
div.className = 'line';
input.type = 'text';
a.href = '#';
a.className = 'remScnt';
a.appendChild(t);
div.appendChild(input);
div.insertBefore(a, input.nextSibling);
return div;
}
$('#inputs').change(
function() {
var num = $(this).val(),
cur = $('div.line input:text'),
curL = cur.length;
if (!curL) {
for (var i = 1; i <= num; i++) {
$(makeRow()).appendTo($('body'));
}
}
else if (num < curL) {
var filled = cur.filter(
function() {
return $(this).val().length
}),
empties = curL - filled.length,
dA = curL - num;
if (empties >= num) {
cur.filter(
function() {
return !$(this).val().length;
}).parent().slice(-num).remove();
}
else if (empties < num) {
var remainder = num - empties;
cur.filter(
function() {
return !$(this).val().length;
}).parent().slice(-num).remove();
$('div.line').slice(-remainder).remove();
}
}
else {
var diff = num - curL;
for (var i = 0; i < diff; i++) {
$(makeRow()).appendTo($('body'));
}
}
});
$('body').on('click', '.line a.remScnt', function() {
console.log($(this));
$(this).parent().remove();
});
JS Fiddle demo.
Please note that I've made little, or (more precisely) no, attempt to ensure cross-browser usability with this. The native DOM methods used in the makeRow() function are used for (minor optimisations of increasing the) speed, using jQuery (with its cross-browser-abstractions might make things even more reliable. And is worth considering.
References:
Native vanilla JavaScript:
node.appendChild().
document.createElement().
document.createTextNode().
element.className().
node.insertBefore().
jQuery stuff:
appendTo().
change().
filter().
parent().
slice().
:text selector.
val().
okay change it a little to allow for a new list to be created.
$(function(){
$('#inputs').change(function(){
$('#divIdHere').empty()
for(i=0; i < $("select option:selected").text; i++)
{
$('#divIdHere').append('<input blah blah />');
}
})
});
that will basically empty out the contents of the div before adding them all back in again :)
you need to make you DIV before use append
just try this html
<select id="inputs" style="width:60px;">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
<option value="6">6</option>
<option value="7">7</option>
<option value="8">8</option>
<option value="9">9</option>
<option value="10">10</option>
</select>
<div id="add_words"></div>
and Jquery with this importand line scntDiv.empty();
JQuery
$(document).ready(function() {
var scntDiv = $('#add_words');
var wordscount = 1;
var i = $('.line').size() + 1;
$('#inputs').change(function() {
var inputFields = parseInt($('#inputs').val());
scntDiv.empty()
for (var i = 0; i < inputFields; i++){
scntDiv.append($('<div class="line">Word is ' + wordscount + '<input type="text" value="' + wordscount + '" />'));
}
});
});
You could only add new lines to make up the number of lines when the select's value increases and only remove the 'extra' lines when it decreases.
$( document ).ready(
function() {
var divs = $( 'div#add_words' );
$( '#inputs' ).change(
function(evt) {
var n = $( this ).val();
var lines = $( 'div.line' );
var numlines = lines.size();
if( n > numlines ) {
// We want more line. Add some.
while( n > numlines ) {
numlines += 1;
divs.append( '<div class="line">Line ' + numlines + '</div>' );
}
}
else {
// Remove everything after the n'th line.
lines.slice( n ).remove();
}
} )
.change();
} );