MSFT138
MSFT138

Reputation: 11

Javascript, parsing multiple values in a variable

I have a working html form (in laravel) that is using a javascript call to employe Ajax.

Right now I'm using console log to make sure my click event shows the variables which it does.

However, because of how my values are below, I get multiple values in one variable and I'm wondering if there's a way to parse them into their own.

For example, in my form I have multiple values sharing table cells:

<form id="saveLineup">
@foreach($lists as $list)

  <tr style="text-align:center;">
      <td id="groupNumber">{{$list['product']}} - {{$list['product_NAME']}}</td>
      <td id="detailColor">{{$list['detail']}}/{{$list['COLOR']}} - {{$list['description']}}</td>
      <td id="category">{{$list['CATEGORY']}}</td>
      <td><input id="addToLineup"> type="checkbox" <?php if ($list['LINE_UP'] == 1) echo "checked='checked'"; ?>></td>
  </tr>  

@endforeach
</form>

But when I log my variables I get

category: "categoryOne" //which is correct
detailColor: "123/Blue - Description"
productNumber: 123 - productOne

What I'd like to do is parse those and have it all as separate values like so:

category:"categoryOne"
detail: "123"
color: "Blue"
productNumber: "123"
productDescription: "productOne"

Is there a way to do that within my JS?

$("#addToLineup").click(function (e) {

  var productNumber = document.getElementById("productNumber").innerHTML = productNumber;
  var detailColor = document.getElementById("detailColor").innerHTML = detailColor;
  var category = document.getElementById("category").innerHTML = category;

  updatedata.productNumber = productNumber;
  updatedata.detailColor = detailColor;
  updatedata.category = category;

  $.ajax({
    url: "/test/addToLineup",
    data: updatedata,
    _token: phpVariables.csrfToken,
    type: "POST",
    beforeSend: function () {
      showLoading(element);
    },
    success: function (data) {
      location.reload();
    },
  });
});

Upvotes: 0

Views: 686

Answers (1)

Pluda
Pluda

Reputation: 1477

I believe the simplest way is splitting your variables like this:

var detailColor = "123/Blue - Description";
var productNumber = "123 - productOne";

var first = detailColor.split(' - ');
var just_color = first[0].split('\/');
var detail = just_color[0];
var color = just_color[1];

var second = productNumber.split(' - ');
var product_number = second[0];
var product_description = second[1];

console.log(detail , color, product_number, product_description);

Upvotes: 1

Related Questions