Pavan Pavan - 1 year ago 143
Javascript Question

How to Iterate the String in JavaScript?

I got the JsonObject and It contains the html content as a value of one key to my javascript from java code.

Now I want to parse the String using the option, value, label and create a select field using the string.

I thought of using replace method which is not effective and not working in all the cases.So, I decided to use a loop.

HTML returned as a String from Java Code :


What I tried is :

$.each(html,function(value, label){
$('#state').append('<option value='+value+'>" '+ label +'</option');

Not sure how does it work and what needs to improve !!!

Answer Source

If you always get a standard format like the sample you provided you can still parse it and populate your select this way

var html = "<option><value>com.taleo.systemcomponent.olf.entity.NetworkLocation__10053</value><label>Badghis</label></option>`<option><value>com.taleo.systemcomponent.olf.entity.NetworkLocation__10054</value><label>Baghlan</label></option>";

	var value = $(item).find('value').text();
	var label = $(item).find('label').text();
        $('#state').append('<option value='+value+'>'+ label +'</option');
<script src=""></script>
<select id="state"></select>

First, you need to wrap your html inside another container so you can access it, in this case, added inside a div.

Then you loop through all the options inside your html, for each option, you extract the text of the value and the label, create an option tag and append it to your select

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download