Show Content of Selected Options - javascript

I'd like to show the content of the selected options in the span tags with corresponding id's.
So when you choose Chocolate as your ice cream flavor and Caramel as your topping, the text at the bottom will change to:
"I love Chocolate ice cream with Caramel".
<ul id="icecream" style="list-style:none;line-height:30px;">
<li>
<select id="icecream">
<option value="vanilla">Vanilla</option>
<option value="chocolate">Chocolate</option>
<option value="strawberry">Strawberry</option>
</select>
</li>
<li>
<select id="topping">
<option value="sprinkles">Sprinkles</option>
<option value="chocolatedip">Chocolate Dip</option>
<option value="caramel">Caramel</option>
</select>
</li>
<li>I love <span id="icecreamFlavor"></span> ice cream with <span id="toppingFlavor"></span>.</li>
</ul>
Does anyone know of a javascript that can do this?
Update:
- Without using jQuery.
- Vanilla, Chocolate, Strawberry, Sprinkles, Chocolate Dip, and Caramel don't have to be displayed in bold.
- The first option in the select list is shown as default. I.e.:
"I love Vanilla ice cream with Sprinkles".

Add the following code in javascript
$('#icecream').change(function(){
$('#icecreamFlavor').text($(this).val());
});
$('#topping').change(function(){
$('#toppingFlavor').text($(this).val());
});
Add the following code in css
#icecreamFlavor, #toppingFlavor{
font-weight:bold;
font-style:italic;
}

Here's one way:
<!doctype html>
<html>
<head>
<script>
// wait for DOM content to finish loading
window.addEventListener( 'DOMContentLoaded', function DOMContentLoaded() {
// no need to listen anymore
this.removeEventListener( 'DOMContentLoaded', DOMContentLoaded );
// get the DOM elements
var icecream = document.getElementById( 'icecream' );
var topping = document.getElementById( 'topping' );
var icecreamFlavor = document.getElementById( 'icecreamFlavor' );
var toppingFlavor = document.getElementById( 'toppingFlavor' );
// define an event listener that changes our output based on the selected options
var onSelectChange = function( event ) {
icecreamFlavor.textContent = icecream.options[ icecream.selectedIndex ].textContent;
toppingFlavor.textContent = topping.options[ topping.selectedIndex ].textContent;
}
// listen for the change events with the event listener
icecream.addEventListener( 'change', onSelectChange );
topping.addEventListener( 'change', onSelectChange );
// initialize our output
onSelectChange();
} );
</script>
</head>
<body>
<ul style="list-style:none;line-height:30px;">
<li>
<select id="icecream">
<option value="vanilla">Vanilla</option>
<option value="chocolate">Chocolate</option>
<option value="strawberry">Strawberry</option>
</select>
</li>
<li>
<select id="topping">
<option value="sprinkles">Sprinkles</option>
<option value="chocolatedip">Chocolate Dip</option>
<option value="caramel">Caramel</option>
</select>
</li>
<li>I love <span id="icecreamFlavor"></span> ice cream with <span id="toppingFlavor"></span>.</li>
</ul>
</body>
</html>
fiddle demo
P.S.: Your <ul> had a conflicting id (icecream), so I had to remove it.

Updated Answer
Updated Javascript Demo
Change your 'ul' element id as 'iceCreamList' as there should be unique ids for html elements to identify them. Try this,
function selectIceCream(that){
var iceCreamType = that.options[that.selectedIndex].text;
document.getElementById('icecreamFlavor').innerHTML = iceCreamType;
};
function selectToppings(that){
var toppingType = that.options[that.selectedIndex].text;
document.getElementById('toppingFlavor').innerHTML = toppingType;
};
Also, you should consider placing the default options in your select list.

Related

Cannot get the Selected Value from Materialize dropdown with React JS

I have this Materialize DropDown
<ul id="dropdown1" className="dropdown-content">
<li>
<a href="#!">
one
</a>
</li>
<li>
two
</li>
<li className="divider" tabIndex="-1"></li>
<li>
three
</li>
<li>
<a href="#!">
<i className="material-icons">view_module</i>four
</a>
</li>
<li>
<a href="#!">
<i className="material-icons">cloud</i>five
</a>
</li>
</ul>
and I have declared it as follows :-
componentDidMount() {
let dropdowns = document.querySelectorAll('.dropdown-trigger');
let options = {
inDuration: 300,
outDuration: 300,
hover: true, // Activate on hover
coverTrigger: false, // Displays dropdown below the button
};
M.Dropdown.init(dropdowns, options);
var instance = M.Dropdown.getInstance(dropdowns);
}
which displays fine, however I cannot manage to get the selected value.
I tried the following JQuery:-
$(document).ready(function(){
$('dropdown1').formSelect();
});
but I am getting a type error :-
TypeError: jquery__WEBPACK_IMPORTED_MODULE_6___default(...)(...).formSelect is not a function
Any help will be very much appreciated!
Thanks
I think one should use <Select> in case of a form to select from a list of options. So, you can initialize the Materialize components in componentDidMount() lifecycle method.
I attached onChange event listener on <Select> so that we can track the value and save it in our state. I also gave the defaultValue property so that a person knows in form what he has to choose, for example, Choose a country.
CodeSandbox - Working Demo (Select in React)
Select Component
import React, { Component } from "react";
import M from "materialize-css";
import "materialize-css/dist/css/materialize.min.css";
class Select extends Component {
constructor() {
super();
this.state = {
selectVal: null
};
}
componentDidMount() {
M.FormSelect.init(this.FormSelect);
}
handleChange = event => {
this.setState({
[event.target.name]: event.target.value
});
};
render() {
console.log(this.state.selectVal);
return (
<div className="input-field col s12">
<select
ref={FormSelect => {
this.FormSelect = FormSelect;
}}
name="selectVal"
onChange={this.handleChange}
defaultValue="0"
>
<option value="0" disabled>
Choose your option
</option>
<option value="1">Option 1</option>
<option value="2">Option 2</option>
<option value="3">Option 3</option>
</select>
<label>Materialize Select</label>
</div>
);
}
}
export default Select;

How to remove element in jquery sortable?

My HTML Code is like this :
<div class="content">
box 1 (Customer)
<ol class='example mauDIDROP vertical'>
<li>Valentino Rossi</li>
<li>David Beckham</li>
<li>Eden Hazard</li>
<li>Lionel Messi</li>
<li>Christiano Ronaldo</li>
<li>Frank Lampard</li>
</ol>
</div>
<div class="content">
<form id="myForm" action="" method="POST">
box 2 (Room Type)
<br>
<select id="room_type">
<option value="1">Single Room</option>
<option value="2">Double Room</option>
<option value="3">Twin Room</option>
</select>
<input type="button" value="Add" style="margin-top: -10px;" id="add_room">
<ol class="example areaDROP vertical" id="room_list">
<li class="room_number msg1" id="room_remove11">Deluxe Room<div class="room-remove"><i class="fa fa-times"></i></div><ol><li id="room_remove21">John Terry<div class="room-remove"><i class="fa fa-times"></i></div></li></ol></li>
<li class="room_number msg1" id="room_remove12">Family Room<div class="room-remove"><i class="fa fa-times"></i></div><ol><li id="room_remove22">Jose Mourinho<div class="room-remove"><i class="fa fa-times"></i></div></li></ol></li>
</ol>
<button type="submit">Save</button>
</form>
</div>
My Javascript is like this :
function delete_room(id){
$('#room_remove'+id).remove();
}
$(document).ready(function(){
$("ol.mauDIDROP").sortable({
group: '.example'
});
$("ol.areaDROP").sortable({
group: '.example',
});
var room_type_number = 5;
$('#add_room').click(function(){
var text = $("#room_type option:selected").html();
var room_type_id = $.trim($('#room_type').val());
$('#room_list').append('<li class="room_number msg" id="room_remove'+(++room_type_number)+'" data-id="'+room_type_id+'" data-name="'+text+'">'+text+'<div class="room-remove"><i class="fa fa-times"></i></div><ol></ol></li>');
$("ol.mauDIDROP").sortable({
group: '.example'
});
$("ol.areaDROP").sortable({
group: '.example',
});
});
});
Demo is like this : https://jsfiddle.net/oscar11/4wnfnz6z/1/
When I click on the close icon, the selected element successfully deleted.
But what I want:
When I click on the close icon, the selected element removed and deleted customer element appears in box 1.
For example : http://imgur.com/rEzryt3
When I click on the close icon(deluxe room), it will look like this : http://imgur.com/YpkBTKH
How to keep deleted customer element in moving towards the box 1?
Any suggestion to solve my problem?
Thank you
You can change a bit your delete_room function so it would grab the names of customers from the room you are removing and then append them as lis to your left container:
function delete_room(id){
var customers = '';
$('#room_remove'+id).find('li').each( function() {
customers += '<li>'+$(this).text()+'</li>';
});
$('#room_remove'+id).remove();
$('ol.example.mauDIDROP.vertical').append(customers);
}
Check fiddle: Fiddle
This approach have better performance, cause you are setting the find to a var and doing a loop instead of doind a loop with the find.
var child = $('#room_remove'+id).find('li');
if(child.length > 0){
var li = "";
child.each(function(){
li += "<li>"+$(this).text()+"</li>";
});
}
$(".mauDIDROP").append($(li));

jQuery show and hide dynamic classes not working

I am trying to hide and show div's displayed on my page with a select element however having a bit of trouble as I can't seem to get the jQuery to function.
I am listing results from my SQL table using PHP that currently displays every row onto my page and prints them into a list.
I want to make the jQuery hide the div's that don't have a class that matches the select option that is selected.
Here is an example of the listing template that echo's out all of the MySQL results and displays them into a template and is then looped to display every row on the table:
<?php while($row = $results->fetch(PDO::FETCH_ASSOC))
{
echo '
<div class="listing-container ' . $row["Make"] . '">
<h3 class="model-listing-title clearfix">'.$row["Make"].' '.$row["Model"].' '.$row["Variant"].'</h3>
<h3 class="price-listing">£'.number_format($row['Price']).'</h3>
</div>
<div class="listing-container-spec">
<img src="'.(explode(',', $row["PictureRefs"])[0]).'" class="stock-img-finder"/>
<div class="ul-listing-container">
<ul class="overwrite-btstrp-ul">
<li class="diesel-svg list-svg">'.$row["FuelType"].'</li>
<li class="saloon-svg list-svg">'.$row["Bodytype"].'</li>
<li class="gear-svg list-svg">'.$row["Transmission"].'</li>
<li class="color-svg list-svg">'.$row["Colour"].'</li>
</ul>
</div>
<ul class="overwrite-btstrp-ul other-specs-ul h4-style">
<li>Mileage: '.number_format($row["Mileage"]).'</li>
<li>Engine size: '.$row["EngineSize"].'cc</li>
</ul>
<button href="#" class="btn h4-style checked-btn hover-listing-btn"><span class="glyphicon glyphicon-ok"></span> History checked
</button>
<button href="#" class="btn h4-style more-details-btn hover-listing-btn tst-mre-btn"><span class="glyphicon glyphicon-list"></span> More details
</button>
<button href="#" class="btn h4-style test-drive-btn hover-listing-btn tst-mre-btn"><span class="test-drive-glyph"></span> Test drive
</button>
<h4 class="h4-style listing-photos-count"><span class="glyphicon glyphicon-camera"></span> 5 More photos</h4>
</div>
';
} ?>
The 'Make' is added to the listing-container div to add a class to be able to filter the results with jQuery.
Here is the form with the select element I am using:
<form>
<select class="form-control select-box">
<option value="make-any">Make (Any)</option>
<?php while($make = $filterres->fetch(PDO::FETCH_ASSOC))
{
echo '
<option>'.$make["Make"].'</option>
';
} ?>
</select>
<select class="form-control last-select select-box">
<option value="model-any">Model (Any)</option>
<option value="two">Two</option>
<option value="three">Three</option>
<option value="four">Four</option>
<option value="five">Five</option>
</select>
</form>
As you can see the select option contains the 'Make' and is looped.
So down to the jQuery:
<script>//Wait for DOM to load
(function() {
$(“.select-box”).change( function() {
// get the value of the select element
var make = $(this).val();
//get all of the listing-container divs, remove the ones with the selected make class, then hide the rest
$(“.listing-container”).not(“.” + make).hide();
});
});</script>
So in theory this should work but for some reason it isn't, can anybody notice anything that might be wrong?
I have placed my script below the core jQuery in my footer and it still doesn't work.
Here is a live example: http://www.drivencarsales.co.uk/used-cars.php
Looks like you're using the wrong quotes in the source code of that page try replacing them with "
//Wait for DOM to load
$(function() {
$(".select-box").change( function() {
// get the value of the select element
var make = $(this).val();
//get all of the listing-container divs, remove the ones with the selected make class, then hide the rest
$(".listing-container").not("." + make).hide().next().hide();
});
});
Edit
You also need a $ before the function
If I understand you correctly ↓ working code ↓
$(function() {
$('.select-box').on("change",function() {
var make = this.value;
$('div.listing-container.'+make+",div.listing-container."+make+" + div.listing-container-spec").show();
$('div.listing-container:not(.'+make+'),div.listing-container:not(.'+make+') + div.listing-container-spec').hide();
});
});
And shorter code (but slower):
$(function() {
$('.select-box').on("change",function() {
var make = this.value;
$('.listing-container.'+make+",.listing-container."+make+" + div").show();
$('.listing-container:not(.'+make+'),.listing-container:not(.'+make+') + div').hide();
});
});
P.S.You miss value attribute (but in live example everything ok):
echo '<option value="'.$make["Make"].'">'.$make["Make"].'</option>';

Hide element after this select box by change

I am working on a time table where users can update their opening hours.
I have select boxes per day with 'open' or 'closed', and after this time select boxes with 'from' and 'till'.
I want to make it so if a user select for example wednesday: 'closed', the till and from select boxes (list items in this .time_row) are hiding.
My HTML for each day:
<div class="time_row">
<label>Monday:</label>
<li>
<select>
<option value="open">Open</option>
<option value="closed">Closed</option>
</select>
</li>
<li>
From:
</li>
<li>
<select>
<option value="00:00">00:00</option>
<option value="01:00">01:00</option>
etc
</select>
</li>
<li>
Till:
</li>
<li>
<select>
<option value="00:00">00:00</option>
<option value="01:00">01:00</option>
etc
</select>
</li>
</div><!--End time_row-->
I have tried to make it with jQuery .slice() but then he hides all list elements after this select box and before?
// Account time table
$('.time_row select').change( function() {
if( $(this).val() == 'closed' ) {
$('.time_row li').slice(3).hide();
}
});
Can someone help me with this?
Thank you!
I assume you are looking for something like that:
$('.time_row').find('select:first').change(function() {
$(this)
.closest('.time_row')
.find('li')
.slice(1)
.toggle(this.value === 'open');
}).change();
In this case on change event you search for the <select> closest parent element with class .time_row. Then pick up all inner <li> elements, remove the first from the list with slice(1) and either show or hide the rest upon the condition this.value === 'open'.
You should also check your markup and put all <li> elements inside <ul> to make it valid.
In the updated answer I have included the correct selector to select only first <select> elements (ignoring time selectors) and added the by default state with triggering change event after binding.
DEMO: http://jsfiddle.net/mPNCA/1/
You can do (untested):
$(".time_row select:first").change(function() {
if (this.value == "closed") {
$(this).closest(".time_row").find("select").not(this).hide();
}
});

Highlight Corresponding Names With Javascript

I have a list of names to display in a browser:
Alan, Ben, Cindy, Dan, Ellen, Fred.
I'd like the user to be able to select male or female.
Then I'd like the name(s) of people who are that gender to change colors, or become highlighted.
Is there a way to do this with JavaScript?
If i understand you correctly, you can do following:
// step 1 create list of names with classes
<ul>
<li class="person male">Alan</li>
<li class="person male">Ben</li>
<li class="person female">Cindy</li>
</ul>
// step 2 create dropdown list of genders
<select id="my-dropdown-id" name="gender">
<option value="male">Male</option>
<option value="female">Female</option>
</select>
// step 3 simple jQuery script
<script type="text/javascript">
$('#my-dropdown-id').change(function() {
$('.person').removeClass('selected');
$('.' + this.value).addClass('selected');
});
</script>
<style>
.selected{
background: yellow;
}
</style>
This is a very simple solution, though i believe it implements your idea at least theoretically.

Categories

Resources