I have a very simple question, I have tried searching forums but I've not been able to find what I think I need. Below is a bit of script which works as I expect:
$(function(){
var ProjType = $("#cfs_i3_cf3");
$(ProjType).change(function() {
$("#cfs_h3").css("background-color", "red");
alert('okay then!');
});
});
Basically, the ID #cfs_i3_cf3 represents a drop-down box and when it changes, the colour changes.
I want to advance this a little and say:
If #cfs_i3_cf3 = A then color = X otherwise color = Y
Very simple, but struggling with the syntax and hopefully it's a very simple answer as I'm not used to javascript.
Many thanks in advance!
James
The correct approach to do this is:
You listen for changes in the select box and then on its change get the select box's value and if it is one then color the paragraph red else yellow.
$(function(){
var ProjType = $("#cfs_i3_cf3");
$(ProjType).change(function(){
if($(this).val() == "1")
{
$("#cfs_h3").css("background-color", "red");
}
else
{
$("#cfs_h3").css("background-color", "yellow");
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="cfs_i3_cf3">
<option value="" selected disabled>Select</option>
<option value="1">One</option>
<option value="2">Two</option>
</select>
<p id="cfs_h3">THIS IS THE OUTPUT</p>
Just to add additional refactor. Sorry! I simply think jQuery is doing to same thing but why load extra library?
function switchColor(select){
var redOrNot = select.value == 'red' ? true: false;
var el = document.getElementById('cfs_h3');
if (redOrNot) {
el.style.backgroundColor = select.value;
} else {
el.style.backgroundColor = select.value;
}
}
/* if you don't need logic, you can simply do
el.style.backgroundColor = select.value; since the color logic
is already embedded in the HTML.
*/
<select id="cfs_i3_cf3" onchange="switchColor(this)">
<option value="" selected disabled>Select</option>
<option value="red">One</option>
<option value="yellow">Two</option>
</select>
<p id="cfs_h3">THIS IS THE OUTPUT</p>
Related
So I have a very basic HTML form, and I'm trying to figure out how to run a JS function if a user selects a specific with a specific value, inside of an HTML element. I'm very, very new to coding so forgive me if it looks awful; But something like this, where say I want the background to turn red when an option with the value "two" is selected:
HTML:
<select id="numberDropdown">
<option disabled selected>0</option>
<option value="one">1</option>
<option value="two">2</option>
<option value="three">3</option>
</select>
JavaScript:
document.getElementById("numberDropdown").value = document.getElementById("numberDropdown").selectedIndex.value;
if (document.getElementById("numberDropdown").value = "two"){
document.body.style.backgroundColor = "red";
};
I really don't know any java script, just tried to type something so you can understand the question. Thanks for any help!
This should get updated everytime a new value is selected
const selectElement = document.getElementById("numberDropdown");
selectElement.addEventListener('change', (event) => {
let val = selectElement.options[selectElement.selectedIndex].value;
if (val == "two"){
document.body.style.backgroundColor = "red";
}
});
You can use a button to handle an event and get the value of the selected index of selector.
const btn = document.querySelector('#btn');
const selector = document.querySelector('#numberDropdown');
btn.onclick = (event) => {
event.preventDefault();
console.log(selector.selectedIndex)
if (selector.selectedIndex == 2){
document.body.style.backgroundColor = "red";
}
};
<select id="numberDropdown">
<option disabled selected>0</option>
<option value="one">1</option>
<option value="two">2</option>
<option value="three">3</option>
</select>
<button id="btn">Get number</button>
You can wrap your javascript code in a function and use onchange attribute on the select tag. So whenever the select tag's value changes, your fuction will execute.
function changeColour() {
let selectElement = document.getElementById("numberDropdown")
let selectedValue = selectElement.options[selectElement.selectedIndex].value;
if (selectedValue === "two"){
document.body.style.backgroundColor = "red"
}
}
and you can change your html to
<select id="numberDropdown" onchange="changeColour()">
<option disabled selected>0</option>
<option value="one">1</option>
<option value="two">2</option>
<option value="three">3</option>
</select>
There are numerous ways to do it, as far as I know this is the simplest way.
The following code uses select2 to allo multiple selection from a dropdown. My question is how can I show a "x selected" after third choice, instead of all the choices and have a huge textbox?
<select multiple id="e1" style="width:300px">
<option value="AL">Alabama</option>
<option value="Am">Amalapuram</option>
<option value="An">Anakapalli</option>
<option value="Ak">Akkayapalem</option>
<option value="WY">Wyoming</option>
</select>
$("#e1").select2();
I have a jSfiddle here
http://jsfiddle.net/ishanbakshi/fyhsz9ra/
I have worked hard and managed to supply a jQuery solution for you. Change your JavaScript to this:
$("#e1").select2();
$(document).ready(function(){
var showHugeSelect = false;
$("#s2id_e1 ul.select2-choices").prepend("<button id='btnE1ShowAll' style='display: none;' />")
$("#btnE1ShowAll").click(function(e){
$("#s2id_e1 .select2-search-choice").show();
$("#btnE1ShowAll").hide();
showHugeSelect = true;
function hideHugeSelect(){
showHugeSelect = false;
}
setTimeout(hideHugeSelect, 5000);
})
setInterval(customizeSelectE1, 500);
function customizeSelectE1(){
var selectedCount = $("#s2id_e1 .select2-search-choice").length;
if(selectedCount > 2 && !showHugeSelect){
$("#s2id_e1 .select2-search-choice").hide();
$("#btnE1ShowAll").html(selectedCount + " selected").show();
}
}
})
I've checked it in the jsFiddle and it works perfectly. It's not possible to make a more elegant solution. If you really want a more elegant one, you need either to develop your own control or change the source code of Select2.
I have created a fiddle . Try this way..
$("#e1").select2().on('change', function() {
if ($(this).val().length >= 3) {
var html = $('.select2-choices li:first-child').clone();
$('.select2-choices li:not(:last-child)').remove();
var divContent = html.find('div').html($(this).val().length + ' Selected');
$('.select2-choices').prepend(html).find('a').on('click', function() {
$(this).parent('li').remove();
$("#e1").val('');
});
}
});
I found an answer to my question here but it really doesn't work for me. I am very new to programming and quite not yet familiar using javascript. Sad to say, I've been trying to do this for quite a while.
What I want to do is to change the background of a div whenever I change the option in a select tag. Here's my .JSP code
Add Ons Type:
<select id="addOnsType" name="addOnsType" onchange="changePicture()">
<option selected disabled> select add ons</option>
<c:forEach var="addOnsType" items="${addOnsType}">
<option value="${addOnsType.addOnsTypeId}"> ${addOnsType.description} </option>
</c:forEach>
</select>
<div id="PictureDiv" style="height: 58px; width: 344px">
</div>
The addOnsTypeId has values of 1, 2 and 3.
While my javascript is written as (I've used what I saw in here)
function changePicture() {
var PictureDivBG = document.getElementById("PictureDiv");
var addOnsTypeSelected = document.getElementById("addOnsType");
if (addOnsTypeSelected.val() == 1) {
PictureDivBG.style.backgroundImage = "url('../images/cartoon1.jpg')";
} else if (addOnsTypeSelected.val() == 2) {
PictureDivBG.style.backgroundImage = "url('../images/cartoon2.jpg')";
} else if (addOnsTypeSelected.val() == 3) {
PictureDivBG.style.backgroundImage = "url('../images/cartoon3.jpg')";
}
};
Any help/hints/answers would be much appreciated. Thanks!
Follow up newbie question: I'm quite confused about javascript and jQuery, what's the difference?
addOnsTypeSelected is a dom element reference, it doesn't have the val() function, which is provided by jQuery.
You can get the jQuery object for those element using the id selector and get the value
function changePicture() {
var addOnsTypeSelected = $("#addOnsType").val(),
backgroundImage;
if (addOnsTypeSelected == 1) {
backgroundImage = "url('../images/cartoon1.jpg')";
} else if (addOnsTypeSelected == 2) {
backgroundImage = "url('../images/cartoon2.jpg')";
} else if (addOnsTypeSelected == 3) {
backgroundImage = "url('../images/cartoon3.jpg')";
}
$('#PictureDiv').css('background-image', backgroundImage);
};
But using jQuery event handlers, you can
jQuery(function() {
var imgs = {
1: 'url(//placehold.it/64/ff0000)',
2: 'url(//placehold.it/64/00ff00)',
3: 'url(//placehold.it/64/0000ff)'
}
$('#addOnsType').change(function() {
$('#PictureDiv').css('background-image', imgs[$(this).val()] || 'none');
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Add Ons Type:
<select id="addOnsType" name="addOnsType">
<option selected disabled>select add ons</option>
<option>1</option>
<option>2</option>
<option>3</option>
</select>
<div id="PictureDiv" style="height: 58px; width: 344px">
</div>
I have the following code that does not seem to work:
$('.chosen-select').on('change', function() {
if ('.chosen-select'.value == '1') {
$("#tips").html("the color that you want to add.");
} else if ('.chosen-select'.value == '2') {
$("#tips").html("the text that you want to add.");
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<div id="tips"></div>
<select class="chosen-select" style="width:290px;" name="option">
<option value="1">change background colour</option>
<option value="2">insert text</option>
<option value="3">insert arrow</option>
</select>
My web browser console is not giving me any error. The code is suppose to change the html of the div based on changing the select option value.
This '.chosen-select'.value won't work as it's neither a valid jQuery expression nor JavaScript. Instead use $('.chosen-select').val(), this.value or $(this).val().
jsFiddle example
Use if($(this).val() == '1') { not as if('.chosen-select'.value == '1')
$(function() {
$('.chosen-select').on('change', function() {
if($(this).val() == '1') {$("#tips").html( "the color that you want to add.");}
else if($(this).val() == '2') {$("#tips").html( "the text that you want to add.");}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<div id="tips"></div>
<select class="chosen-select" style="width:290px;" name="option">
<option value="1">change background colour</option>
<option value="2">insert text</option>
<option value="3">insert arrow</option>
</select>
The below expression doesn't yield the results you want:
'.chosen-select'.value
It attempts to access the value property of a String object, which is undefined, because strings don't have such properties.
Within the change event handler function, you can make good use of the fact that this references the <select> element:
var selectedValue = this.value; // get value from select element
Alternatively, use jQuery's .val() function to get the value:
var selectedValue = $(this).val();
How do you take a value of an option in a select form and use it for a if else statement?
for example if apple is selected as an option then write to the document how to make applesauce but orange is selected then write how to make orange?
so far I have a basic form and select options and I know how to do the document.write but I dont know how to use a select form with if else
thanks for the help
First, make sure you have an id on your <select> allowing you to reference it from Javascript:
<select id="fruits">...</select>
Now, you can use the options and selectedIndex fields on the Javascript representation of your <select> to access the current selected value:
var fruits = document.getElementById("fruits");
var selection = fruits.options[fruits.selectedIndex].value;
if (selection == "apple") {
alert("APPLE!!!");
}
var select = document.getElementById('myList');
if (select.value === 'apple') {
/* Applesauce */
} else if (select.value === 'orange') {
/* Orange */
}
Your HTML markup
<select id="Dropdown" >
<option value="Apple">Apple</option>
<option value="Orange">Orange</option>
</select>
Your JavaScript logic
if(document.getElementById('Dropdown').options[document.getElementById('Dropdown').selectedIndex].value == "Apple") {
//write applesauce
}
else {
//everything else
}
Alternatively you can do this.
var fruitSelection = document.formName.optionName; /* if select has been given an name AND a form have been given a name */
/* or */
var fruitSelection = document.getElementById("fruitOption"); /* If <select> has been given an id */
var selectedFruit = fruitSelection.options[fruitSelection.selectedIndex].value;
if (selectedFruit == "Apple") {
document.write("This is how to make apple sauce....<br />...");
} else {
}
//HTML
<!-- For the 1st option mentioned above -->
<form name="formName">
<select name="optionName> <!-- OR -->
<select id="optionName">
<option value="Apple">Apple</option>
<option value="Pear">Pear</option>
<option value="Peach">Peach</option>
</select>
</form>