word dropdownnssss

by lovromar

HTML

<p id="the-text">This is an example paragraph containing many <select class="selector"><option>selections</option><option>dropdown thingies</option><option>option choosers</option></select> that I would like to be able to <select class="selector"><option>click on</option><option>select</option><option>choose</option></select> and then know what the <select class="selector"><option>final</option><option>selected</option><option>variable</option></select> paragraph text is. <select class="selector"><option>It would be great</option><option>It would be nice</option><option>It'd be delightful</option></select> , and <select class="selector"><option>useful</option><option> helpful</option><option>interesting</option></select> to dynamically create paragraphs like this.</p>

	<textarea id="text-area" rows="4" cols="60">
	This is where the text should appear... 
	</textarea>

JavaScript

function updateTextArea() {
    		//get all of the text selections, and put them in an array
	  	var foo = []; 
		$('.selector :selected').each(function(i, selected){ 
		  foo[i] = $(selected).text(); 
		});
		
		//get the paragraph content, and store it
		var safe_content = $('#the-text').html();
		
		//delete all the options
		$('.selector').text('');
		
		//get the text without the dropdown options
		var content = $('#the-text').html();
		
		//create a regex expression to detect the remaining drop-down code
		var pattern = "<select class=\"selector\"></select>",
		    re = new RegExp(pattern, "g");
		
		//replace all the drop-down selections with {
		content = content.replace(re,"{");
		
		//turn the content into an array
		content_array = content.split(" ");
		
		//go through the array, and if a element is {, go to "foo" and replace it with the selected option
		var length = content_array.length,
		    element = null;
		var j = 0;
		for (var i = 0; i < length; i++) {
		  element = content_array[i];
		
		  	if(element == "{") {
			content_array[i] = foo[j];
			j++;
			}
		
		}
		
		//turn the array back into a paragraph
		new_content = content_array.join(" ");
		
		//replace the text with the origionanl text
		$('#the-text').html(safe_content);
		
		//put the new content into the text area
		$('#text-area').val(new_content);
}

$( document ).ready(function() {
    updateTextArea();
	});

$( document ).on("change",".selector",function() {
  updateTextArea();
});