html form using javaScript to call out some function - javascript

I'm a beginner and I'm try to set up a form. I have written the html/css code. What I wanted to do is to click on a level of study such as Bachelors, I want all the courses under bachelors to display in the second box (choose course) while hiding the rest of the courses in the box.
label {
font-family: sans-serif;
font-size: 1rem;
padding-right: 10px;
}
select {
font-size: .9rem;
padding: 2px 5px;
}
<h2>This is a form</h2>
<p>Online Application:</p>
<form id="form1" action="#">
<label for="school-select">Choose levels of study:</label>
<select id="level-select">
<option value="">--Please choose an option--</option>
<option value="bachelor">Bachelors</option>
<option value="postgraduates">Postgraduates</option>
<option value="phd">PhD</option>
</select>
</form>
<br>
<form id="form2" action="#">
<label for="course-select">Choose course:</label>
<select id="cour">
<optgroup label="Bachelors">
<option>Microbiology</option>
<option>chemistry</option>
<option>physics</option>
</optgroup>
<optgroup label="Postgraduates">
<option>computer</option>
<option>biology</option>
<option>accounting</option>
</optgroup>
<optgroup label="PhD">
<option>business</option>
<option>fisheries</option>
<option>agric</option>
</optgroup>
</select>
</form>

Here, I've come up with a simple solution to this. I've changed your html a little bit. I've set the same values as their optgroup's label so that we can choose the specific optgroup for being shown. So the solution is simple:
Hide all the options of the second box.
Show the one by courses.querySelector('[label="' + value + '"]'); this, where value is your first box's selected value.
Have a look at the code snippet below:
function getLevels() {
var value = document.getElementById("level-select").value;
if (value) {
var courses = document.querySelector("#cour");
var all_options = courses.querySelectorAll('optgroup');
var show_courses = courses.querySelector('[label="' + value + '"]');
all_options.forEach(function (element) {
element.style.display = "none";
});
show_courses.style.display = "block";
}
}
<h2>This is a form</h2>
<p>Online Application:</p>
<form id="form1" action="#">
<label for="school-select">Choose levels of study:</label>
<select id="level-select" onchange="getLevels()">
<option value="">--Please choose an option--</option>
<option value="Bachelors">Bachelors</option>
<option value="Postgraduates">Postgraduates</option>
<option value="PhD">PhD</option>
</select>
</form>
<br>
<form id="form2" action="#">
<label for="course-select">Choose course:</label>
<select id="cour">
<option selected>--Choose Course--</option>
<optgroup label="Bachelors">
<option>Microbiology</option>
<option>chemistry</option>
<option>physics</option>
</optgroup>
<optgroup label="Postgraduates">
<option>computer</option>
<option>biology</option>
<option>accounting</option>
</optgroup>
<optgroup label="PhD">
<option>business</option>
<option>fisheries</option>
<option>agric</option>
</optgroup>
</select>
</form>

Just add onClick event in <option> tag?
<option onClick="myFunction()">Microbiology</option>
<script>
function myFunction() {
//do what you want..
}
</script>```

Add a onchange event to the select field, and push the value to a function like;
<select id="level-select" onchange="setLevel(this.value)">
Hide all option groups in css;
#cour optgroup {
display:none;
}
Give all option groups a unique ID containing the value of the first select, like;
<optgroup label="Bachelors" id="course_bachelor">
And now the function for the onchange event could be something like this;
function setLevel (val) {
var elements = document.getElementsByTagName('optgroup');
// Loop through all elements and check if they are hidden or shown
for(var i=0; i < elements.length; i++) {
if (elements[i].id === 'course_' + val) {
elements[i].style.display = 'block';
} else {
elements[i].style.display = 'none';
}
}
}

label {
font-family: sans-serif;
font-size: 1rem;
padding-right: 10px;
}
select {
font-size: .9rem;
padding: 2px 5px;
}
<h2>This is a form</h2>
<p>Online Application:</p>
<form id="form1" action="#">
<label for="school-select">Choose levels of study:</label>
<select id="level-select">
<option value="">--Please choose an option--</option>
<option value="bachelor">Bachelors</option>
<option value="postgraduates">Postgraduates</option>
<option value="phd">PhD</option>
</select>
<br>
<label for="course-select">Choose course:</label>
<select id="cour">
</select>
</form>
var select = document.getElementById("level-select");
select.onchange(() => {
if(select.value == 'bachelor') {
document.getElementById("cour").value == "<optgroup label="Bachelors">
<option>Microbiology</option>
<option>chemistry</option>
<option>physics</option>
</optgroup>"
}
})
Do this for all the conditions.

You'll need to use some Javascript to do this. Here's one solution that could work for you.
I've updated some of your html names (first dropdown values to exactly match the 'optgroup' labels in your second dropdown). Also added some CSS to have the options for the courses dropdown to not show until you've selected a valid option, which prevents the user from, say, going back to change the first dropdown value while the second dropdown value stays the same. Always 'idiot-proof' your UI:
//grab both dropdowns and store in variable
var levelSelectDropdown = document.querySelector('#level-select');
var coursesDropdown = document.querySelector('#cour');
//create an on 'change' event for first dropdown
levelSelectDropdown.addEventListener('change', levelDropdownChange);
function levelDropdownChange(e){
var selectedLevelOfStudy = e.target.value;
var coursesGroups = coursesDropdown.querySelectorAll('optgroup');
//this basically hides the 'default' empty option that's auto-selected
//by default
coursesDropdown.querySelector('option[value="default"]').style.display = 'none';
//loop through all 'optgroup' items in second dropdown (coursesGroups)
coursesGroups.forEach(function(element){
//default course dropdown to first element (this essentially resets
//the course dropdown each time level of study dropdown is changed
coursesDropdown.selectedIndex = 0;
//make sure all optgroups are hidden
element.style.display = 'none';
//only display optgroup whose label matches the value selected
//from first dropdown
if(element.getAttribute('label') == selectedLevelOfStudy){
element.style.display = 'block';
}
})
}
label {
font-family: sans-serif;
font-size: 1rem;
padding-right: 10px;
}
select {
font-size: .9rem;
padding: 2px 5px;
}
#cour optgroup {
display:none;
}
<h2>This is a form</h2>
<p>Online Application:</p>
<form id="form1" action="#">
<label for="school-select">Choose levels of study:</label>
<select id="level-select">
<option value="">--Please choose an option--</option>
<option value="bachelors">Bachelors</option>
<option value="postgraduates">Postgraduates</option>
<option value="phd">PhD</option>
</select>
</form>
<br>
<form id="form2" action="#">
<label for="course-select">Choose course:</label>
<select id="cour">
<option value="default"></option>
<optgroup label="bachelors">
<option>Microbiology</option>
<option>chemistry</option>
<option>physics</option>
</optgroup>
<optgroup label="postgraduates">
<option>computer</option>
<option>biology</option>
<option>accounting</option>
</optgroup>
<optgroup label="phd">
<option>business</option>
<option>fisheries</option>
<option>agric</option>
</optgroup>
</select>
</form>

label {
font-family: sans-serif;
font-size: 1rem;
padding-right: 10px;
}
select {
font-size: .9rem;
padding: 2px 5px;
}
<h2>This is a form</h2>
<p>Online Application:</p>
<form id="form1" action="#">
<script lang="javascript">
function onLevelofStudyChange()
{
var selectedLevel=document.getElementById("level-select").value;
var course = document.querySelector("#cour");
var alloption = course.querySelectorAll('optgroup')
var getByLabel = course.querySelector('[label="'+selectedLevel+'"]');
//Hide all Optgroups
alloption.forEach(function(element){
element.style.display = "none";
});
if(getByLabel!=null)
getByLabel.style.display = "block";
}
</script>
<label for="school-select">Choose levels of study:</label>
<select id="level-select" onchange="onLevelofStudyChange()">
<option value="">--Please choose an option--</option>
<option value="bachelor">Bachelors</option>
<option value="postgraduates">Postgraduates</option>
<option value="phd">PhD</option>
</select>
</form>
<br>
<form id="form2" action="#">
<label for="course-select">Choose course:</label>
<select id="cour">
<option>--Please Choose course--</option>
<optgroup label="bachelor" style="display:none">
<option>Microbiology</option>
<option>chemistry</option>
<option>physics</option>
</optgroup>
<optgroup label="postgraduates" style="display:none">
<option>computer</option>
<option>biology</option>
<option>accounting</option>
</optgroup>
<optgroup label="phd" style="display:none">
<option>business</option>
<option>fisheries</option>
<option>agric</option>
</optgroup>
</select>
</form>
Try this, it should work also note I have changed Optgroup label inorder to match the value of first dropdown

Related

Change bootstrap multiselect values based on another select options, using jquery

I have a simple form created using HTML and JS. There are 3 select elements that the options of the second and the third select elements are based on the first select option. The HTML code is below.
<div class="d-flex flex-column">
<label>City</label>
<select name="city" class="city" id="city-selection">
<option selected="selected" value="">Select City</option>
<option value="City 1">City 1</option>
<option value="City 2">City 2</option>
<option value="City 3">City 3</option>
<option value="City 4">City 4</option>
<option value="City 5">City 5</option>
<option value="City 6">City 6</option>
<option value="City 7">City 7</option>
</select>
</div>
<div class="d-flex flex-column">
<label>Hotel</label>
<select name="hotel" class="hotel" id="hotel-selection">
<option selected="selected" value="">Select Hotel</option>
</select>
</div>
<div class="d-flex flex-column">
<label>Tours</label>
<select name="tour" class="tour" id="tour-selection" multiple="multiple">
<option selected="selected" value="">Select Tours</option>
</select>
</div>
The first(#city-selection) and the second(#hotel-selection) select elements are just normal ones. But I changed the third(#tour-selecton) select element as a Bootstrap multi-select element. So the JS part is below.
//City 1 options
var city1Hotels = '<option selected="selected" value="">Select Hotel</option><option value="City 1 Hotel 1">City 1 Hotel 1</option>';
//City 2 options
var city2Hotels = '<option selected="selected" value="">Select Hotel</option><option value="City 2 Hotel 1">City 2 Hotel 1</option>';
var city2Tours = '<option selected="selected" value="">Select Tours</option><option value="City 2 Tour 1">City 2 Tour 1</option><option value="City 2 Tour 2">City 2 Tour 2</option>';
var cityS = $("select#city-selection");
var hotelS = $("select#hotel-selection");
var tourS = $("select#tour-selection");
//changing second and third select elements options based on first select element
$(document).ready(function(){
cityS.on('change',function(){
if($(this).val()=="City 1"){
hotelS.html(city1Hotels); //for hotel results based on a city
}
else if($(this).val()=="City 2"){
hotelS.html(city2Hotels); //for hotel results based on a city
tourS.html(city2Tours); //for tour results based on a city
}
});
});
//set multiselect on third select element
$(function() {
"use strict";
$(document).ready(function() {
$('#tour-selection').multiselect({
includeSelectAllOption: false,});
});
});
The Issue
When I select a city from #city-selection, the #hotel-selection show results properly based on the city entries. But when it comes to #tour-selection, it doesn't show me tours when I selected a city. However, if I remove the multi-select function it shows me all the tours based on the cities. But then the user can select only one option. So it's not my intention and I think the issue with the multi-select. Currently, I have used if-else to change decisions based on the cities. If someone can help me, I'll be much appreciated it!
For More information:
I used this documentation to add bootstrap multi-select. https://davidstutz.github.io/bootstrap-multiselect/
When I add custom options to the third(#tour-selection) select element using HTML to check it, the multi-select feature works properly. But decision-based selection still not working.
I have edited your javascript code using an array of objects to set the data for cities, hotels, and tours to make them dynamically render options
Html
<div class="d-flex flex-column">
<label>City</label>
<select name="city" class="city" id="city-selection">
<option selected="selected" value="">Select City</option>
</select>
</div>
<div class="d-flex flex-column">
<label>Hotel</label>
<select name="hotel" class="hotel" id="hotel-selection">
<option selected="selected" value="">Select Hotel</option>
</select>
</div>
<div class="d-flex flex-column">
<label>Tours</label>
<select name="tour" class="tour" id="tour-selection" multiple="multiple">
<option selected="selected" value="">Select Tours</option>
</select>
</div>
Javascript
//City Options
var cities = ["city-1", "city-2"];
// Hotel options based on cities
var hotels = [
{
city: "city-1",
hotels: ["hotel-1", "hotel-2"],
},
{
city: "city-2",
hotels: ["hotel-1", "hotel-2"],
},
];
// Tour options based on Cities
var tours = [
{
city: "city-1",
tours: ["tour-1", "tour-2"],
},
{
city: "city-2",
tours: ["tour-1", "tour-2"],
},
];
var citySelect = $("select#city-selection");
var hotelSelect = $("select#hotel-selection");
var tourSelect = $("select#tour-selection");
// render city options
for (i in cities) {
if (i == 0) {
// first option with "Select City" as the selected option
citySelect.html(
`<option selected="selected" value="">Select City</option>`
);
citySelect.append(
`<option value="${cities[i]}">${cities[i]}</option>`
);
} else {
// the rest of the options
citySelect.append(
`<option value="${cities[i]}">${cities[i]}</option>`
);
}
}
// changing both hotel options and tour options based on selected city
$(document).ready(function () {
citySelect.on("change", function () {
// render hotel options based on selected city
for (i in hotels) {
if ($(this).val() == hotels[i]["city"]) {
console.log(hotels[i]["city"]);
// first option
hotelSelect.html(
`<option selected="selected" value="">Select Hotels</option>`
);
hotels[i]["hotels"].forEach((hotel) => {
hotelSelect.append(
`<option value="${hotels[i]["city"]}-${hotel}">${hotels[i]["city"]}-${hotel}</option>`
);
});
}
}
// render tour options based on selected city
for (i in tours) {
if ($(this).val() == tours[i]["city"]) {
console.log(tours[i]["city"]);
// first option
tourSelect.html(
`<option selected="selected" value="">Select tours</option>`
);
tours[i]["tours"].forEach((hotel) => {
tourSelect.append(
`<option value="${tours[i]["city"]}-${hotel}">${tours[i]["city"]}-${hotel}</option>`
);
});
}
}
});
tourSelect.on("change", function () {
console.log($(this).val())
})
});
Finally I figure out I can't working with Bootstrap multi-select. That because of it won't let custom JS code replace it's current options in select elements. Otherwise bootstrap-multiselect is a great way to create checkboxes in select elements. There may be a way to override that. But I'm unable to find a way to do that. However I found a another method to fulfill my needs without using Bootstrap multi-select and select element. This answer contains several code lines of multiple stackoverflow answers.
Those answers are,
How to create checkbox inside dropdown?
How to replace all the <li> elements of an <ul> using JQuery?
HTML
First I replace the select element with ul list element as shown in below code.
<div class="d-flex flex-column">
<label>City</label>
<select name="city" class="city" id="city-selection">
<option selected="selected" value="">Select City</option>
<option value="City 1">City 1</option>
<option value="City 2">City 2</option>
<option value="City 3">City 3</option>
<option value="City 4">City 4</option>
<option value="City 5">City 5</option>
<option value="City 6">City 6</option>
<option value="City 7">City 7</option>
</select>
</div>
<div class="d-flex flex-column">
<label>Hotel</label>
<select name="hotel" class="hotel" id="hotel-selection">
<option selected="selected" value="">Select Hotel</option>
</select>
</div>
<div class="d-flex flex-column">
<div id="list1" class="dropdown-check-list">
<label>Select Tours</label>
<span class="anchor">Select Tours</span>
<ul class="tours" id="tour-list">
</ul>
</div>
</div>
CSS
CSS code for dropdown.
.dropdown-check-list {
display: inline-block;
}
.dropdown-check-list .anchor {
position: relative;
cursor: pointer;
display: inline-block;
padding: 5px 50px 5px 10px;
border: 1px solid #ccc;
}
.dropdown-check-list .anchor:after {
position: absolute;
content: "";
border-left: 2px solid black;
border-top: 2px solid black;
padding: 5px;
right: 10px;
top: 20%;
-moz-transform: rotate(-135deg);
-ms-transform: rotate(-135deg);
-o-transform: rotate(-135deg);
-webkit-transform: rotate(-135deg);
transform: rotate(-135deg);
}
.dropdown-check-list .anchor:active:after {
right: 8px;
top: 21%;
}
.dropdown-check-list ul.tours {
padding: 2px;
display: none;
margin: 0;
border: 1px solid #ccc;
border-top: none;
}
.dropdown-check-list ul.tours li {
list-style: none;
}
.dropdown-check-list.visible .anchor {
color: #0094ff;
}
.dropdown-check-list.visible .tours {
display: block;
}
JS and JQuery
var city1Tours = ["c1 Tour1","c1 Tour2"];
var city2Tours = ["c2 Tour1","c2 Tour2"];
var city1Hotels = '<option selected="selected" value="">Select Hotel</option><option value="City 1 Hotel 1">City 1 Hotel 1</option>';
var city2Hotels = '<option selected="selected" value="">Select Hotel</option><option value="City 2 Hotel 1">City 1 Hotel 1</option>';
//tour list dropdown js code
var checkList = document.getElementById('list1');
checkList.getElementsByClassName('anchor')[0].onclick = function(evt) {
if (checkList.classList.contains('visible'))
checkList.classList.remove('visible');
else
checkList.classList.add('visible');
}
//hotel selection based on user city decision js code
$(document).ready(function(){
cityS.on('change',function(){
if($(this).val()=="City 1"){
hotelS.html(city1Hotels);
//Tour selection based on the city
$("#tour-list").empty();//This line clears current li contents
$.each(city1Tours, function( key, value ) {
$('#tour-list').append('<li>' + '<input type="checkbox" />' + value + '</li>');
});
}else if($(this).val()=="City 2"){
hotelS.html(city2Hotels);
//Tour selection based on the city
$("#tour-list").empty();//This line clears current li contents
$.each(city2Tours, function( key, value ) {
$('#tour-list').append('<li>' + '<input type="checkbox" />' + value + '</li>');
});
}
});
});
Hope this answer helps someone in future.

How do I hide the select tag based on Js iteration of a list

I had a challenge getting this question but tried to research and redo it.
I'm trying to get an item in a list from a controller, then iterate through the list. Based on the content of the array, I would like to show or hide the select that has options in it. I can't seem to hide or show any of them at the moment.
var names = ['marketing']; //or ['business']
var text = "";
var i;
//$(document).ready(function() {
for (i = 0; i < names.length; i++) {
if (names[i] === 'business') {
//alert('Hooray');
$("#business").show("slow");
$(".marketing").hide("fast");
} else
if (names[i] === 'marketing') {
$("#marketing").show("slow");
$(".marketing").hide("fast");
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="all" id="note">
Some content will be posted here...
</div>
<select id="marketing" multiple>
<option value="1">Definition</option>
<option value="2">Advertise</option>
<option value="3">Promotion</option>
</select>
<select id="business" multiple>
<option value="1">Definition</option>
<option value="2">Buy</option>
<option value="3">Sell</option>
</select>
If your array contains the exact name of the id you can "hide" the elements with CSS and show them with two lines of javascript
var names = ['marketing'];//or ['business']
names.forEach( name => {
$('#' + name).show('slow')
});
select {
display: none;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="all" id="note">
Some content will be posted here...
</div>
<select id="marketing" multiple>
<option value="1">Definition</option>
<option value="2">Advertise</option>
<option value="3">Promotion</option>
</select>
<select id="business" multiple>
<option value="1">Definition</option>
<option value="2">Buy</option>
<option value="3">Sell</option>
</select>

Open Another Input Text when the user selects an option

I am a newbie and I have this project where the user should have the option of custom input if the listed options are not in dropdown.
HTML
<div class="form-group">
<label class="col-sm-2 col-form-label">Select Page Size</label>
<select name = 'pageSelector' class="col-sm-3">
<option value ="">Select Page Size</option>
<option value ="84.1|118.9">A0</option>
<option value = "59.4|84.1">A1</option>
<option value = "7.4|10.5">A7</option>
<option value = "custom">Select Custom</option>
</select>
</div>
PHP
if(isset($_POST["pageSelector"]))
{
$result = $_POST['pageSelector'];
if($result == "")
{
echo "<script>alert('Please select the Page')</script>";
}
$result_explode = explode('|', $result);
$width_page = $result_explode[0];
$height_page = $result_explode[1];
// Converting the string variables to integer
$width_plate=(double)$width_plate;
$height_plate=(double)$height_plate;
$width_page=(double)$width_page;
$height_page=(double)$height_page;
// To calculate the number of pages that can be print with one selected plate
$calculated_width = $width_plate/$width_page;
$calculated_height = $height_plate/$height_page;
$print_include = (int)$calculated_height*(int)$calculated_width;
echo "<div class='h1'>Number of Prints in one plate ".$print_include." prints</div> ";
}
I would like if the user selects the custom option then a input text should appear on the screen.
If user selected a custom option then you can give him an input.
let selectEl = document.getElementById('select-list');
selectEl.addEventListener('change', (e) => {
if (e.target.value == 'custom') {
document.getElementById('txt-custom').style.display = 'block';
} else {
document.getElementById('txt-custom').style.display = 'none';
}
});
#txt-custom {
display: none;
}
<select id="select-list">
<option value="">Select an option</option>
<option value="1">Option 1</option>
<option value="2">Option 2</option>
<option value="custom">Custom</option>
</select>
<input type="text" id="txt-custom" name="custom-value" />
var pageSelector = document.getElementById('pageSelector');
var customInput = document.getElementById('customInput');
pageSelector.addEventListener('change', function(){
if(this.value == "custom") {
customInput.classList.remove('hide');
} else {
customInput.classList.add('hide');
}
})
.hide {
width: 0;
height: 0;
opacity: 0;
}
<div class="form-group">
<label class="col-sm-2 col-form-label">Select Page Size</label>
<select name = 'pageSelector' class="col-sm-3 page" id="pageSelector">
<option value ="">Select Page Size</option>
<option value ="84.1|118.9">A0</option>
<option value = "59.4|84.1">A1</option>
<option value = "7.4|10.5">A7</option>
<option value = "custom">Select Custom</option>
</select>
<input type="text" class="hide" placeholder="Custom Selector" name="custom" id="customInput">
</div>
Demo Code :
First you should have input with style="display:none" and with jQuery
jQuery(document).ready(function() {
jQuery("#selectId").change(function() {
if (jQuery(this).val() === 'custom'){
jQuery('input[name=other_input]').show();
} else {
jQuery('input[name=other_input]').hide();
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<select name = 'pageSelector' class="col-sm-3" id="selectId" >
<option value ="">Select Page Size</option>
<option value ="84.1|118.9">A0</option>
<option value = "59.4|84.1">A1</option>
<option value = "7.4|10.5">A7</option>
<option value = "custom">Select Custom</option>
</select>
<br><br><br>
<input type="text" name="other_input" style="display:none" />
Angular Version
Angular CLI: 13.0.3
Node: 16.15.0
Package Manager: npm 8.5.5
In .html File
**<div class="col-md-6">
<label class="form-label">Attendence Type</label>
<select (change)="type($event)" class="form-select" aria-label="Default select example" >
<option selected value="P">Present</option>
<option value="A">Absent</option>
<option value="PL">Paid Leave</option>
<option value="UL">Unpaid Leave</option>
</select>
</div>**
I want to Show this input after select paid leave
**<div *ngIf="plFlag" class="col-md-6">
<label class="form-label">Leave Type</label>
<select class="form-select" aria-label="Default select example">
<option selected disabled>Leave Type</option>
<option value="CL">Causel Leave</option>
<option value="SL">Seek Leave</option>
</select>
</div>**
and in .ts File
**type(event: any) {
console.log(event.target.value);
if (event.target.value == "PL") {
this.plFlag = true;
}
else {
this.plFlag = false;
}
}**

Change CSS color from select list option

I'm trying to change css based on a select list options, what am I doing wrong?
Help is much appreciated! (I can't change the HTML)
Many thanks.
Erwin
$("select").change(function() {
var color = $("#5f01264e722ae").val();
$("#sw_poster_text2").css("background", color);
});
.sw_poster_text2 {
margin: 30px;
background: white;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="wapf-field-input">
<select data-is-required="" data-field-id="5f01264e722ae" name="wapf[field_5f01264e722ae]" class="wapf-input">
<option value="">choose an option</option>
<option value="0z489" data-wapf-label="black">black </option>
<option value="wu4xz" data-wapf-label="brown">brown </option>
<option value="5k848" data-wapf-label="blue">blue </option>
</select>
</div>
<div class="sw_poster_text2">My name</div>
Use $(this).find('option:selected').data('wapf-label') to get the value of the select and use . instead of # to select elements with a particular class.
var color = $(this).find('option:selected').data('wapf-label')
$(".sw_poster_text2").css("background", color);
$("select").change(function() {
var color = $(this).find('option:selected').data('wapf-label')
$(".sw_poster_text2").css("background", color);
});
.sw_poster_text2 {
margin: 30px;
background: white;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="wapf-field-input">
<select data-is-required="" data-field-id="5f01264e722ae" name="wapf[field_5f01264e722ae]" class="wapf-input">
<option value="">choose an option</option>
<option value="0z489" data-wapf-label="black">black </option>
<option value="wu4xz" data-wapf-label="brown">brown </option>
<option value="5k848" data-wapf-label="blue">blue </option>
</select>
</div>
<div class="sw_poster_text2">My name</div>
Your option value not is a valid color, you need set a valid color to after set in your style try this:
$("select").change(function() {
var color = $("#5f01264e722ae").val();
$("#sw_poster_text2").css("background", color);
});
.sw_poster_text2 {
margin: 30px;
background: white;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="wapf-field-input">
<select data-is-required="" data-field-id="5f01264e722ae" name="wapf[field_5f01264e722ae]" class="wapf-input">
<option value="">choose an option</option>
<option value="black" data-wapf-label="black">black</option>
<option value="brown" data-wapf-label="brown">brown</option>
<option value="blue" data-wapf-label="blue">blue</option>
</select>
</div>
<div class="sw_poster_text2">My name</div>

Show hidden div element based on option selected in select option element

I have a div "businessmodel" with some html element inside that is hidden by default and I want it to display when the option selected in the select option "accounttype" is provider.
Please see the code here:
JavaScript
<script type="text/javascript">
$('#accounttype').bind('change', function(event) {
var i= $('#accounttype').val();
if(i=="0")
{
$('#businessmodel').hide();
}
elseif(i=="1")
{
$('#businessmodel').show();
}
});
</script>
HTML
Account Type
<select name="type" required="" class='selector' id="accounttype" onchange="change(this)">
<option value='0'>User</option>
<option value='1'>Provider</option>
</select>
<div id="businessmodel" style="display:none;">
<p id="modellevel" >Business model</p>
<select name="model" required="" class='selector' id="model">
<option value='choose' >Choose Business Model</option>
<option value='ALPHA' >ALPHA</option>
<option value='Thecla'>Thecla</option>
<option value='Sixtus'>Sixtus</option>
<option value='Marthar'>Marthar</option>
<option value='Alma' >Alma</option>
<option value='Manuel'>Manuel</option>
<option value='Dum'>Dum</option>
<option value='Gech'>Gech</option>
<option value='Alba'>Hika</option>
<option value='Win'>Win</option>
<option value='Rex'>Rex</option>
<option value='Hika'>Hika</option>
</select>
</div>
Try this
<script type="text/javascript">
$(document).ready(function() {
$('select').change(function () {
$('.business').toggleClass('hide');
});
});
</script>
<style type="text/css">
.accounttype {
border: 1px solid;
margin: 5px;
padding: 10px;
}
.business {
border: 1px solid;
margin: 5px;
padding: 10px;
}
.hide {
display: none;
}
</style>
<div class="accounttype">
Show business model :
<select>
<option value="no">No</option>
<option value="yes">Yes</option>
</select>
</div>
<div class="business hide">
Some content goes here
</div>
Try this code.
$('#accounttype').on('change', function() {
var i = this.value;
if(i=="0")
{
$('#businessmodel').hide();
}
else
{
$('#businessmodel').show();
}
}
<select name="type" required="" class='selector' id="accounttype">
<option value='0'>User</option>
<option value='1'>Provider</option>
</select>
<div id="businessmodel" >
<p id="modellevel" >Business model</p>
<select name="model" required="" class='selector' id="model">
<option value='choose' >Choose Business Model</option>
<option value='ALPHA' >ALPHA</option>
<option value='Thecla'>Thecla</option>
<option value='Sixtus'>Sixtus</option>
<option value='Marthar'>Marthar</option>
<option value='Alma' >Alma</option>
<option value='Manuel'>Manuel</option>
<option value='Dum'>Dum</option>
<option value='Gech'>Gech</option>
<option value='Alba'>Hika</option>
<option value='Win'>Win</option>
<option value='Rex'>Rex</option>
<option value='Hika'>Hika</option>
</select>
</div>
$('#accounttype').on('change', function(event) {
var i= $('#accounttype').val();
if(i=="0")
{
$('#businessmodel').hide();
}
else
{
$('#businessmodel').show();
}
});

Categories

Resources