Form calculator using Each() and Children() in jQuery - javascript

Im trying to build a form that calculates a total price based on a series of drop down boxes with string values such as "This option costs £30" i know this is not ideal but im putting this together as a hack for an existing script
For the most part ive got it working however im not sure how to run the each function for each child of #productconfig
I can manually input each of the drop downs ids into an array and that makes the calculation but it would be good if it just worked with all the children of #productconfig
<code>
<div id="#productconfig">
<label>Model Type</label>
<select name="products[220][data][modeltype]" id="data-modeltype-220">
<option value="M-Type £500">M-Type £500</option>
<option value="P-Type £500">P-Type £500</option>
<option value="S-Type £500">S-Type £500</option>
</select>
</div>
</code>
<code>
$(document).ready(function() {
$("#productconfig").children().change(function () {
calculateoptions();
});
calculateoptions();
});
</code>
<code>
function calculateoptions() {
var arr = ["data-modeltype-220"];
var total = 0;
jQuery.each(arr, function () {
var str = $('#' + this).attr("value");
var poundsign = str.indexOf('£');
var poundsign = poundsign + 1;
var lengthofstr = str.length;
var shortstr = str.substr(poundsign, lengthofstr);
total = eval(total) + eval(shortstr);
});
$('#price').html("£" + total);
}
</code>

How about this:
function calculateoptions() {
var total = 0;
jQuery('#productconfig select').each(function () {
total += $(this).val().match(/£(\d+)/)[1];
});
$('#price').html("£" + total);
}

You can use:
$("#productconfig select").each(function(){...});
To select each drop down in the product config div.

Related

Change <select> options with javascript dynamically

Can I use a javascript if/else function to change the select options of a form? I don't want to use CSS to hide/display different dropdown menus, so here is what I've ccome up with:
function getType() {
var x = document.getElementById("food").value;
var items;
if (x === "fruit") {
items = "Apple" || items = "Oranges" || items = "Bananas";
else {
items = "Eggplants" || items = "Olives"
}
document.getElementById("pickone").value;
}
<input type="text" id="food">
<select id="pickone">
<option id="1"></option>
<option id="2"></option>
</select>
I can't seem to find any documentation about how to do this, so any help would be great.
You could append a string for the options and set it as innerHTML of your select field afterwards:
function getType() {
var x = document.getElementById("food").value;
var items;
if (x === "fruit") {
items = ["Apple", "Oranges", "Bananas"];
} else {
items = ["Eggplants", "Olives"]
}
var str = ""
for (var item of items) {
str += "<option>" + item + "</option>"
}
document.getElementById("pickone").innerHTML = str;
}
document.getElementById("btn").addEventListener("click", getType)
<input type="text" id="food">
<button id="btn">click</button>
<select id="pickone">
</select>
Your logic is not very right, specially where you try to do this
items = "Apple" || items = "Oranges" || items = "Bananas";
with the above statement you are saying that itens are Apple OR Oranges OR Bananas, only one at once...
you'll need an array of elements, like this:
var itens = ["Apple", "Oranges", "Bananas"];
Then, you will need to loop through it to add them to the select, like this:
var itens = ["Apple", "Orange", "Banana"];
var selectElem = document.getElementById("mySelect");
for (var i = 0; i < itens.length; i++){
var item = itens[i];
var element = document.createElement("option");
element.innerText = item;
selectElem.append(element);
}
<select id="mySelect"></select>
With that, now you can achieve what you want, just follow this logic...
you can also, if you want, add an `if` statement to check what is the input value, then set the options based on the input value, as you are already trying to do.
You can change options easily with JavaScript. I would advise to use an additional library to ease DOM manipulation, such as JQuery. An example code would look like the example below. You have to make sure to define an event on which the options should be changed. The example listens to changes within the input field.
<input type="text" id="food" value="vegetables"/>
<select id="pickone"></select>
<script src="https://cdn.jsdelivr.net/npm/jquery#3.3.1/dist/jquery.min.js"></script>
<script>
var fruits = ["Apple", "Oranges", "Bananas"];
var vegetables = ["Eggplants", "Olives"];
vegetables.forEach(function(item){
$('#pickone').append("<option>" + item + "</option>");
});
$('body').on('keyup', '#food', function (){
if ($('#food').val() === 'fruits') {
$('#pickone').html("");
fruits.forEach(function(item){
$('#pickone').append("<option>" + item + "</option>");
});
}
});
</script>

Submit drop down values into google spreadsheet with google script

I have coded a script with help from several stackoverflow examples but I get stuck when trying to go a bit further.
It seems very straightforward but I cannot seem to work it out.
So here it is:
I have coded an HTML script that initiates a dialogbox with some drop down menus. The data in the drop down menus is dynamic and taken from a range in a spreadsheet. I want for users to open the spreadsheet, run the script and choose the options from the drop down values. These drop down values will be pasted on the same spreadsheet.
The bit I got working is that the code sees the values that need to go in the drop down box, illustrates that and that there is a submit box.
However, I cannot seem to submit the values onto the spreadsheet. Please could anyone help me out or point me in the right direction?
test.gs
function openInputDialog1() {
var html = HtmlService.createHtmlOutputFromFile('Test').setSandboxMode(HtmlService.SandboxMode.IFRAME);
SpreadsheetApp.getUi()
.showModalDialog(html, 'Add Item');
}
function getMenuListFromSheet() {
return SpreadsheetApp.getActive().getSheetByName('Part Names')
.getRange(1,5,6,1).getValues();
}
function getThicknessFromSheet(){
return SpreadsheetApp.getActive().getSheetByName('Part Names')
.getRange(1,5,6,1).getValues();
}
function itemadd(form) {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheetByName('Part Names');
var LastRow=sheet.getLastRow();
Logger.log(LastRow);
Logger.log(form);
sheet.getRange(LastRow+1,1,1,2).setValues(form);
return true;
}
Test.html
<!DOCTYPE html>
<html>
<p>List of parts:</p>
<select id="menu">
<option></option>
<option>Google Chrome</option>
<option>Firefox</option>
</select>
<select id="thickness">
<option></option>
<option>1</option>
<option>2</option>
</select>
<script
src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js">
</script>
<input type="submit" value="Submit" onclick="select()">
<script>
// The code in this function runs when the page is loaded.
$(function() {
google.script.run.withSuccessHandler(showMenu)
.getMenuListFromSheet();
google.script.run.withSuccessHandler(showThickness)
.getThicknessFromSheet();
});
/**function showThings(things) {
var list = $('#things');
list.empty();
for (var i = 0; i < things.length; i++) {
list.append('<li>' + things[i] + '</li>');
}
}
**/
function showMenu(menuItems) {
var list = $('#menu');
list.find('option').remove(); // remove existing contents
for (var i = 0; i < menuItems.length; i++) {
list.append('<option>' + menuItems[i] + '</option>');
}
}
function showThickness(menuThickness) {
var list = $('#thickness');
list.find('option').remove(); // remove existing contents
for (var i = 0; i < menuThickness.length; i++) {
list.append('<option>' + menuThickness[i] + '</option>');
}
}
</script>
<script>
function select(){
var x = document.getElementById('menu').value;
var y = document.getElementById('thickness').value;
google.script.run
.itemadd(x,y)
google.script.host.close();
</script>
</html>
I know that I am somewhere not making the connection between the script and the HTML side but fail to understand where.
Thanks,
Tim
Here's the lacking bits from your code:
<input type="submit" value="Submit" onclick="sheetConnect()">
In your .HTML file:
function sheetConnect(){
var e = document.getElementById('menu'); //choices are Google Chrome and Firefox
var name = e.options[e.selectedIndex].value; //get whatever the user selected
google.script.run.writeData(name); //pass the value to Code.gs
}
In your Code.gs
function writeData(name){
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheetByName('Sheet1'); //whatever your sheet's name
var cell = sheet.getRange(1,8); //assign position to column H row 1
cell.setValue(name); // write selected data from Dropdown named 'menu'
}
result:
Use the knowledge here to complete your project :)
I haven't used gs before but from looking at other examples yours looks right, however, in the second line you have tml.Service instead of Html.Service, not sure if that will fix all your issues but that will break it.

Simple javascript: arrays, and form information gathering #2

I don't know javascript much at all, I just like making lists for myself. I am currently trying to create a html page that I can keep track of characters from my favorite game, but I have run across a couple of problems I don't know how to solve.
<form name="inputNightlife" id="inputNightlife">
<h2>Nightlife</h2>
<label for="traits"><b>Traits:</b></label><br>
<select multiple="true" name="traits" id="traits">
<option value="Cologne">Cologne</option>
<option value="Stink">Stink</option>
<option value="Fatness">Fatness</option>
<option value="Fitness">Fitness</option>
</select>
<label for="turnOns"><b>Turn Ons:</b></label><br>
<select multiple="true" name="turnOns" id="turnOns">
<option value="Blonde Hair">Blonde Hair</option>
<option value="Red Hair">Red Hair</option>
<option value="Brown Hair">Brown Hair</option>
<option value="Black Hair">Black Hair</option>
</select>
<p>Select all that apply.</p>
<nav id="box8" class="hide"><table id="menu3"><tr><td rowspan="2" id="soft">
<textarea name="source8" onclick="this.focus();this.select()" cols="40" rows="3" id="result">
</textarea></td><td>
<input type="button" value="Get Code!" onclick="javascript:generateNightlife();"></td>
<td rowspan="2" id="softA">
<img src="./forSCV/icons/nightlife.png" alt="Nightlife" title="Nightlife" id="arrow" onclick="toggle('box8');">
</td></tr><tr><td>
<input type="button" value="Test Code" onclick="javascript:displayNightlife(this.form);">
</td></tr></table></nav></form>
When I click the button, the document.results.endresults.value appears in the text area. I can then copy the results, and save them as html. This is intended to be a page generator (the best I can come up with).
I am not sure how to make traits and turnOns automatically create an array (with spaces) of the chosen options that will then print in the document.result.endresult.value. I did find several different ways to create an array from the forms, but not how to then get it to go into the document.result.endresult.value.
One way Google. And another way Google
Adding...
Ok, I reworked my html to include names and id's, and I found a little better page generator, so I was trying to get that to work. Now I have tried this.
function byId(idStr){return document.getElementById(idStr);}
function getFormValues() {
var traitsSelectElem = byId('traits');
var turnOnsSelectElem = byId('turnOns');
var chosenTraits = getSelectedOptions(traitsSelectElem);
var chosenTurnOns = getSelectedOptions(turnOnsSelectElem);
var i, n, outputStr;
n = chosenTraits.length;
outputStr = '';
for (i = 0; i < n; i ++)
{
if (outputStr != ".")
outputStr += ", ";
outputStr += chosenTraits[i].value;
}
byId('traitsOutput').innerText = outputStr;
n = chosenTurnOns.length;
outputStr = '';
for (i = 0; i < n; i++)
{
if (outputStr != '.')
outputStr += ', ';
outputStr += chosenTurnOns[i].value;
}
byId('turnOnsOutput').innerText = outputStr;
}
function getSelectedOptions(selectElem) {
var i, nOptions = selectElem.options.length;
var result = [];
for (i = 0; i < nOptions; i++)
{
if (selectElem.options[i].selected)
{
result.push(
{
value: selectElem.option[i].value
}
);
}
}
return result;
}
function generateNightlife() {
//nightlife
var traits = getFormValues();
var turnOns = getFormValues();
turnOff = document.inputNightlife.turnOff.value;
perfumeDuration = document.inputNightlife.perfumeDuration.value;
lovePotion = document.inputNightlife.lovePotion.value;
outputNightlife = "<a name='nightlife'></a>\n<div id='easy'>\n<h2>Nightlife</h2>\n
<table class='ntlf'><tr><th>Traits:</th><td class='white'>"+traits+"
</td></tr><tr><th>Turn Ons:</th><td class='white'>"+turnOnsOutput+"</td></tr><tr><th>
Turn Offs:</th><td class='white'>"+turnOff+"</td></tr></table>\n<p class='up2'>Perfume
Duration: <span class='colorme'>"+perfumeDuration+"</span></p>\n<p>Love Potion Duration:
<span class='colorme'>"+lovePotion+"</span></p>\n</div>\n"
document.inputNightlife.source8.value = outputNightlife;
return outputNightlife;
}
When I test it with chrome it says it cannot set property of .innerText of null which I think is because I don't want it to go to a div. I would like the value returned back to function generateNightlife so that it can be added to the outputNightlife. I don't know how to do that, and I need some help.
Here's a fully worked example that will pull multiple selections from a select element, before going on to construct an array with them, and finally printing them to screen.
Either of the two tutes you linked to are okay - it's always hard to know what will be obvious, what will need explaining and what will rely on background information that may/may not have already been covered.
I've used a few different tricks here and there are many that are more sophisticated I've elected to eschew. I hope the comments make the operation clear, though would be happy to add clarification as needed. :)
Here's a runnable snippet:
function byId(idStr){return document.getElementById(idStr);}
function getFormValues()
{
// 1. get a reference to each of the select elemenets we wish to process
var mainMealSelectElem = byId('mainSelect');
var dessertSelectElem = byId('dessertSelect');
// 2. get an array of all of the selected options in each of our select elements
var chosenMains = getSelectedOptions(mainMealSelectElem);
var chosenSweets = getSelectedOptions(dessertSelectElem);
var i, n, outputStr;
n = chosenMains.length;
outputStr = '';
for (i=0; i<n; i++)
{
// only add a comma before an element if at least one element already exists
// this is how we do it when writing a list manually.
if (outputStr != '')
outputStr += ", ";
// grab the two values from the array we constructed using the getSelectedOptions function.
// we said that each array element would have 2 fields, and named them "value" and "textLabel" - both entirely arbitrary name.
// whatever we named them in the below function is what we need to use to access them here.
outputStr += chosenMains[i].textLabel + " (" + chosenMains[i].value + ")";
}
// set the text content of the target span with the array of chosen stuff.
byId('mainsOutput').innerText = outputStr;
n = chosenSweets.length;
outputStr = '';
for (i=0; i<n; i++)
{
if (outputStr != '')
outputStr += ", ";
outputStr += chosenSweets[i].textLabel + " (" + chosenSweets[i].value + ")";
}
byId('dessertsOutput').innerText = outputStr;
}
// returns an array that consists of <value, text-label> pairs - 1 element for each selected option.
function getSelectedOptions(selectElem)
{
// aloop counter and the total number of iterations required
var i, nOptions = selectElem.options.length;
// the empty result array
var result = [];
// loop through all the options this select element has
for (i=0; i<nOptions; i++)
{
// if the current option is selected, we'll need to extract it's info and add it to the output array
if (selectElem.options[i].selected)
{
result.push(
{
value: selectElem.options[i].value,
textLabel: selectElem.options[i].label
}
);
}
}
return result;
}
div
{
display: inline-block;
}
.centered
{
text-align: center;
}
<div class='centered'>
<form>
<h2>Select the ones you like</h2>
<select id='mainSelect' multiple>
<option value='spag'>Spaghetti</option>
<option value='satay'>Peanut satay</option>
<option value='schnitz'>Chicken Schnitzel</option>
</select>
<select id='dessertSelect' multiple>
<option value='1'>Ice-cream</option>
<option value='2'>Fruit salad</option>
<option value='3'>Custard</option>
</select>
</form>
<br>
<button onclick='getFormValues()'>Get chosen values</button>
<hr>
</div>
<br>
<div>
Selected main-meals: <span id='mainsOutput'></span><br>
Selected desserts: <span id='dessertsOutput'></span><br>
</div>
And here's the full (copy/pastable) source:
<!doctype html>
<html>
<head>
<script>
function byId(idStr){return document.getElementById(idStr);}
function getFormValues()
{
// 1. get a reference to each of the select elemenets we wish to process
var mainMealSelectElem = byId('mainSelect');
var dessertSelectElem = byId('dessertSelect');
// 2. get an array of all of the selected options in each of our select elements
var chosenMains = getSelectedOptions(mainMealSelectElem);
var chosenSweets = getSelectedOptions(dessertSelectElem);
var i, n, outputStr;
n = chosenMains.length;
outputStr = '';
for (i=0; i<n; i++)
{
// only add a comma before an element if at least one element already exists
// this is how we do it when writing a list manually.
if (outputStr != '')
outputStr += ", ";
// grab the two values from the array we constructed using the getSelectedOptions function.
// we said that each array element would have 2 fields, and named them "value" and "textLabel" - both entirely arbitrary name.
// whatever we named them in the below function is what we need to use to access them here.
outputStr += chosenMains[i].textLabel + " (" + chosenMains[i].value + ")";
}
// set the text content of the target span with the array of chosen stuff.
byId('mainsOutput').innerText = outputStr;
n = chosenSweets.length;
outputStr = '';
for (i=0; i<n; i++)
{
if (outputStr != '')
outputStr += ", ";
outputStr += chosenSweets[i].textLabel + " (" + chosenSweets[i].value + ")";
}
byId('dessertsOutput').innerText = outputStr;
}
// returns an array that consists of <value, text-label> pairs - 1 element for each selected option.
function getSelectedOptions(selectElem)
{
// aloop counter and the total number of iterations required
var i, nOptions = selectElem.options.length;
// the empty result array
var result = [];
// loop through all the options this select element has
for (i=0; i<nOptions; i++)
{
// if the current option is selected, we'll need to extract it's info and add it to the output array
if (selectElem.options[i].selected)
{
result.push(
{
value: selectElem.options[i].value,
textLabel: selectElem.options[i].label
}
);
}
}
return result;
}
</script>
<style>
div
{
display: inline-block;
}
.centered
{
text-align: center;
}
</style>
</head>
<body>
<div class='centered'>
<form>
<h2>Select the ones you like</h2>
<select id='mainSelect' multiple>
<option value='spag'>Spaghetti</option>
<option value='satay'>Peanut satay</option>
<option value='schnitz'>Chicken Schnitzel</option>
</select>
<select id='dessertSelect' multiple>
<option value='1'>Ice-cream</option>
<option value='2'>Fruit salad</option>
<option value='3'>Custard</option>
</select>
</form>
<br>
<button onclick='getFormValues()'>Get chosen values</button>
<hr>
</div>
<br>
<div>
Selected main-meals: <span id='mainsOutput'></span><br>
Selected desserts: <span id='dessertsOutput'></span><br>
</div>
</body>
</html>

Set option val based on array

I am trying to build a search that uses multiple drop downs. The script for the search uses the values for the first drop down and the second drop down. It works correct for Acura and MDX, but if I choose RLX it still passes MDX to the search as the value.
I know I have so somehow set for the value for the appended option to be whatever array is chosen in the second drop down, but I have had no luck. I am new to javascript so for all I know there may be a way easier than this to accomplish my goal.
FORM FOR SUBMIT
<form name="searchform" onSubmit="return dosearch();">
Brand:
<select id="brands">
<option val="Acura">Acura</option>
<option val="Chrysler">Chrysler</option>
</select>
<select id="item">
</select>
<input type="submit" value="Submit">
</form>
SCRIPT FOR URL STARTING WITH A BASE URL
<script type="text/javascript">
function dosearch() {
var sf=document.searchform;
var baseUrl = 'http://www.spitzer.com/new-inventory/index.htm?';
location.href = baseUrl.concat('make='+ sf.brands.options[sf.brands.selectedIndex].value + '&&&&' + 'model=' + sf.item.options[sf.brands.selectedIndex].value + '&&&&' );
return false;
}
SCRIPT FOR DROP DOWNS
// JavaScript Document
$(document).ready(function(){
Acura=new Array("MDX","RLX","ILX","TLX");
Chrysler=new Array('200','3000','Town&Country');
populateSelect();
$(function() {
$('#brands').change(function(){
populateSelect();
});
});
function populateSelect(){
cat=$('#brands').val();
$('#item').html('');
eval(cat).forEach(function(t) {
$('#item').append('<option val="">'+t+'</option>');
});
}
});
Wow wow!
Please read some code style for js. If it works it doesnt mean that it's good.
DO NOT USE eval, EVER! eval = evil
You forgetting var declaration.
Inline handler in html bad practice too.
forEach will break in IE <= 8
concat is good, plus is good too
... lot of mistakes, that will cost you after.
I`ve wrote you a one liner, but it doesnt have structure. Just some ideas and removed a lot of things.
http://jsfiddle.net/gwEP5/
Whole js code:
$(function (){
// Selector
var $form = $("#searchform");
// it could be hashchange in the future
var setPath = function (url) {
window.location = url;
};
var searchHandler = function (e) {
e.preventDefault();
// You can serialize whole form just by .serialize
var url = window.location.pathname + "?" + $form.serialize();
setPath(url);
};
// Handlers, set handlers in js not in DOM, inline delegation is really nasty
// alias for .submit
$form.on("submit", searchHandler);
// Form elements
var $brands = $('#brands'),
$item = $("#item");
// Items list, dont use new Array or String. It`s good way in
var items = {
"Acura": ["MDX","RLX","ILX","TLX"],
"Chrysler": ['200','3000','Town&Country']
};
// eval is EVIL !!!! don`t use it ever
var populateItems = function () {
var elements = "",
value = $brands.val();
if (items[value] != null) {
$.each(items[value], function (i, item) {
elements += "<option value=\"" + item + "\">" + item + "</option>";
});
}
$item.html(elements);
}
// Alias .change
$brands.on("change", populateItems);
// init for start
populateItems();
});
Html form:
<form name="searchform" id="searchform">
Brand:
<select id="brands" name="make">
<option value="Acura">Acura</option>
<option value="Chrysler">Chrysler</option>
</select>
<select id="item" name="model">
</select>
<input type="submit" value="Submit"/>
</form>
The setup itself is fine. However, you have a typo:
sf.item.options[sf.brands.selectedIndex]
Should be:
sf.item.options[sf.item.selectedIndex]
Or, if you prefer the more aesthetic jQuery:
function dosearch() {
var baseUrl = 'http://www.spitzer.com/new-inventory/index.htm?';
var brand = $('#brands').find(":selected").text();
var item = $('#item').find(":selected").text();
location.href = baseUrl + 'make=' + brand + '&&&&' + 'model=' + item + '&&&&';
return false;
}

Detect multiple drop-down selections and paragraph content dynamically with jQuery and JavaScript

I've created a madlib style paragraph with multiple drop-down selections for synonyms of various words. Here's an example:
<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="110">This is where the text should appear...
</textarea>
Here is a live example: http://jsfiddle.net/T4guG/2/
Using jQuery and Javascript, I am trying to get the selected (and surrounding) text to appear in the text area.
It's kind of working, but there are two problems:
1) SOLVED: There was a problem with punctuation, but replacing:
if (element == "{") {
content_array[i] = foo[j];
j++;
}
with
if (element.indexOf('{') >= 0) {
content_array[i] = foo[j];
j++;
}
allows { to be detected consistently
2) SOLVED: you only can change the options once.
Is there a more elegant solution than what I have come up with? Here is the code:
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();
});
$(".selector").change(function () {
updateTextArea();
});
You are splitting text based on " " (using space) and replacing element { with array value but text is. {, and contains comma i.e., {, is not equal to {. Add space after element {. This solves your first problem.
As you are removing and adding select options dynamically in function updateTextArea(). You have to use .on() to attach event handler for dynamically created elements.
Try:
$( document ).on("change",".selector",function() {
updateTextArea();
});
Instead of
$(".selector").change(function () {
updateTextArea();
});
DEMO FIDDLE

Categories

Resources