Show image depending on <option value> in a <select> element - javascript

I've been struggling for the last 2 days to create an option when a user clicks the button "submit" after they selected a value from a "select>" element, the website to show an image.
<label for="cars" id="carInput" name="carInput">
<select id="modelsList">
<option value="mba">Mercedes-Benz A Class</option>
<option value="mbc">Mercedes-Benz C Class</option>
<option value="mbe">Mercedes-Benz E Class</option>
<option value="mbs">Mercedes-Benz S Class</option>
<option value="mbeq">Mercedes-Benz EQE Class</option>
<option value="mbeqs">Mercedes-Benz EQS Class</option>
</select>
<button id="btn">submit</button>
I tried something like this in Javascript, but everytime I click the submit button it adds a new image and I really dont want that, I want the image to change everytime a value is chosen.
document.querySelector('#btn').addEventListener('click', submit);
function submit() {
let select = document.querySelector('#modelsList');
let value = select.options[select.selectedIndex].value;
let container = document.querySelector('.container');
const aImg = document.createElement("img");
const cImg = document.createElement("img");
const eImg = document.createElement("img");
const sImg = document.createElement("img");
const eqImg = document.createElement("img");
const eqeImg = document.createElement("img");
aImg.src = "https://ag-spots-2021.o.auroraobjects.eu/2021/07/26/mercedes-amg-cla-45-c117-c479326072021173956_1.jpg?1627314027"
cImg.src = "https://ireland.apollo.olxcdn.com/v1/files/eyJmbiI6IjM1bXk3dTVtcTd1OC1BVVRPVklUUk8iLCJ3IjpbeyJmbiI6InE3bXo1M2JpZnB6ay1BVVRPVklUUk8iLCJzIjoiMTYiLCJwIjoiMTAsLTEwIiwiYSI6IjAifV19.dxCeoriV-0ygVtEXaXgFFvuomnzNmndAS1G5qVVYqaM/image;s=1080x720"
eImg.src = "https://ireland.apollo.olxcdn.com/v1/files/eyJmbiI6IjdjYzZ2cm84NjNrcS1BVVRPVklUUk8iLCJ3IjpbeyJmbiI6InE3bXo1M2JpZnB6ay1BVVRPVklUUk8iLCJzIjoiMTYiLCJwIjoiMTAsLTEwIiwiYSI6IjAifV19.5PJ743A4FPdZuZkRpYhJh9g96i1AASth2X4nBJXS0oU/image;s=644x461"
sImg.src = "https://ireland.apollo.olxcdn.com/v1/files/eyJmbiI6InM1NnM5ZndkYTR4dC1BVVRPVklUUk8iLCJ3IjpbeyJmbiI6InE3bXo1M2JpZnB6ay1BVVRPVklUUk8iLCJzIjoiMTYiLCJwIjoiMTAsLTEwIiwiYSI6IjAifV19.1N_EW-jPwI1Q33sSuwaIdYxTexUdYAHcWgEFYCPqkrU/image;s=1080x720"
eqImg.src = "https://www.cars-data.com/pictures/mercedes/mercedes-benz-g-class_4266_24.jpg"
eqeImg.src = "https://mercedesblog.com/wp-content/uploads/2019/06/mercedes-eqe.jpg"
if (value === 'mba') {
container.appendChild(aImg);
} else if (value === 'mbc') {
container.appendChild(cImg)
} else if (value === 'mbe') {
container.appendChild(eImg);
} else if (value === 'mbs') {
container.appendChild(sImg);
} else if (value === 'mbeq') {
container.appendChild(eqImg);
} else {
container.appendChild(eqeImg);
}
}
And 1 more bonus question: how to actually inject a whole div container with 3 flex childrens(a img, paragraph and a small div) when the submit button is clicked?

Try removing all child nodes from the container first:
function removeAllChildNodes(parent) {
while (parent.firstChild) {
parent.removeChild(parent.firstChild);
}
}
const container = document.querySelector('#container');
removeAllChildNodes(container);

You can remove everything from the container before appending :
function submit() {
let select = document.querySelector('#modelsList');
let value = select.options[select.selectedIndex].value;
let container = document.querySelector('.container');
container.innerHTML = '';
[...]
or you can change src of image without appending new image
document.querySelector('#btn').addEventListener('click', submit);
const images = {
mba:'https://ag-spots-2021.o.auroraobjects.eu/2021/07/26/mercedes-amg-cla-45-c117-c479326072021173956_1.jpg?1627314027',
mbc:'https://ireland.apollo.olxcdn.com/v1/files/eyJmbiI6IjM1bXk3dTVtcTd1OC1BVVRPVklUUk8iLCJ3IjpbeyJmbiI6InE3bXo1M2JpZnB6ay1BVVRPVklUUk8iLCJzIjoiMTYiLCJwIjoiMTAsLTEwIiwiYSI6IjAifV19.dxCeoriV-0ygVtEXaXgFFvuomnzNmndAS1G5qVVYqaM/image;s=1080x720',
mbe:'https://ireland.apollo.olxcdn.com/v1/files/eyJmbiI6IjdjYzZ2cm84NjNrcS1BVVRPVklUUk8iLCJ3IjpbeyJmbiI6InE3bXo1M2JpZnB6ay1BVVRPVklUUk8iLCJzIjoiMTYiLCJwIjoiMTAsLTEwIiwiYSI6IjAifV19.5PJ743A4FPdZuZkRpYhJh9g96i1AASth2X4nBJXS0oU/image;s=644x461',
mbs:'https://www.cars-data.com/pictures/mercedes/mercedes-benz-g-class_4266_24.jpg',
mbeq:'https://www.cars-data.com/pictures/mercedes/mercedes-benz-g-class_4266_24.jpg',
default:'https://mercedesblog.com/wp-content/uploads/2019/06/mercedes-eqe.jpg'
}
function submit() {
let select = document.querySelector('#modelsList');
let value = select.options[select.selectedIndex].value;
let container = document.querySelector('.container');
const img = document.querySelector('#img');
if(images.hasOwnProperty(value)) {
img.setAttribute('src', images[value]);
} else {
img.setAttribute('src', images.default);
}
}
<label for="cars" id="carInput" name="carInput"/>
<select id="modelsList">
<option value="mba">Mercedes-Benz A Class</option>
<option value="mbc">Mercedes-Benz C Class</option>
<option value="mbe">Mercedes-Benz E Class</option>
<option value="mbs">Mercedes-Benz S Class</option>
<option value="mbeq">Mercedes-Benz EQE Class</option>
<option value="mbeqs">Mercedes-Benz EQS Class</option>
</select>
<button id="btn">submit</button>
<div class="container">
<img id="img"/>
</div>

I suggest changing about the way you think of the relationship between the HTML and the JS. The former is the presentation layer, the latter is the logic layer. It makes little sense to include presentation information in your business logic, if you can help it. Right now, if you want to make changes to the way this select works (for example, adding new images or changing existing images) you have to change the JS as well as the HTML.
You could change your code to the following:
document.querySelector('#btn').addEventListener('click', submit);
function submit() {
let select = document.querySelector('#modelsList');
let value = select.options[select.selectedIndex].value;
let containerImg = document.querySelector('#container-img');
containerImg.hidden = false;
containerImg.src = value;
}
This allows you to add any number of future image options without having to touch the code. This makes some assumptions about the HTML. You would have to change it like this:
<label for="cars" id="carInput" name="carInput">
<select id="modelsList">
<option value="image1.png">Mercedes-Benz A Class</option>
<option value="image2.png">Mercedes-Benz C Class</option>
</select>
<button id="btn">submit</button>
</label>
<div class="container">
<img hidden src="" id="container-img" />
</div>

Add this div element.
<div id="container"></div>
Change container variable.
let container = document.getElementById('container');
Add innerHTML method before your if statement.
container.innerHTML=""; //<-------------- This will clear your div before appending your new image
if (value === 'mba') { //Note: I have not changed the if statement
container.appendChild(aImg);
} else if (value === 'mbc') {
container.appendChild(cImg)
} else if (value === 'mbe') {
container.appendChild(eImg);
} else if (value === 'mbs') {
container.appendChild(sImg);
} else if (value === 'mbeq') {
container.appendChild(eqImg);
} else {
container.appendChild(eqeImg);
}

Related

How to change the text-content of an html-element as soon as a new option was selected?

I am trying to change a span element when a new option is selected in Javascript.
This is the html code:
<span id="month"></span>
(...)
<option id="plan_option".....
And this is my javascript code that currently just displays a text in when the page loads:
window.onload = function month_freq() {
var id = document.getElementById("plan_option").value;
var freq = '';
if (id == 5144746){
freq = 'ogni mese';
} else{
freq = 'ogni due mesi';
}
document.getElementById("month").innerHTML = freq;
}
So, should I make a new function that is called when option changes or idk.
Any help is appreciated, thanks!
EDIT
So, I try to set it in more context and update it to the current status.
My goal here is to tell the client, relative to the plan that he chooses, on which basis will he pay (monthly or two monthly).
Thanks to #Peter Seliger I updated the code, so I now have this:
Liquid/HTML(1):
<select name="plan_select" id="plan_select">
{% for plan in selling_plan_group.selling_plans %}
<option id="plan_option" data-billing-frequency="{% if plan.id == 5144746 %}ogni mese{% else %}ogni due mesi{% endif %}" value="{{ plan.id }}">{{ plan.options[0].value }}</option>
{% endfor %}
</select>
HTML(2):
<span id="month"></span>
Javascript:
function displayBoundBillingFrequency(evt) {
const elementSelect = evt.currentTarget;
if (elementSelect) {
const selectedOption = elementSelect[elementSelect.selectedIndex];
// `this` equals the bound billing-frequency display-element.
this.textContent = (selectedOption.dataset.billingFrequency || '');
}
}
function mainInit() {
const planOptions = document.querySelector('#plan_select');
const frequencyDisplay = document.querySelector('#month');
if (planOptions && frequencyDisplay) {
const displayBillingFrequency = displayBoundBillingFrequency.bind(frequencyDisplay);
// synchronize display data initially.
displayBillingFrequency({
currentTarget: planOptions,
});
// initialize event listening/handling
planOptions.addEventListener('change', displayBillingFrequency);
}
}
mainInit();
But it still doesn't work. Thanks.
One just wants to listen to the changes of a select element.
Thus one somehow needs to identify this very select element and not so much each of its option elements. The latter one's then do not need to feature either a name- or an id-attribute but a value-attribute instead.
Then one does implement an event handler which does read the currently selected option's value and also does write this very value to the desired/related html-element.
One also needs to provide the event listening/handling to the formerly mentioned select element.
In addition one wants to synchronize the default selected value with the displaying element at load/render time.
Note
For security reasons one does not really want to render a text value via innerHTML ... in this case a textContent write access does the job just fine.
function handleMonthOptionChangeForRelatedDisplay(evt) {
const elementDisplay = document.querySelector('#month');
const elementSelect = evt.currentTarget;
if (elementDisplay && elementSelect) {
const elementSelect = evt.currentTarget;
const selectedIndex = elementSelect.selectedIndex;
elementDisplay.textContent = elementSelect[selectedIndex].value
}
}
function initMonthOptionChange() {
const elementSelect = document.querySelector('#month-options');
elementSelect.addEventListener('change', handleMonthOptionChangeForRelatedDisplay);
}
// window.onload = function () {
// handleMonthOptionChangeForRelatedDisplay({
// currentTarget: document.querySelector('#month-options')
// });
// initMonthOptionChange();
// }
handleMonthOptionChangeForRelatedDisplay({
currentTarget: document.querySelector('#month-options')
});
initMonthOptionChange();
<select name="plan_option" id="month-options">
<option value=""></option>
<option value="Ogni Mese">ogni mese</option>
<option value="Ogni due Mesi" selected>ogni due mesi</option>
</select>
<p id="month"></p>
In case the OP has to render an option-specific text-value different from the option element's value-attribute there was still the approach of providing this information via an option-specific data-attribute in order to keep the handler-implementation as generic (without any additional and case-specific compare-logic) as possible ...
function displayBoundBillingFrequency(evt) {
const elementSelect = evt.currentTarget;
if (elementSelect) {
const selectedOption = elementSelect[elementSelect.selectedIndex];
// `this` equals the bound billing-frequency display-element.
this.textContent = (selectedOption.dataset.billingFrequency || '');
}
}
function mainInit() {
const planOptions = document.querySelector('#plan-options');
const frequencyDisplay = document.querySelector('#plan-billing-frequency');
if (planOptions && frequencyDisplay) {
const displayBillingFrequency = displayBoundBillingFrequency.bind(frequencyDisplay);
// synchronize display data initially.
displayBillingFrequency({
currentTarget: planOptions,
});
// initialize event listening/handling
planOptions.addEventListener('change', displayBillingFrequency);
}
}
mainInit();
<select name="plan_option" id="plan-options">
<option value=""></option>
<option value="541758" data-billing-frequency="ogni mese" selected>First Option</option>
<option value="752649" data-billing-frequency="ogni due mesi">Second Option</option>
<option value="invalid">Invalid Option</option>
</select>
<p id="plan-billing-frequency"></p>
You should check HTMLElement: change event
var planSelectElem = document.getElementById("plan_select"); // <select id="plan_option_select"></select>
planSelectElem.onchange = month_freq;
// OR
planSelectElem.addEventListener("change", month_freq);

onChange function stops after one click, what code do I need to write so that it continues indefinitely? (Javascript)

change = function(event) {
let new_url;
if (event.target.value == "views") {
new_url = "images/desert.jpg";
} else if (event.target.value == "beaches") {
new_url = "images/beach-calm.jpg";
} else if (event.target.value == "party") {
new_url = "images/plane-wing.jpg";
}
let image_two = document.getElementById("image-two");
if (new_url && image_two.src.indexOf("images/second-main-image.png") != -1) {
image_two.src = new_url;
}
}
<select id="select-one" class="suggestion-dropbox" name="likes" onchange="change(event)">
<option id="default" value="default"> </option>
<option id="views" value="views">stunning views</option>
<option id="beaches" value="beaches">glorious white beaches</option>
<option id="party" value="party">places to party</option>
</select>
I have a dropdown menu and when a different option is clicked I want an image on the page to change with it. I have managed to make it do this however only does it once and stops after that. I've added the code so far below.
Do I need to make it a while loop and if so how would I structure it? Thanks for any help
Your second function definition is replacing the first one, so you only update the image when you select beaches.
You need one function that checks for both options.
It only works one time because you only change the image when it contains images/second-main-image.png. After you've selected something from the menu, that's no longer true. You should remove that check.
And if you want to go back to the default when the user selects the default option, add a case for that.
change = function(event) {
let new_url;
if (event.target.value == "views") {
new_url = "images/desert.jpg";
} else if (event.target.value == "beaches") {
new_url = "images/beach-calm.jpg";
} else {
new_url = ("images/second-main-image.png");
}
let image_two = document.getElementById("image-two");
image_two.src = new_url;
}
<select id="select-one" class="suggestion-dropbox" name="likes" onchange="change(event)">
<option id="default" value="default"> </option>
<option id="views" value="views">stunning views</option>
<option id="beaches" value="beaches">glorious white beaches</option>
<option id="party" value="party">places to party</option>
</select>
<img id="image-two" src="images/second-main-image.png">

How to change to default the selected dropdown [duplicate]

I have the following HTML <select> element:
<select id="leaveCode" name="leaveCode">
<option value="10">Annual Leave</option>
<option value="11">Medical Leave</option>
<option value="14">Long Service</option>
<option value="17">Leave Without Pay</option>
</select>
Using a JavaScript function with the leaveCode number as a parameter, how do I select the appropriate option in the list?
You can use this function:
function selectElement(id, valueToSelect) {
let element = document.getElementById(id);
element.value = valueToSelect;
}
selectElement('leaveCode', '11');
<select id="leaveCode" name="leaveCode">
<option value="10">Annual Leave</option>
<option value="11">Medical Leave</option>
<option value="14">Long Service</option>
<option value="17">Leave Without Pay</option>
</select>
Optionally if you want to trigger onchange event also, you can use :
element.dispatchEvent(new Event('change'))
If you are using jQuery you can also do this:
$('#leaveCode').val('14');
This will select the <option> with the value of 14.
With plain Javascript, this can also be achieved with two Document methods:
With document.querySelector, you can select an element based on a CSS selector:
document.querySelector('#leaveCode').value = '14'
Using the more established approach with document.getElementById(), that will, as the name of the function implies, let you select an element based on its id:
document.getElementById('leaveCode').value = '14'
You can run the below code snipped to see these methods and the jQuery function in action:
const jQueryFunction = () => {
$('#leaveCode').val('14');
}
const querySelectorFunction = () => {
document.querySelector('#leaveCode').value = '14'
}
const getElementByIdFunction = () => {
document.getElementById('leaveCode').value='14'
}
input {
display:block;
margin: 10px;
padding: 10px
}
<select id="leaveCode" name="leaveCode">
<option value="10">Annual Leave</option>
<option value="11">Medical Leave</option>
<option value="14">Long Service</option>
<option value="17">Leave Without Pay</option>
</select>
<input type="button" value="$('#leaveCode').val('14');" onclick="jQueryFunction()" />
<input type="button" value="document.querySelector('#leaveCode').value = '14'" onclick="querySelectorFunction()" />
<input type="button" value="document.getElementById('leaveCode').value = '14'" onclick="getElementByIdFunction()" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
function setSelectValue (id, val) {
document.getElementById(id).value = val;
}
setSelectValue('leaveCode', 14);
Not answering the question, but you can also select by index, where i is the index of the item you wish to select:
var formObj = document.getElementById('myForm');
formObj.leaveCode[i].selected = true;
You can also loop through the items to select by display value with a loop:
for (var i = 0, len < formObj.leaveCode.length; i < len; i++)
if (formObj.leaveCode[i].value == 'xxx') formObj.leaveCode[i].selected = true;
I compared the different methods:
Comparison of the different ways on how to set a value of a select with JS or jQuery
code:
$(function() {
var oldT = new Date().getTime();
var element = document.getElementById('myId');
element.value = 4;
console.error(new Date().getTime() - oldT);
oldT = new Date().getTime();
$("#myId option").filter(function() {
return $(this).attr('value') == 4;
}).attr('selected', true);
console.error(new Date().getTime() - oldT);
oldT = new Date().getTime();
$("#myId").val("4");
console.error(new Date().getTime() - oldT);
});
Output on a select with ~4000 elements:
1 ms
58 ms
612 ms
With Firefox 10. Note: The only reason I did this test, was because jQuery performed super poorly on our list with ~2000 entries (they had longer texts between the options).
We had roughly 2 s delay after a val()
Note as well: I am setting value depending on the real value, not the text value.
document.getElementById('leaveCode').value = '10';
That should set the selection to "Annual Leave"
I tried the above JavaScript/jQuery-based solutions, such as:
$("#leaveCode").val("14");
and
var leaveCode = document.querySelector('#leaveCode');
leaveCode[i].selected = true;
in an AngularJS app, where there was a required <select> element.
None of them works, because the AngularJS form validation is not fired. Although the right option was selected (and is displayed in the form), the input remained invalid (ng-pristine and ng-invalid classes still present).
To force the AngularJS validation, call jQuery change() after selecting an option:
$("#leaveCode").val("14").change();
and
var leaveCode = document.querySelector('#leaveCode');
leaveCode[i].selected = true;
$(leaveCode).change();
Short
This is size improvement of William answer
leaveCode.value = '14';
leaveCode.value = '14';
<select id="leaveCode" name="leaveCode">
<option value="10">Annual Leave</option>
<option value="11">Medical Leave</option>
<option value="14">Long Service</option>
<option value="17">Leave Without Pay</option>
</select>
The easiest way if you need to:
1) Click a button which defines select option
2) Go to another page, where select option is
3) Have that option value selected on another page
1) your button links (say, on home page)
<a onclick="location.href='contact.php?option=1';" style="cursor:pointer;">Sales</a>
<a onclick="location.href='contact.php?option=2';" style="cursor:pointer;">IT</a>
(where contact.php is your page with select options. Note the page url has ?option=1 or 2)
2) put this code on your second page (my case contact.php)
<?
if (isset($_GET['option']) && $_GET['option'] != "") {
$pg = $_GET['option'];
} ?>
3) make the option value selected, depending on the button clicked
<select>
<option value="Sales" <? if ($pg == '1') { echo "selected"; } ?> >Sales</option>
<option value="IT" <? if ($pg == '2') { echo "selected"; } ?> >IT</option>
</select>
.. and so on.
So this is an easy way of passing the value to another page (with select option list) through GET in url. No forms, no IDs.. just 3 steps and it works perfect.
function foo(value)
{
var e = document.getElementById('leaveCode');
if(e) e.value = value;
}
Suppose your form is named form1:
function selectValue(val)
{
var lc = document.form1.leaveCode;
for (i=0; i<lc.length; i++)
{
if (lc.options[i].value == val)
{
lc.selectedIndex = i;
return;
}
}
}
Should be something along these lines:
function setValue(inVal){
var dl = document.getElementById('leaveCode');
var el =0;
for (var i=0; i<dl.options.length; i++){
if (dl.options[i].value == inVal){
el=i;
break;
}
}
dl.selectedIndex = el;
}
Why not add a variable for the element's Id and make it a reusable function?
function SelectElement(selectElementId, valueToSelect)
{
var element = document.getElementById(selectElementId);
element.value = valueToSelect;
}
Most of the code mentioned here didn't worked for me!
At last, this worked
window.addEventListener is important, otherwise, your JS code will run before values are fetched in the Options
window.addEventListener("load", function () {
// Selecting Element with ID - leaveCode //
var formObj = document.getElementById('leaveCode');
// Setting option as selected
let len;
for (let i = 0, len = formObj.length; i < len; i++){
if (formObj[i].value == '<value to show in Select>')
formObj.options[i].selected = true;
}
});
Hope, this helps!
You most likely want this:
$("._statusDDL").val('2');
OR
$('select').prop('selectedIndex', 3);
If using PHP you could try something like this:
$value = '11';
$first = '';
$second = '';
$third = '';
$fourth = '';
switch($value) {
case '10' :
$first = 'selected';
break;
case '11' :
$second = 'selected';
break;
case '14' :
$third = 'selected';
break;
case '17' :
$fourth = 'selected';
break;
}
echo'
<select id="leaveCode" name="leaveCode">
<option value="10" '. $first .'>Annual Leave</option>
<option value="11" '. $second .'>Medical Leave</option>
<option value="14" '. $third .'>Long Service</option>
<option value="17" '. $fourth .'>Leave Without Pay</option>
</select>';
I'm afraid I'm unable to test this at the moment, but in the past, I believe I had to give each option tag an ID, and then I did something like:
document.getElementById("optionID").select();
If that doesn't work, maybe it'll get you closer to a solution :P

How to run a piece of javascript when you select a dropdown option?

I have a select with loads of options. (Code below shortened for sake of example).
I want it to set the value of the input textfield "hoh" to "10" when you click/select all dropdown options, except one, that should set it to 50.
I imagined something like this would work, but its not. What am I doing wrong here?
<select>
<option onselect="document.getElementById('hoh').value = '50'">Hey</option>
<option onselect="document.getElementById('hoh').value = '10'">Ho</option>
<option onselect="document.getElementById('hoh').value = '10'">Lo</option>
....
</select>
<input type="text" id="hoh" value="10">
Something like this should work:
<script>
function myFunc(val) {
if (val == '50') {
document.getElementById('hoh').value = val;
} else {
document.getElementById('hoh').value = '10';
}
}
</script>
<select onchange="myFunc(this.value)">
<option value="1">one</option>
<option value="2">two</option>
<option value="50">fifty</option>
</select>
http://jsfiddle.net/isherwood/LH57d/3
The onselect event refers to selecting (or highlighting) text. To trigger an action when a dropbox selection changes, use the onchange event trigger for the <select> element.
E.g. Since you didn't already set the value attribute of your option tags.
<select id="myselect" onchange="myFunction()">
<option value="50">Hey</option>
<option value="10">Ho</option>
<option value="10">Lo</option>
....
</select>
and somewhere inside of a <script> tag (presumably in your HTML header) you define your javascript function.
<script type="text/javascript>
function myFunction() {
var dropbox = document.getElementById('myselect');
document.getElementById('hoh').value = dropbox[dropbox.selectedIndex].value;
}
</script>
I'm not sure it's wise to repeat the same value among different options in a droplist, but you could expand on this to implement the result other ways, such as if the sole option which will have value 50 is in a certain position, you could compare the selectedIndex to that position.
you could add an onchange event trigger to the select, and use the value of an option to show in the textbox
see http://jsfiddle.net/Icepickle/5g5pg/ here
<select onchange="setValue(this, 'hoh')">
<option>-- select --</option>
<option value="10">Test</option>
<option value="50">Test 2</option>
</select>
<input type="text" id="hoh" />
with function setValue as
function setValue(source, target) {
var tg = document.getElementById(target);
if (!tg) {
alert('No target element found');
return;
}
if (source.selectedIndex <= 0) {
tg.value = '';
return;
}
var opt = source.options[source.selectedIndex];
tg.value = opt.value;
}
Try this code
var inp = document.getElementById('hoh');
sel.onchange = function(){
var v = this.value;
if( v !== '50'){
v = '10';
}
inp.value = v;
};

How to click on a button, and have the item in question go to the next list using javascript?

I have this problem. I have two lists. One with the items of my fridge (that's the assignment :) ) and other with the items of the shop. I want to be able to click on an item of the fridge, and have it show up on the list of the left. In javascript, that is.
If anyone knows how to do it, I'd be very glad to hear from you.
Daniel
Using JavaScript:
function get(id) {
return document.getElementById(id);
}
document.addEventListener('click', function(event) {
event = event || window.event;
if (event) {
var el = event.target,
ePa = el.parentNode,
htm = "";
if (String(ePa.id) === "list1") {
htm = el.parentNode.removeChild(el);
get("list2").appendChild(htm);
} else if (String(ePa.id) === "list2") {
htm = el.parentNode.removeChild(el);
get("list1").appendChild(htm);
}
}
}, false);
Example here: http://fiddle.jshell.net/Shaz/EEfhh/
I wrote this - before I saw the Homework tag.
Would have been nice to see what you had already done before I did your assignment for you
<script>
var shopItems = [];
function addShop(theForm) {
var sel = theForm.fridge;
if (sel.selectedIndex < 1) return;
var opt = sel.options[sel.selectedIndex]
if (shopItems[opt.text]) return
shopItems[opt.text]=opt.value;
theForm.shop.options[theForm.shop.options.length]=new Option(opt.text,opt.value);
theForm.shop.options[theForm.shop.options.length-1].selected=true;
}
</script>
<form>
<select name="fridge" >
<option value="">Please select</option>
<option value="cheese">Cheese</option>
<option value="butter">Butter</option>
</select>
<input type="button" onclick="addShop(this.form)" value=" >>> ">
<select name="shop" >
<option value="">Please select</option>
</select>
</form>

Categories