0

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
1

4 Answers 4

1

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>

Sign up to request clarification or add additional context in comments.

Comments

0

hope it helps you:

var myArray = $('input').val().split(',');

Using jQuery

Comments

0

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>

Comments

0

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.