user3033194
user3033194

Reputation: 1821

Read comma-separated values in HTML form

I have a simple HTML input element:

<input type="text" class="form-control" name="value">

This field could have comma-separated values e.g. ABC, DEF, GHI. The field value when submitted must be exactly the same as when entered. However, when I am printing the field value to the console, I am getting

ABC%2C+DEF%2C+GHI.

I want ABC, DEF, GHI

I tried things like decodeURIComponent and accept-charset="ISO-8859-1" for the form, but they don't work. How can I prevent the encoding of the commas and spaces? Thanks in advance!

Upvotes: 1

Views: 3868

Answers (2)

inubs
inubs

Reputation: 519

Before submiting, encode the value and it should work, according to my test

<form id="myForm" action="form.php" method="GET">
    <input id="encodeMe" name="string" value="this will be encoded correctly" />
    <input type="submit" value="OK" />
</form>

$('#myForm').submit(function() {
    var enc = escape($("#encodeMe").val());
    $("#encodeMe").val(enc);
});

Upvotes: 1

user3033194
user3033194

Reputation: 1821

Ok, I got it. In JavaScript, the input field has to be handled thus:

decodeURIComponent(str.replace(/\+/g,' '))

where str = ABC%2C+DEF%2C+GHI. Only decodeURIComponent is not enough. Hope it helps!

Upvotes: 0

Related Questions