List / output comma-separated values from single input - javascript

How would I go about outputting a list (whether as individual values or as an array) from a comma-separated value in a single input field?
Example
User enters the following into a text input field: Steve, Bruce, Matt, Natasha, Peter
Result:
Steve
Bruce
Matt
Natasha
Peter

Just split the input on comma, and generate the list
var input = "Steve, Bruce, Matt, Natasha, Peter",
ul = $('<ul />');
input.split(',').forEach(function(item) {
ul.append(
$('<li />', { text : item })
)
});
$('body').append(ul);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

hope it helps you:
var myArray = $('input').val().split(',');
Using jQuery

Since you put jquery in your tags i guess you want a jQuery solution.
First of all you would want to split the values, and after that create a list (ul or ol) and add list elements (li)
$(function() {
$("#valuesForm").submit(function(e) {
e.preventDefault();
var values = $("#textfieldId").val().split(",");
if (values) {
for (var i in values) {
var value = values[i].trim(),
$valueList = $("#valueList"),
$valueItem = $("<li />");
$valueItem.text(value);
$valueList.append($valueItem);
}
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<form id="valuesForm">
<input type="text" id="textfieldId">
<input type="submit" value="Split!">
</form>
<ul id="valueList">
</ul>

There are several options.
1 Splitting
var aux = "Steve, Bruce, Matt, Natasha, Peter";
aux = aux.split(',');
This one gives you the names within an array but with the space after the comma.
2 White Space Removal
var aux = "Steve, Bruce, Matt, Natasha, Peter";
aux = aux.split(', ');
This one does resolve the white-space after the comma.
3 Alternative
var aux = "Steve, Bruce, Matt, Natasha, Peter";
aux = aux.split(',');
aux = jQuery.map( aux, function( n, i ) {
return n.trim();
});
This last one is more flexible and i'm showing it just to give an example.

Related

jQuery search for individual words not string of words

Question:
I have a jQuery search function however it searches for words together not individually. e.g. "ASUS B350" not "ASUS" and "B350" this can be seen when searching for Asus STRIX B350-F GAMING, "ASUS B350" produces no result but "ASUS" and "B350" would.
Code:
$("#mySearch").on("keyup", function() {
var value = $(this).val().toLowerCase();
$("#myTable tr:not(.discarded) td:nth-child(1)").filter(function() {
$(this).parent().toggle($(this).text().toLowerCase().indexOf(value) > -1)
});
});
Expected Result:
I also want if the string is encased in "" it searches for those words in order.
If you need any more details please let me know
Thanks
You can split the words at every space and check if those individual words exist in the text using every:
Now if you search for "Asus strix" in the below snippet, both ASUS results will be shown
$("#mySearch").on("keyup", function() {
var value = $(this).val().toLowerCase();
$("#myTable tr:not(.discarded) td:nth-child(1)").filter(function() {
let toggle = value.split(" ").every(i => !i || $(this).text().toLowerCase().indexOf(i) > -1);
$(this).parent().toggle(toggle);
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" id="mySearch" />
<table id="myTable">
<tr><td>Asus STRIX B350-F GAMING</td></tr>
<tr><td>Asus ROG Strix SCAR II Gaming</td></tr>
<tr><td>Dell G7 15 Gaming Laptop</td></tr>
</table>
You could use a regexp pattern to find out if individual words are occurring in the string:
$("#mySearch").on("keyup", function() {
var value = $(this).val().toLowerCase();
if(!(value.startsWith('"')&&value.endsWith('"'))){
value=value.replace(" ", "|");
value= value.trim();
}else {
value=value.replace("\"", "");
}
$("#myTable tr:not(.discarded) td:nth-child(1)").filter(function() {
$(this).parent().toggle($(this).text().toLowerCase().match(value));
});
});

Type to search from input box

I have a form where a user can choose their Occupation. The list of occupations are in a seperate .js file like so:
var occupationSelect = "<select id='occupationSelect' onchange='selectChange()' ><option value=''></option><option value='v10173' >AA Patrolman</option><option value='v10174' >Abattoir Inspector</option>
Now in my form I want the input box (as the occupation list is very long) , for the user to type A, B etc and then the relevant occupations come up. Something like the following jsfiddle
Similar JS Fiddle
This fiddle is fine if I put all the Occupations into an array.
However the options in my .js file have values attached for use later in the web application (eg. option value='v10173')
What is the best option to get the Occupation by typing but also to make sure the value is attached.
Edited the js fiddle:
<input name="car" list="anrede" />
<input name="car-val" hidden />
<ul id="anrede"></ul>
var mycars2 = [
['Herr', 'herr'],
['thomas', 'v2345'],
];
var list = $('#anrede');
listHtml = '';
mycars2.forEach(function(item){
var option = '<li data-val="' + item[1] + '">' + item[0] + '</li>';
listHtml += option;
});
list.html(listHtml);
$('#anrede li').on('click', function(){
$('input[name="car"]').val($(this).html());
$('input[name="car-val"]').val($(this).attr('data-val'));
});
This needs jquery, and the names/values are stored in pairs inside the list.
A hidden input is used for the value.
I would suggest using data-value attribute for the "value" of selected item and array of objects, like so:
var mycars = [
{
title: 'Herr',
value: 'Herr Value'
},
{
title: 'Frau',
value: 'Frau Value'
}
];
var list = document.getElementById('anrede');
var input = document.getElementById('carList');
mycars.forEach(function(item) {
var option = document.createElement('option');
option.value = item.title;
option.dataset.value = item.value;
list.appendChild(option);
});
input.onchange = function() {
alert(document.querySelector('option[value="' + this.value + '"]').dataset.value)
}
here is the jsfiddle - https://jsfiddle.net/0jvt05L0/302/

Search function filter li's in pure Js

I'm trying to make an input that filters a <ul> based on the value in pure JavaScript. It should filter dynamically with the onkeyup by getting the li's and comparing their inner element name with the filter text.
Here is my function:
var searchFunction = function searchFeature (searchString) {
console.log("Is my search feature working?");
//Get the value entered in the search box
var inputString = document.getElementById('inputSearch');
var stringValue = inputString.value;
//Onkeyup we want to filter the content by the string entered in the search box
stringValue.onkeyup = function () {
//toUpperCase to make it case insensitive
var filter = stringValue.toUpperCase();
//loop through all the lis
for (var i = 0; i < eachStudent.length; i++) {
//Do this for all the elements (h3, email, joined-details, date)
var name = eachStudent[i].getElementsByClassName('student-details')[1].innerHTML;
//display all the results where indexOf() returns 0
if (name.toUpperCase().indexOf(filter) == 0)
eachStudent[i].style.display = 'list-item';
else
eachStudent[i].style.display = 'none';
}
}}
My HTML for the search bar:
<div class="student-search">
<input id="inputSearch" placeholder="Type name here.." type="text"> <button>Search</button></div>
My HTML for one of the li's:
<ul class="student-list">
<li class="student-item cf">
<div class="student-details">
<img class="avatar" src="#">
<h3>John Doe</h3>
<span class="email">John.Doe#example.com</span>
</div>
<div class="joined-details">
<span class="date">Joined 01/01/14</span>
</div>
</li>
I would like to filter all the elements (name, email, joined date) based on the value of the input.
Unfortunately, I don't get any errors and it's simply not working.
The function is correctly invoked because the console.log prints...
Here goes the codepen: http://codepen.io/Delano83/pen/qaxxjA?editors=1010
Any help or comments on my code is very appreciated.
There were several issues:
stringValue.onkeyup - stringValue is the value. You can't onkeyup it.
var eachStudent = document.querySelector(".student-item"); will fetch the first thing with student-item class. You need to use querySelectorAll or just use jquery's $('.find-item').
if (name.toUpperCase().indexOf(filter) == 0) indexOf returns 0 if the filter is found at the beginning of the name. 0 as match if found at index 0. You need to check against -1, which means it was not found at all.
Otherwise it more or less worked, good job.
I also added Jquery for me to fix it faster. If you insist on using pure javascript I am sure you will be able to edit it.
Check it out here: http://codepen.io/anon/pen/WGrrXW?editors=1010. Here is the resulting code:
var page = document.querySelector(".page");
var pageHeader = document.querySelector(".page-header");
var studentList = document.querySelector(".student-list");
var eachStudent = document.querySelectorAll(".student-item");
var studentDetails = document.querySelector(".student-details");
//Recreate Search Element in Js
var searchBar = function createBar(searchString) {
var studentSearch = document.createElement("div");
var input = document.createElement("input");
var searchButton = document.createElement("button");
input.type = "text";
var txtNode = document.createTextNode("Search");
if (typeof txtNode == "object") {
searchButton.appendChild(txtNode);
}
studentSearch.setAttribute("class", "student-search");
input.setAttribute("id", "inputSearch");
//append these elements to the page
studentSearch.appendChild(input);
studentSearch.appendChild(searchButton);
input.placeholder = "Type name here..";
return studentSearch;
}
var searchFunction = function searchFeature(searchString) {
console.log("Is my search feature working?");
//Get the value entered in the search box
var inputString = document.getElementById('inputSearch');
var stringValue = inputString.value;
//Onkeyup we want to filter the content by the string entered in the search box
inputString.onkeyup = function() {
//toUpperCase to make it case insensitive
var filter = $(this).val().toUpperCase()
//loop through all the lis
for (var i = 0; i < eachStudent.length; i++) {
//Do this for all the elements (h3, email, joined-details, date)
var name = $(eachStudent[i]).find('h3').text()
console.log(name, filter, name.toUpperCase().indexOf(filter))
//display all the results where indexOf() does not return -1
if (name.toUpperCase().indexOf(filter) != -1)
eachStudent[i].style.display = 'list-item';
else
eachStudent[i].style.display = 'none';
}
}
}
function addElements() {
console.log('Add search bar, trying to anyway...')
pageHeader.appendChild(searchBar());
// page.appendChild(paginationFilter());
onLoad();
}
window.onload = addElements;
window.onLoad = searchFunction;

Changing input field value while writing

Let's say I have a input field
<input type="text" class="form-control" name="filename">
and do write something like this:
Hällo
Is it possible to check while writing if that field has a the letter ä and change it to an a while writing ?
So far, I built this:
$search = array('ä', 'Ä');
$replace = array('ae', 'Ae');
$project = str_replace($search, $replace, $input);
You don't do this with PHP, you would do it with Javascript:
var el = document.getElementById("filename");
el.addEventListener('keyup', function(){
var replace = ['ä','å'];
var replacewith = 'a';
var replace1 = ['ö'];
var replacewith1 = 'o';
replace.forEach(function(letter){
el.value = el.value.replace(letter, replacewith);
});
replace1.forEach(function(letter){
el.value = el.value.replace(letter, replacewith1);
});
});
Add id="filename" to the input element for this to work. You can add as many letters to the replace array as you would like.
You can also add more arrays to replace letters.
https://jsfiddle.net/dek5as1x/1
Edit: Solution for several letters
var el = document.getElementById("filename");
el.addEventListener('keyup', function(){
var replaces = [['ä','å'],['ö','ø'],['ï','ì'],['ü','ù','û'],['ë','ê']];
var replacewith = ['a','o','i','u','e'];
replaces.forEach(function(letterGroup, index){
letterGroup.forEach(function(letter){
el.value = el.value.replace(letter, replacewith[index]);
});
});
});
Here you add a new array ([]) to replaces. Then you add all the letters to that array that should be turned into the same letter to that array. Example: ['ê','ë','è']. Then you add the letter to the replacewith array. It is important that the letter comes to replace the letters in the array has the same index as the corresponding array in replaces.
This solution should be a little cleaner for when you have lots of letters to replace.
You can't do this using PHP because PHP is serverside.
But you can do this using JavaScript.
Try:
<script language="JavaScript">
function replace() {
var input = document.getElementById("filename");
input.value = input.value.replace("ä","a");
}
<script>
<input type="text" class="form-control" name="filename" onchange="replace()">

How to get value of an HTML element nested inside other HTML elemnts?

I have HTML elements as shown below
<div id="container">
<div>
<span>
<input type="text" id="item1" value="AA"/>
</span>
</div>
<div>
<span>
<input type="text" id="item2" value="BB"/>
</span>
</div>
<div>
<span>
<input type="text" id="item3" value="CC"/>
</span>
</div>
</div>
I need to extract array of values like [AA,BB,CC] and IDs like [1,2,3] -from item1,item2,item3 using JavaScript and Jquery .How to do the same?
Try
var idarray = [];
var valuearray = [];
$("#container input").each(function(){
var $this = $(this);
idarray.push($this.attr("id").substring(4));
valuearray.push($this.val());
});
console.log(idarray);
console.log(valuearray);
Demo: Fiddle
var arr = $('#container').find('input').map(function(){
return $(this).val();
}).get();
var ids = $('#container').find('input').map(function(){
return $(this).attr('id').replace('item','');
}).get();
http://jsfiddle.net/mohammadAdil/Qhm5J/1/
var ids = $("input[id^='item']").map(function(i,e){
return e.id;
});
var values = $("input[id^='item']").map(function(i,e){
return $(e).val();
});
console.log(ids);
console.log(values);
Working Example: http://jsfiddle.net/RLsCX/
Please refer
http://jsfiddle.net/2dJAN/8/
var ids = []
var values = []
$('#container input[type=text]').each(function() {
ids.push($(this).attr('id'));
values.push($(this).val())
})
alert(ids)
alert(values)
var arrId = [], arrVal = [];
$("input[type='text']").each(function(){//find input text
if(this.id && this.id.indexOf("item")===0){//check id starts with item
arrId.push(this.id.replace("item",""));//push id
arrVal.push(this.value);//push value
}
});
http://jsfiddle.net/jGNy7/
Try this:
$(document).ready(function() {
var valuesArray = []
, idsArray = [];
$('#container').children().each(function() {
valuesArray.push($(this).children().children().val());
idsArray.push($(this).children().children().prop('id').substr(4));
});
alert(valuesArray);
alert(idsArray);
});
Try this:
var vals = [];
var ids = [];
$("#container input").each(function(){
vals.push($(this).val());
ids.push($(this).attr("id").replace("item", ""));
});
Here is the jsfiddle:
Loop the inputs, pull the values, parse the item value. Something like this:
var ids = [];
var values = [];
$("input").each(function(){
var input = $(this);
var value = input.val();
var id = input.attr("id").replace("item", "");
ids.push(id);
values.push(value);
});
Here is a working example (warning: two alert popups)
Notice the the input value is obtained using input.val(), this will ensure that the value retrieved is the current value as entered by the user. If you wanted the attribute value (which will not be changed simply by the user typing something else) you could use input.attr("value") instead
If you have other input elements on the page that you do not want to include then you need to be more specific with you selector. For example, if all the desired input elements are with the id="container" element, then you can use this instead:
$("#container input").each(...

Categories