Javascript and HTML - Getting value from a SPAN and Selection [duplicate] - javascript

This question already has answers here:
Get selected option text with JavaScript
(16 answers)
Closed 4 years ago.
I am fairly new to Javascript programming. I would like to get the selected value from the list of values presented to the customer. I want to display this as a simple text saying, the selection was from the options provided. Let me paste the code snippet
<span id="Step2" style="display:none">
<form>
<fieldset>
<legend>Type of Customization</legend>
<p>
<label>Available Customization</label>
<select id = "myCust">
<option value = "1">New Dimension Table</option>
<option value = "2">Add a Fact Table</option>
<option value = "3">Completely New Form</option>
<option value = "4">Edit an Old Form</option>
<option value = "5">Others</option>
</select>
</p>
</fieldset>
</form>
so from the provided options, if the person chooses, say, "Completely New Form" I would like to display that into the HTML
I tried
document.getElementById("myCust")
but that won't work.

function getCust() {
var typeofCust = document.getElementById("myCust");
var cust = typeofCust.querySelector('option[value="'+typeofCust.value+'"]');
document.getElementById('selected-customer').innerText=cust.innerText;
}
document.getElementById('myCust')
.addEventListener('change', getCust)
<div id="FooterTableStep2" style="background-color:Silver">
Selected Customization : <span id="selected-customer"></span>
</div>
<form>
<fieldset>
<legend>Type of Customization</legend>
<p>
<label>Available Customization</label>
<select id="myCust">
<option value="1">New Dimension Table</option>
<option value="2">Add a Fact Table</option>
<option value="3">Completely New Form</option>
<option value="4">Edit an Old Form</option>
<option value="5">Others</option>
</select>
</p>
</fieldset>
</form>
getElementById returns the actual HTML element object.
const selectEl = document.getElementById('myCust');
const customer = selectEl.value;
console.log(customer); // selected value
It's also worth noting that most elements can also query their children
const row = document.querySelector('td:nth-child(13)');
const selectEl = row.getElementById('some-id');
Updated to include your comment:
<td id="FooterTableStep2" style="background-color: silver;">
Selected Customization: <span id="selected-customer"></span>
</td>
<script>
function getCust() {
var typeofCust = document.getElementById("myCust");
var cust = typeofCust.querySelector('option[value="' + typeofCust.value + '"]');
document.getElementById('selected-customer').innerText = cust.innerText;
}
</script>

Related

How to use a value as a name of a file?

I'm a newbie in JS. I want to change the background image of a div by using values from tag. I can change the background-color but now I want to use the value as the name of a jpg file. Does anyone know how? The values will be 1,2,3 and the name of the graphic files are 1.jpg, 2.jpg and 3.jpg.
<div class="container" id="wrapper">
<form>
<label for="my-select">Choose the continent: </label>
<select
name=""
id="my-select"
value="Choose the continent"
onChange="myFunction()"
>
<option value="default">default</option>
<option value="1">Asia</option>
<option value="2">Australia</option>
<option value="3">South america</option>
</select>
</form>
</div>
const myWrapper = document.querySelector("#wrapper");
function myFunction() {
var x = document.getElementById("my-select").value;
myWrapper.style.backgroundImage = url("images/x.jpg");
}
// I know the last line won't work.
You were close, try something like this:
const myWrapper = document.querySelector("#wrapper");
function myFunction() {
var x = document.getElementById("my-select").value;
myWrapper.style.backgroundImage = "url(images/" + x + ".jpg)";
}
<div class="container" id="wrapper">
<form>
<label for="my-select">Choose the continent: </label>
<select
name=""
id="my-select"
value="Choose the continent"
onChange="myFunction()"
>
<option value="default">default</option>
<option value="1">Asia</option>
<option value="2">Australia</option>
<option value="3">South america</option>
</select>
</form>
</div>
If you want even more readable code, you can use template literals instead of string concatenation, like this:
myWrapper.style.backgroundImage = `url(images/${x}.jpg)`;
Your Solution is mostly correct. You only needed to insert the entire string to the CSS-Styling, as you would normally in CSS.
You then needed to concatenate the X-Value to the string, so it gets the number stored in it instead of the x as a direct character.
const myWrapper = document.querySelector("#wrapper");
function myFunction() {
var x = document.getElementById("my-select").value;
// You'll need to insert the CSS-Style as an entire string.
// We concatenate the Variable X to the string, so it gets dynamicly used.
myWrapper.style.backgroundImage = "url('images/"+x+".jpg')";
}

Fill Field textarea different select

I've been stuck in this problem for a few days. I am trying to create selects and by choosing, fill the field in the "textarea". An example of what I did and what I'm trying to do. The image is edited. I don't know how to create more than one select that feeds the same textarea.
function fillFild() {
var myList = document.getElementById("myList");
document.getElementById("fild").value = myList.options[myList.selectedIndex].value;
}
function fillFild1() {
var myList = document.getElementById("myList1");
document.getElementById("fild1").value = myList.options[myList.selectedIndex].value;
}
<form name="Form">
Select your Device:
<select id="myList" name="select_field" onchange="fillFild();">
<option value="Laptop: ">Laptop</option>
<option value="PC:">PC</option>
<option value="Smartphone: ">Smartphone</option>
<option value="Tablet: ">Tablet</option>
</select>
<form name="Form1">
Select your Problem:
<select id="myList1" name="select_field" onchange="fillFild1();">
<option value="Software: ">Software</option>
<option value="Hardware:">Hardware</option>
</select>
<textarea name="TextArea" id="fild1" style="position:absolute;left:23px;top:153px;width:394px;height:119px;z-index:5;" rows="7" cols="47" spellcheck="false"></textarea>
</form>
Illustrating what I'm trying to do
Thanks in advance!
I see you are trying hard to add a post. The one you added has already closed, and you're still adding pretty much the same. Not the way ;)
First, read carefully how to ask questions how-to-ask
Below you have the solution to your question:
const selectElements = document.querySelectorAll('.select_field');
const textArea = document.querySelector('textarea');
[].slice.call(selectElements).map(el => el.addEventListener('change', e => {
const selcted = e.target.value;
if (selcted !== '') {
textArea.value += selcted + '\n';
}
}));
<div>
Select your Device:
<select id="myList" name="select_field" class="select_field">
<option value="">-- choose --</option>
<option value="Laptop:">Laptop</option>
<option value="PC:">PC</option>
<option value="Smartphone:">Smartphone</option>
<option value="Tablet:">Tablet</option>
</select>
</div>
<div>
Select your Problem:
<select id="myList1" name="select_field" class="select_field">
<option value="">-- choose --</option>
<option value="Software:">Software</option>
<option value="Hardware:">Hardware</option>
</select>
</div>
<textarea name="TextArea" id="fild1" rows="7" cols="47" spellcheck="false"></textarea>

How to get jQuery autocomplete selected values as an array

I'm using jQuery autocomplete multiple select, I'm trying to get the values into an array like: ["kiwi", "fraise", "avocat", "banane"], however it is only showing as: kiwi, fraise, avocat, banane,
I'm using chosenjs along with the chosen.order plugin
As I said I can easily get the selected items in order, I just can't get it to output as an array, any help would be most welcome.
The jquery code is:
$(document).ready(function() {
// Chosenify every multiple select DOM elements with class 'chosen'
$('select.chosen').chosen();
// Get a reference to the DOM element
var MY_SELECT = $('select[multiple].chosen').get(0);
$('#get-order').click(function() {
var selection = ChosenOrder.getSelectionOrder(MY_SELECT);
$('#order-list').empty();
$('#order-list').html("<div>" + selection + "</div>");
});
});
And the HTML is:
<h1>The Chosenified multiple <select></h1>
<p>
<select name="fruits" class="chosen" multiple style="width: 500px;">
<option value="banane">Banane</option>
<option value="pomme">Pomme</option>
<option value="poire">Poire</option>
<option value="ananas" selected>Ananas</option>
<option value="kiwi" selected>Kiwi</option>
<option value="goyave">Goyave</option>
<option value="abricot">Abricot</option>
<option value="fraise" selected>Fraise</option>
<option value="framboise">Framboise</option>
<option value="avocat" selected>Avocat</option>
</select>
</p>
<h2>Retrieving the order</h2>
<p>
<button type="button" id="get-order">Retrieve selection in order</button>
<br/>
</p>
<P>
<div id="order-list"></div>

Javascript Calculating a Form [duplicate]

This question already has answers here:
How not to refresh a page from JavaScript?
(3 answers)
Closed 6 years ago.
Please help me:
when i put this code it shows the result for only a sec before it refreshes the entire page. I havent been able to find any problems apart from it saying that calcCharterCost is not defined. I do not know what it means by that because to me it looks defined.
Thanks,
<script>
function calcCharterCost()
{
var destList = document.getElementById("destList");
var distance = destList.options[destList.selectedIndex].id;
var speedList = document.getElementById("speedList");
var gph = speedList.options[speedList.selectedIndex].id;
var speed = speedList.value;
var fuelCost = document.getElementById("fuelCost").value;
var feeOutput = document.getElementById("fee");
var time;
time = (distance / speed);
var cost;
cost = time * gph * fuelCost;
feeOutput.innerHTML = "$" + cost;
}
function validate()
{
if (isNaN(fuelCost) == true)
{
document.getElementById("error").innerHTML="Error invalid Fuel Cost";
document.myform.fuelCost.value="";
document.myform.fuelCost.focus();
}
}
</script>
<body>
<form name="myform">
<select id="destList">
<option id="28">Falmouth to Nantucket</option>
<option id="11">Falmouth to Edgartown</option>
<option id="7.6">Falmouth to Oak bluffs</option>
<option id="38">Falmouth to Newport</option>
</select>
<p/>
<select id="speedList">
<option id="18" value="14">14 kt</option>
<option id="24" value="18">18 kt</option>
<option id="30" value="20">20 kt</option>
<option id="37" value="22">22 kt</option>
</select>
<p/>
<input type="text" id="fuelCost" value="4.25" onblur="validate()"/>
<i><small><span style="color:red;" id="error" ></i></small> </span>
<p/>
<button onClick="calcCharterCost()">Calculate</button>
<p> The cost of the charter is <div id="fee">XXXX</div>
</body>
By default a button without a type will submit a form.
Either give the button a non-submit type:
<button type="button" onClick="calcCharterCost()">Calculate</button>
Or remove the form tag:
<form name="myform">
The latter seems preferable anyway, since the form tag is never closed and technically the markup is invalid. Nothing is actually using this form, so it's not needed.
You have markup errors and did not define fuelCost variable in global scope. When validate method executes, it cannot find the fuelCost variable as it is defined and used in calculate method.
I have fixed your script and markup issues. Please check out the corrected version and fiddle.
<script>
var fuelCost = 0;
function calcCharterCost() {
var destList = document.getElementById("destList");
var distance = destList.options[destList.selectedIndex].id;
var speedList = document.getElementById("speedList");
var gph = speedList.options[speedList.selectedIndex].id;
var speed = speedList.value;
fuelCost = document.getElementById("fuelCost").value;
var feeOutput = document.getElementById("fee");
var time;
time = (distance / speed);
var cost;
cost = time * gph * fuelCost;
feeOutput.innerHTML = "$" + cost;
}
function validate() {
if (isNaN(fuelCost) == true) {
document.getElementById("error").innerHTML = "Error invalid Fuel Cost";
document.myform.fuelCost.value = "";
document.myform.fuelCost.focus();
}
}
</script>
<body>
<select id="destList">
<option id="28">Falmouth to Nantucket</option>
<option id="11">Falmouth to Edgartown</option>
<option id="7.6">Falmouth to Oak bluffs</option>
<option id="38">Falmouth to Newport</option>
</select>
<p>
<select id="speedList">
<option id="18" value="14">14 kt</option>
<option id="24" value="18">18 kt</option>
<option id="30" value="20">20 kt</option>
<option id="37" value="22">22 kt</option>
</select>
</p>
<input type="text" id="fuelCost" value="4.25" onblur="validate()" />
<span style="color:red;" id="error"></span>
<button onClick="calcCharterCost()">Calculate</button>
The cost of the charter is
<div id="fee">XXXX</div>
</body>
Form tag is not needed in this scenario as it is not referenced by any other part of your code. I removed it.
Fiddle

Automatic form fill using javascript

here is my code:
function setActualDate()
{
var d1 = new Date();
var y = d1.getFullYear();
var d = d1.getDate();
var m1 = d1.getMonth() + 1;
var m2 = d1.getMonth();
document.getElementById('entryDate').value = (y+"-"+m1+"-"+d);
document.getElementById('selectedYear').value = y;
document.getElementById('selectedMonth').value = ("0"+m2);
}
</script>
</head>
<body onload="setActualDate()">
<div id="page">
<h3> Welcome to Money Logger!</h3>
<form name="enter" action="enter.php" method="post">
Enter
<select name="mode">
<option selected="selected" value=""></option>
<option value="1">the money withdraw</option>
<option value="2">the money income</option>
</select>
<input id ="entryDate" type="date" name="entryDate">
<input type="text" name="entryName">
<input type="text" name="entryValue">
<input type="submit" value="Enter">
<input type="reset" value="Clear">
</form>
<form name="getEntry" action="getEntry.php" method="post">
Choose month and year for monthly overview:
<select name="month">
<option id = "selectedMonth" selected="selected" value=""></option>
</select>
<select name="year">
<option id = "selectedYear" selected="selected" value=""></option>
</select>
<input type="submit" value="Display">
</form>
</div>
</body>
I used simple javascript to automatically fill the form inputs "entryDate, selectedYear, selectedMonth" by actual date and some other dates used by the further scripts.
My problem is, that when the site is loaded, only first input is automatically filled - the input with id = entryDate.
The next 2 inputs are empty. But, when I press F5 and the site is reloaded again, the 2 inputs are filled correctly.
Could you please help me fix it to have all 3 forms filled when the site is loaded for the first time...
Thank you
You are not using <select> and <option> correctly. <select> represents a dropdown, which can contain multiple <option> elements.
An <option> element represents an option in the dropdown. You close an <option> with </option>. Whatever is BETWEEN the tags will appear in the dropdown:
<option>Hello</option> <!--user sees "Hello" as an option in the dropdown-->
On the other hand, an <option>'s value attribute contains the string that will be sent to the server, if the option is selected, when the form is submitted. You can think of this as the "real" value of the <option>: the user won't see it, but it's the one that matters. Whatever is between <option> and </option> is visible by the user, but doesn't actually DO anything.
Any one of a dropdown's options can be "selected" (that is, visible as the chosen option in the dropdown) by giving it a selected attribute set to selected (selected="selected"). When a user chooses an option, this attribute gets set automatically (and the selected attribute on the other options gets cleared).
So first of all, let's get your selectedYear dropdown looking right. You'll need to manually provide some years as options:
<select id="selectedYear" name="year">
<option value="2013">2013</option>
<option value="2012">2012</option>
<option value="2011">2011</option>
</select>
Note that you need to specify the year both between the tags AND in each <option>'s value attribute, as explained above. Also note that I moved the id to the <select>. There's rarely a reason to select an individual <option> of a <select>; typically to modify a dropdown's options, you should select the <select> tag itself.
So, let's try that. I'll re-create the dropdown above, but I'll add its options using JavaScript:
<select id="selectedYear" name="year"></select>
<script type="text/javascript">
var dropdown = document.getElementById('selectedYear');
var start_year = 2011;
var end_year = 2013;
for (var i = start_year; i <= end_year; i++) {
dropdown.innerHTML += '<option value="' + i + '">' + i + '</option>';
}
</script>
The innerHTML function lets you set the HTML content between an element's opening tag (in this case <select id="selectedYear" name="year"> and closing tag (</select>).
Knowing this, it's pretty easy to select the option you want using JavaScript. Remember you can do this by setting the selected attribute of the <option> to "selected". Here's a portion of your setActualDate function, showing how to set the default year for just the selectedYear dropdown:
<script type="text/javascript>
function setActualDate() {
var d1 = new Date();
var year = d1.getFullYear();
var dropdown = document.getElementById('selectedYear');
//loop through the dropdown's options
for (var i = 0; i < dropdown.options.length; i++) {
var option = dropdown.options[i];
//check if this is the option we want to set
if (option.value == year) {
option.selected = true;
} else {
//ensure all other options are NOT selected
option.selected = false;
}
//NOTE: you can simplify the above if-else to just:
//option.selected = (option.value == year);
}
}
</script>
That should be enough to get you started. I hope it all makes sense.
Use the following HTML for month -
<!-- HTML for month -->
<select id = "selectedMonth" name="month">
<option value="1">Jan</option>
<option value="2">Feb</option>
<option value="3">Mar</option>
<option value="4">Apr</option>
<option value="5">May</option>
<option value="6">Jun</option>
<option value="7">Jul</option>
<option value="8">Aug</option>
<option value="9">Sep</option>
<option value="10">Oct</option>
<option value="11">Nov</option>
<option value="12">Dec</option>
</select>
<!-- HTML for year -->
<select id="selectedYear" name="year">
<option value="2010">2010</option>
<option value="2011">2011</option>
<option value="2012">2012</option>
<option value="2013">2013</option>
</select>
and script
//script for setting month
var monthEl = document.getElementById('selectedMonth');
monthEl.options[m2].selected = "selected"
//for year
var yearEl = document.getElementById('selectedYear');
yearEl.options[y].selected = "selected"
You are getting the elements by their ID so the first time the script runs only fills out the first elements it finds (probably the ones in the first form).
Since you have several elements to fill out automatically, you should be setting classes to on them and use these classes to select the ones you are interested in. For example:
<form id="form1">
<input class="entryDate" type="text"> <!-- note the class=..." -->
</form>
<form id="form2">
<input class="entryDate" type="text">
<select name="mode" class="selectedMonth"> <!-- note the class=..." -->
<option selected="selected" value=""></option>
<option value="1">the money withdraw</option>
<option value="2">the money income</option>
</select>
</form>
Now your code should be something like this:
window.onload = function setActualDate() {
var d1 = new Date();
var y = d1.getFullYear();
var d = d1.getDate();
var m1 = d1.getMonth() + 1;
var m2 = d1.getMonth();
var entryDates = document.getElementsByClassName('entryDate');
var years = document.getElementsByClassName('selectedYear');
var months = document.getElementsByClassName('selectedMonth');
var i, j;
for (i in entryDates)
entryDates[i].value = (y + "-" + m1 + "-" + d);
for (i in months) {
for (j in months[i].options)
if (months[i].options[j].value == m1) {
months[i].options[j].selected = true;
break;
}
}
//similarly for years...
};
Here's a fiddle demonstrating it: http://jsfiddle.net/QDdAp/2/

Categories