1

I have these data fetched from an API call: enter image description here

I want to show these data to select option elements so I have this line of codes in my AJAX script file:

$.each($(value.routes), function(index, route){
     $('.searchable-select').append('\
     <option value="'+route+'"> From: '+route+'</option>\
     ');
});

How can I set the option value as 1 and 2 and the string ("From:...") as the text from this object?

7
  • add sample array Commented Aug 15, 2017 at 7:30
  • the sample array is on the picture.. Commented Aug 15, 2017 at 7:31
  • That's not an array but an object with numeric keys hence the first parameter of the callback should be named "key" or "property" because it's not an index. Then just use the key/property instead of route for the value Commented Aug 15, 2017 at 7:33
  • My bad.. my question is updated Commented Aug 15, 2017 at 7:39
  • You want to iterate the routes and pass the data to the <option value="${index}">${valueString}</option> and append it on the <select> right? Commented Aug 15, 2017 at 7:46

2 Answers 2

1

If you want to iterate the routes object, you can use the $.each of jquery.

Codes look like this.

var routes = {
	1: "From Davao Del Sur (Phillipines) ...",
	2: "From Soccsksargen (Phillipines)"
}

var select = '<select>';
$.each(routes, function(index, route) {
	select += '<option value="'+ index +'">'+ route +'</option>';
})
select += '</select>';

$('#demo').html(select);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="demo"></div>

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

Comments

0

If I understand you correct, you want to do String splitting:

var route = "From: Davao Del Sur (Phillipines) - To: Soccsksargen (Phillipines)";
var from = route.split("From: ")[1].split(" - ")[0];

console.log(from);

// How it works:
// Split String into array by using "From: " as seperator:
var array1 = route.split("From: ");
console.log(array1);
// take second element from array
console.log(array1[1]);
// split the element into another array using " - " as seperator:
var array2 = array1[1].split(" - ");
console.log(array2);
// take first element from array
console.log(array2[0]);

// done

1 Comment

Sorry but I don't want to split the string. The string value "From: Davao Del Sur (Phillipines) - To: Soccsksargen (Phillipines)" has to be put as text inside option element and the numbers 1 and 2 as its values.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.