skip to Main Content

I have the following data I’m receiving from the service. The following console logs prints the following in browser:

console.log("Inside data");
console.log(data);

Inside data 
[[id=1, name=BOTTLE-1], [id=2, name=BOTTLE-2], [id=4, name=BOTTLE-3]]

If I want to build a options tag using jQuery, is it easy to extract the id as 1,3 and 4 and name for the value parameter of options tag and build a select dropdown?

For example, if I’ve the following code and if I want to work it like it is showing now.

var data = "[[id=1, name=BOTTLE-1], [id=2, name=BOTTLE-2], [id=4, name=BOTTLE-3]]";
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select name="cars" id="cars">
<option  value="-">"Please Select"</option>
<option id = "1" value="BOTTLE-1">BOTTLE-1</option>
  <option id = "3" value="BOTTLE-2">BOTTLE-2</option>
  <option id="4" value="BOTTLE-3">BOTTLE-3</option>
</select>

Building part using append method should be easy but I am wondering if it’s easy to extract the required values

2

Answers


  1. Here is my solution:

    let data = "[[id=1, name=BOTTLE-1], [id=2, name=BOTTLE-2], [id=4, name=BOTTLE-3]]";
    
    let codingRegex = /id=d+, name=BOTTLE-d+/g;
    let matches = data.match(codingRegex);
    let cars = $("#cars");
    matches.forEach(match => {
      let temp = match.split(", ");
      let id = temp[0].replace("id=", ""),
        name = temp[1].replace("name=", "");
      let option = new Option();
      option.text = name;
      option.value = id;
      cars.append(option);
    });
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <select name="cars" id="cars">
      <option value="-">"Please Select"</option>
    </select>
    Login or Signup to reply.
  2. let data = "[[id=1, name=BOTTLE-1], [id=2, name=BOTTLE-2], [id=4, name=BOTTLE-3]]";
    let label = "BOTTLE";
    let regExString="id=\d+, name="+label+"-\d+";
    let regExp=new RegExp(regExString,"ig");
    let matches = data.match(regExp);
    let cars = $("#cars");
    matches.forEach(match => {
      let temp = match.split(", ");
      let id = temp[0].replace("id=", ""),
        name = temp[1].replace("name=", "");
      let option = new Option();
      option.text = name;
      option.value = id;
      cars.append(option);
    });
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <select name="cars" id="cars">
      <option value="-">"Please Select"</option>
    </select>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search