how to create x amount of div on select option value - javascript

this is my first question on here so ill try and be as detailed as possible! I am currently creating a HTML form with a select option with options 1 - 4. My aim is to use a Javascript function to create a certain amount of div's depending on which value the user has selected from the form.
For example, if the user has selected option 2, i want to auto generate 2 div containers. Then, if the user chooses to select another option after... the correct amount of divs will then be created.
My select HTML currently looks like this;
<select id="select_seasons">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
</select>
I have created a script which will create a div on button click but this isn't my aim;
var number = 2;
document.getElementById('add').addEventListener('click', function(
) {
var newDiv = document.createElement('div');
newDiv.id = 'container';
newDiv.innerHTML = "<label>Episode " + number + " name</label> <input type='text' name='episode'" + number +" /> <label>Episode " + number + " embed</label> <input type='text' /> ";
document.getElementById('contain_form').appendChild(newDiv);
number++;
});
I would appreciate it if somebody was to help me with the JS i will need to make this functionality and i hope i've explained myself clearly enough in this post!
Feel free to comment and ask for me details if required.
Thanks in advance,
Sam

You need to bind the change event on your select element. Something like this:
var divs = [];
document.getElementById('select_seasons').addEventListener('change', function(e) {
var n = +this.value;
for (var i = 0; i < divs.length; i++) {
divs[i].remove();
}
divs = [];
for (var i = 0; i < n; i++) {
var d = document.createElement("div");
d.className = "new";
document.body.appendChild(d);
divs.push(d);
}
});
.new {
background-color: red;
width: 100px;
height: 20px;
margin: 1px;
}
<select id="select_seasons">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
</select>

Solution for your problem: http://jsfiddle.net/43ggkkg7/
document.getElementById('select_seasons').addEventListener('change', function(){
var container = document.getElementById('container');
container.innerHTML = ''; //clear
//Find selected option
var n = 1;
for(var i = 0; i < this.options.length; ++i){
if(this.options[i].selected){
n = ~~this.options[i].value; //Cast to int
break;
}
}
for(var i = 1; i <= n; ++i){ //Because we want to count from 1 not 0
var newDiv = document.createElement('div');
newDiv.id = 'element-' + i;
newDiv.innerHTML = "<label>Episode " + i + " name</label> <input type='text' name='episode[" + i +"]' /> <label>Episode " + i + " embed</label> <input type='text' /> ";
container.appendChild(newDiv);
}
});
//Emit event on page init
document.getElementById('select_seasons').dispatchEvent(new Event('change'));

I will help you to read this now, I don't need another loop to remove the old divs in the container, you can use innedHTML and set it to empty.
<select id="select_seasons">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
</select>
document.getElementById('select_seasons').addEventListener('change', function() {
var self = this,
exisiting = document.getElementById('contain_form');
//remove existing divs
exisiting.innerHTML = '';
for(i=1; i<= self.value; i++) {
var newDiv = document.createElement('div');
newDiv.id = 'container';
newDiv.innerHTML = "<label>Episode " + i + " name</label> <input type='text' name='episode'" + i +" /> <label>Episode " + number + " embed</label> <input type='text' /> ";
exisiting.appendChild(newDiv);
}
});
Check this fiddle

If I understood the question correctly, the seasons form should update and auto-fill with the select's number. Use the change event and refresh the form with the selected value.
var selectSeasons = document.getElementById("select_seasons");
selectSeasons.addEventListener('change', function() {
populateForm(parseInt(this.value));
});
function populateForm(numberOfSeasons) {
// first, remove all existing fields
var containForm = document.getElementById("contain_form");
while (containForm.firstChild) {
containForm.removeChild(containForm.firstChild);
}
for (var i = 1; i <= numberOfSeasons; i++) {
addDiv(i);
}
}
function addDiv(number) {
var newDiv = document.createElement('div');
newDiv.id = 'container';
newDiv.innerHTML = "<label>Episode " + number + " name</label> <input type='text' name='episode'" + number + " /> <label>Episode " + number + " embed</label> <input type='text' /> ";
document.getElementById('contain_form').appendChild(newDiv);
number++;
}
Number of seasons:
<select id="select_seasons">
<option value="0">Please make a selection</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
</select>
<div id="contain_form"></div>

You could use the selected value of the select element:
var number = select.options[select.selectedIndex].value;
For example:
var select = document.getElementById("select_seasons");
var button = document.getElementById("add");
var container = document.getElementById("container");
button.addEventListener("click", function () {
// uncomment the following line if you want the remove the previously generated divs:
//container.innerHTML = "";
var number = select.options[select.selectedIndex].value;
for (var i = 1; i <= number; i++) {
var div = document.createElement("div");
div.innerHTML = "div #" + i;
container.appendChild(div);
}
});
<select id="select_seasons">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
</select>
<button id="add">Add</button>
<div id="container"></div>

Related

How to print drop down menu items as a list in a textbox

I'm trying to get a drop down menu which has a few options and i can print the total price but i want to add something else like the name of selected option which is written in HERE part. For example if the value of my option is 20 i want to print it like HERE -> 20 but could not make it happen.
Here is the link of my code:
<script type="text/javascript">
function calculatePrice(){
//Get selected data
var elt = document.getElementById("foodItem");
var food = elt.options[elt.selectedIndex].value;
elt = document.getElementById("drinkItem");
var drink = elt.options[elt.selectedIndex].value;
elt = document.getElementById("desertItem");
var desert = elt.options[elt.selectedIndex].value;
elt = document.getElementById("tipItem");
var tip = elt.options[elt.selectedIndex].value;
//convert data to integers
food = parseInt(food);
drink = parseInt(drink);
desert = parseInt(desert);
tip = parseInt(tip);
//calculate total value
var total = food+drink+desert+tip;
//print value to PicExtPrice
document.getElementById("totalPrice").value=total;
}
</script>
<br><br><br><br><br><br>
<center>
<FORM Name="myform">
<SELECT NAME="foodItem" onChange="calculatePrice()" id="foodItem">
<OPTION value="0">Select your food</OPTION>
<OPTION value="35">Anthic Steak </OPTION>
<OPTION value="20">Anthic Lasagna </OPTION>
<OPTION value="15">Anthic Pasta </OPTION>
</SELECT>
<SELECT NAME="drinkItem" onChange="calculatePrice()" id="drinkItem">
<OPTION value="0">Select your drink</OPTION>
<OPTION value="5">Coke </OPTION>
<OPTION value="10">Spritz </OPTION>
<OPTION value="15">Beer </OPTION>
</SELECT>
<SELECT NAME="desertItem" onChange="calculatePrice()" id="desertItem">
<OPTION value="0">Select your desert</OPTION>
<OPTION value="15">Baklava </OPTION>
<OPTION value="20">Sütlaç </OPTION>
<OPTION value="25">Sufle </OPTION>
</SELECT>
<SELECT NAME="tipItem" onChange="calculatePrice()" id="tipItem">
<OPTION value="0">Would you like to tip?</OPTION>
<OPTION value="0">No,thanks. </OPTION>
<OPTION value="10">10TL </OPTION>
<OPTION value="15">15TL </OPTION>
<OPTION value="20">20TL </OPTION>
</SELECT>
</FORM>
<br><br>The amount you have to pay:<br><br><INPUT type="text" id="totalPrice" Size=8>
<script>
</script>
</body>
</center>
</html>
I will create a larger textbox and i want to list them as;
Anthic Steak -> 20TL
Drink -> 10TL
Desert -> 5TL
Tip -> 10TL
Total Price -> 45TL
If you have any ideas, please let me know.
Your code is pretty neat and your existing function calculatePrice can make use of an extra snippet to just create a billing summary as you explained. You are currently using the variable elt to get all the elements by Id, which can be kept unique so that you can later use them to fetch the text value of dropdown, and create a summary. Finally you can add this summary to an empty tag(say div) using its id. Here's an alteration to your JavaScript:
function calculatePrice() {
//Get selected data
var foodElt = document.getElementById("foodItem");
var food = foodElt.options[foodElt.selectedIndex].value;
var drinkElt = document.getElementById("drinkItem");
var drink = drinkElt.options[drinkElt.selectedIndex].value;
desertElt = document.getElementById("desertItem");
var desert = desertElt.options[desertElt.selectedIndex].value;
tipElt = document.getElementById("tipItem");
var tip = tipElt.options[tipElt.selectedIndex].value;
//convert data to integers
food = parseInt(food);
drink = parseInt(drink);
desert = parseInt(desert);
tip = parseInt(tip);
//calculate total value
var total = food + drink + desert + tip;
//print value to PicExtPrice
document.getElementById("totalPrice").value = total;
var summary = '';
if (food > 0) {
summary += foodElt.options[foodElt.selectedIndex].text + ' : ' + food + '\n';
}
if (drink > 0) {
summary += drinkElt.options[drinkElt.selectedIndex].text + ' : ' + drink + '\n';
}
if (desert > 0) {
summary += desertElt.options[desertElt.selectedIndex].text + ' : ' + desert + '\n';
}
if (tip > 0) {
summary += 'Tip' + ' : ' + tip + '\n';
}
document.getElementById("summary").innerHTML = summary;
}
Here's an addition to HTML:
<div id="summary"></div>
Note: You can simply make use of the same variable elt, but you will have to manage summary calculation inline ;)

change text attribute of an option

Trying to change text attribute of an option using its value as a variable.
My trying doesn't work, any help, pls.
Expecting result is:
<option value = 2>earth</option>
var x = 2
var str = 'earth';
$('button').on('click', function(){
$('#sela:option[value = ' + x + ']').attr('text', str);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select id='sela'>
<option value = 1>lorem</option>
<option value = 2>ipsum</option>
</select>
<br><br>
<button>CLICK</button>
You have to use $('#sela>option[value = ' + x + ']') to select the direct option child of #sela.
And use text() to update the option text.
var x = 2
var str = 'earth';
$('button').on('click', function() {
$('#sela>option[value = ' + x + ']').text(str);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select id='sela'>
<option value=1>lorem</option>
<option value=2>ipsum</option>
</select>
<br><br>
<button>CLICK</button>

How to use onchange function with dropdown and a total sum in HTML/JavaScript

I'm currently stuck at a shopping cart like HTML site in which the items get created dynamically. I want the sum of a single item and the total sum to refresh when the dropdown gets select to a certain value. I tried this with a onchange function but this didn't work. What am I doing wrong and is there a way to refresh the sums at all?
The JavaScript code is the following:
$( document ).ready(function() {
console.log("BEREIT ZUM SOP");
var sum = 0;
// artikel in von session holen über sbservice
$.ajax({
url: "http://localhost:8080/HandyHammer/rest/shoppingbasket",
method: "GET",
dataType: "json"
})
.done(function(responseData) {
console.log(responseData);
for(var i=0;i<responseData.length;i++){
var data1=responseData[i];
console.log("sarajevo");
console.log("istanbul");
console.log(data1);
var prc= data1.price;
sum = sum + prc; //addiere summe
console.log(sum);
var tmp = '<tr> <td id="warenid">'+data1.id+'</td> <td id="Bezeichnung">'+data1.title+'</td> <td id="preis">'+prc+'€</td> <td><select id="menge" name="maximum10">';
tmp += '<option value="1">1</option> <option value="2">2</option> <option value="3">3</option> <option value="4">4</option>';
tmp += '<option value="5">5</option> <option value="6">6</option> <option value="7">7</option> <option value="8">8</option> <option value="9">9</option> <option value="10">10</option>';
tmp += '</select></td><td id="summe">'+prc+'</td> <td><a id="removeBestellung" class="btn1" type="button"><i class="fa fa-trash" aria-hidden="true"></i></a> </td>'; //removebestellung kommt später DONT FORGET
tmp += '</tr>';
$("#upper").after(tmp);
}
var select = document.getElementById("menge");
select.onchange = function() {
var answer = select.options[select.selectedIndex].value;
console.log("Wert der Dropdown "+answer);
var summe = document.getElementById("summe").innerHTML;
console.log("wert der SUMME Yeet " + summe*answer);
var oldval = summe;
var newval = summe*answer;
var diff = newval - oldval;
document.getElementById("summe").innerHTML = newval;
}
var onsumme = document.getElementById("summe");
console.log("sum 1 " + sum);
console.log("summe element " + onsumme);
onsumme.onchange = function() {
console.log("diff variable " + diff);
sum += diff;
console.log("sum funktion " + sum);
$(".total").append(sum+"€");
}
})
.fail(function( errorResponse, statusText, error ) { // fehlerfall
alert(errorResponse.responseText);
});
/* $("#menge").change(function(){
console.log("change funktion aufgerufen " + sum);
var select = document.getElementById("menge");
var answer = select.options[select.selectedIndex].value;
console.log(answer);
var x = document.getElementById("sume").textContent;
document.getElementById('summe').textContent = x * answer ;
}); */
});
</script>
</body>
</html>
Using the below Select onChange Jquery event, you can get the value wheneven you change the select option value.
$( "select" ).change(function() {
selectedValue= parseInt$(this).val());
selectedValue + (X number);
alert( selectedValue + (X number));
});
in the above script, selected value will be stored in the selectedValue variable so you can add the value with that same variable.
Link for your reference: https://jsfiddle.net/5dbx80f3/6/
You are having problem because the type of 'summe' isnt integer. you can convert it into integer by using
var summe = parseInt(document.getElementById("summe").innerHTML);

Javascript Add To A div Not Working

I cannot figure out why this is not working. What am I doing wrong?!
I am trying to add a row consisting of a form element to a div.
I have gone through this many times and nothing. What am I doing wrong?
Code:
<div class="row">
<div class="col-md-4">
<select class="form-control" id="attributeSelect" style="width: 100%">
<option value='1'>Colors</option>
<option value='2'>Product Type</option>
<option value='3'>Brands</option>
<option value='4'>Product Type</option>
<option value='5'>Width</option>
<option value='6'>Materials</option>
<option value='7'>Pattern</option>
</select>
</div>
<div class="col-md-2 text-left">
<button class="btn btn-md btn-success" onclick="addAttribute();">ADD</button>
</div>
</div>
<div id="add-attribute">
</div>
Javascript:
<script type="text/javascript">
function addAttribute() {
var iDiv = document.createElement('div');
iDiv.className = 'row';
document.getElementById('add-attribute').appendChild(iDiv);
// Now create and append to iDiv
var innerDiv1 = document.createElement('div');
innerDiv1.className = 'col-lg-4';
iDiv.appendChild(innerDiv1);
innerDiv1.innerHTML = "Value";
// Now create and append textbox
var innerDiv2 = document.createElement('div');
innerDiv2.className = 'col-lg-8';
iDiv.appendChild(innerDiv2);
var attributeSelect = document.getElementById("attributeSelect");
var attributeValue = e.options[e.selectedIndex].value;
innerDiv2.innerHTML = "<input type='text' name='attr_" + attributeValue + ' >";
}
</script>
your innerDiv2.innerHTML is not being set properly.
also e.options[e.selectedIndex].value does not make sense. you can simply get the value from attributeSelect itself.
function addAttribute() {
var iDiv = document.createElement('div');
iDiv.className = 'row';
document.getElementById('add-attribute').appendChild(iDiv);
// Now create and append to iDiv
var innerDiv1 = document.createElement('div');
innerDiv1.className = 'col-lg-4';
iDiv.appendChild(innerDiv1);
innerDiv1.innerHTML = "Value";
// Now create and append textbox
var innerDiv2 = document.createElement('div');
innerDiv2.className = 'col-lg-8';
iDiv.appendChild(innerDiv2);
var attributeSelect = document.getElementById("attributeSelect");
var attributeValue = attributeSelect.value;
innerDiv2.innerHTML = "<input type='text' name='attr_" + attributeValue + "' >";
}

Why JQUERY clone functions and appending an id to it and confirm email value?

I am having 2 tricky UX JQuery problems that I'm currently working on.
I am cloning a 2 form variables using JQuery. How do I index, id them so I can label them with this id.
For example if I pick 3 from the select box I should get 3 lines of form and on the left hand side of each line should begins with a number starting 1. form, 2. form, 3 form.
The second problem I have I want to validate attendant[] against confirmattendant[]. How would I do this inside a cloned HTML code.
Here is my JSFiddle
http://jsfiddle.net/tGprH/5/
Here is my HTML code:
<select name="select" id="select">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
</select>
<br/>
<p>Email address, Confirm Email Address</p>
#1 <input type="text" name="attendant[]"/>
<input type="text" name="confirmattendant[]"/>
<br/>
<div id="container">
</div>
Here is my JQuery
$("select").change(function() {
var select = parseInt($('#select').val() , 10);
var $clone = '<input type="text" name="attendant[]" /><input type="text" name="confirmattendant[]" /><br/>';
console.log($clone);
var html = '';
for(var i = 1;i< select ; i++){
html += $clone;
}
$('#container').empty().html(html);
}).change();
you can print the required in your for loop like..
html += '#'+(i + 1)+ ' '+$clone;
try this
$("select").change(function() {
var select = parseInt($('#select').val() , 10);
var $clone = '<input type="text" name="attendant[]" /><input type="text" name="confirmattendant[]" /><br/>';
console.log($clone);
var html = '';
for(var i = 1;i< select ; i++){
html += '#'+(i + 1)+ ' '+$clone;
}
$('#container').empty().html(html);
})
fiddle here
About the first problem : http://jsfiddle.net/tGprH/7/
$("select").change(function() {
var select = parseInt($('#select').val() , 10);
var $clone = '<input type="text" name="attendant[]" /><input type="text" name="confirmattendant[]" /><br/>';
console.log($clone);
var html = '';
for(var i = 1;i< select ; i++){
if(i >= 1)
html += '#' + (i+1) + ' ' + $clone;
else
html += $clone;
}
$('#container').empty().html(html);
}).change();
And about the comparison : http://jsfiddle.net/tGprH/8/
<button id="compare">compare</button>
$('#compare').click(function(){
var $attendantArray = $('input[name="attendant[]"]');
var $confirmattendantArray = $('input[name="confirmattendant[]"]');
for(var i = 0;i< $attendantArray.length ; i++)
{
alert((i+1) + ' attendant [' + $($attendantArray[i]).val() + ' / ' + $($confirmattendantArray[i]).val() + ']')
}
});

Categories

Resources