Gabriel Nessi
Gabriel Nessi

Reputation: 325

Split string when comma is inserted and add it to a string array

I have an input that converts strings into 'styled tags' when the user types a comma, then, when the form is submitted, the strings are pushed into an array called 'content'.

On the EJS views, I am printing the result like <%= course.content %> but the result I am getting is 'string1,string2,string3,string4' and what I am after is that when is pushed into the array, each string must be a different element:

content ['string1','string2','string3','string4']

only then it will render properly in my views by looping the array. I want to achieve this by javaScript or jQuery only, please.

UPDATE: this is how I am rendering in my view

<ul>
   <% var i; for (i = 0; i < course.content.length; i++) { %>
     <li><i class="fas fa-check"></i> <%= course.content %></li>
   <% }; %>
</ul>

UPDATE: this is my route where this POST request is being done

router.post("/", middleware.isLoggedIn, function(req, res) {
  Course.create(req.body.course, function(err, course) {
     if (err) {
       req.flash("error", err.message);
       return res.redirect("back");
     }
       res.redirect("/courses/" + course.id);
  });
});

SOLVED! by using split on the server side like this:

router.post("/", middleware.isLoggedIn, function(req, res) {
   Course.create(req.body.course, function(err, course) {
     if (err) {
       req.flash("error", err.message);
       return res.redirect("back");
     } else {
       var content = req.body.course.content.toString().split(",");
       course.content = content;
       course.save();
       console.log(course.content);
       res.redirect("/courses/" + course.id);
     }
   });
});

Here is another solution in javaScript using function beforesubmit() by @garry man see below.

codepen

Upvotes: 0

Views: 265

Answers (2)

shyammakwana.me
shyammakwana.me

Reputation: 5752

Long way

Otherwise there's one work around is as many tags you enter, that much input elements you should generate.

For e.g. my input tags are foo,bar then 2 input tags will be generated like

                                                            Note square brackets below
<input id="hiddenInput" type="hidden" name="course[content][]" required>
<input id="hiddenInput" type="hidden" name="course[content][]" required>

This is long way.

Another way

If you submit form via AJAX, then you can manipulate data before submitting and convert string into array with the use of .split(',').

Another way (Server side)

Split string by , on server side.

Upvotes: 1

garry man
garry man

Reputation: 465

Okay so the problem is that you are submitting a form containing a single input which can only contain string values.

HTML Form practice is to have a single input for each array element to be posted, like:

<input name="course[content]"/> //value 1
<input name="course[content]"/> //value 2
<input name="course[content]"/> //value 3

So, in order to achieve that, before submit, you can call this function that generates those elements for you:

function beforesubmit(){
  let submitVal = document.getElementById('hiddenInput');
  let values  = submitVal.value.split(',');

  //let's get the container of the params passed to post
  let paramsContainer = submitVal.parentElement;
  // remove the param containting the string with commas as we're generating new ones
  paramsContainer.removeChild(submitVal); 

  for(let i =0; i<values.length;i++){
    //for each value, add a submit param containing each value
    let tmp = document.createElement('input');
    tmp.setAttribute('type','hidden');
    tmp.setAttribute('name','course[content]');
    tmp.setAttribute('value',values[i]);
    paramsContainer.appendChild(tmp);
  }
  document.getElementsByTagName('form')[0].submit();
}

in order to call this function, replace your submit input with this:

<input type="button" value="submit" onclick="beforesubmit()">

Using this code you can already see the POST request difference between before and after. In your codepen it sends a single parameter, while with this snippet of code you are going to send an array of course['content'].

Now it's all up to how you are going retrieve data server side, you should be retrieving the course['content'] param as an array.

Upvotes: 1

Related Questions