change text attribute of an option - javascript

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>

Related

Re-posting <input> value into <textarea>

I want to re-generate user's input values onto textarea with specific format.
I've created input and 'select' with various 'options' inside as well as 'button' that triggers the function.
Can someone please tell me what I'm doing wrong here..?
<SCRIPT>
function myFunction() {
var finaL = document.getElementById("textArea").value;
var spacE = " | ";
var a = document.getElementById("input1").value;
var b = document.getElementById("input2").value;
var c = document.getElementById("selecT").value;
finaL = a + spacE + b + spacE + c;
}
</SCRIPT>
In your code your are getting the value of the textarea and storing it in final variable which is just a string. What you need to do is get the reference of the textarea in the final variable and then set the value.
Working Code:
function myFunction() {
var finaL = document.getElementById("textArea");
var spacE = " | ";
var a = document.getElementById("input1").value;
var b = document.getElementById("input2").value;
var c = document.getElementById("selecT").value;
finaL.value = a + spacE + b + spacE + c;
}
<label for="input1">Male</label>
<input name="input1" id="input1" /> <br>
<label for="input2">Input 3</label>
<input name="input2" id="input2" /> <br>
<label for="selecT">Input 3</label>
<select id="selecT">
<option value="Value 1">Value 1</option>
<option value="Value 2">Value 2</option>
<option value="Value 3">Value 3</option>
</select>
<br>
<button type="button" onclick="myFunction()">Copy</button>
<br>
<label>Result</label>
<textarea id="textArea"></textarea>
just update code to this
<SCRIPT>
function myFunction() {
var finaL = document.getElementById("textArea").value;
var spacE = " | ";
var a = document.getElementById("input1").value;
var b = document.getElementById("input2").value;
var c = document.getElementById("selecT").value;
document.getElementById("textArea").value = a + spacE + b + spacE + c;
}
</SCRIPT>
what i change is from this
value = a + spacE + b + spacE + c;
to this
document.getElementById("textArea").value = a + spacE + b + spacE + c;

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);

how to create x amount of div on select option value

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>

Show variable value in list?

<!doctype html>
<html>
<head>
<body>
<script>
var a=8;
var b=5;
var c=8;
var d=9;
</script>
<select size="5">
<option value="1">"a" seats remaining</option>
<option value="2">"b" seats remaining</option>
<option value="3">"c" seats remaining</option>
<option value="4">"d" seats remaining</option>
</select>
</body>
</html>
In the list, instead of a,b,c,d, can i show the values of the variables like 8,5,8,9?
Give your options an ID for easy access:
<select size="5">
<option id="a" value="1"></option>
<option id="b" value="2"></option>
<option id="c" value="3"></option>
<option id="d" value="4"></option>
</select>
Then you can simple do something like
var a=8;
var b=5;
var c=8;
var d=9;
document.getElementById("a").innerHTML = a + ' seats remaining';
document.getElementById("b").innerHTML = b + ' seats remaining';
document.getElementById("c").innerHTML = c + ' seats remaining';
document.getElementById("d").innerHTML = d + ' seats remaining';
Demo: http://jsfiddle.net/Ayp28/
Try this with using jQuery if you want to replace.
$("select > option").each(function() {
var array = {"a":"8", "b":"5", "c":"8", "d":"9"};
for (var val in array)
this.text = this.text.split('"' + val + '"').join('"' + array[val] + '"');
});

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