Changing background colour with drop down menu - html

I am doing some uni work and I am stuck on this bit of code. I have to change the background colour of the page using a drop down menu.
Drop down menu code
<form>
Background colour:
<select id= background>
<option value="White"> White </option>
<option value="Green" > Green</option>
<option value="Black"> Black </option>
</select>
if statement
<script>
function myFunction() {
var sel1 = document.getElementId('background')
if(sel1 =="Green"){
document.body.style.backgroundColor = Green
}
}
</script>
Also here is the button that runs the function
<button onclick="myFunction()">Change Background</button>

in your javascript code
"getElementId" function is wrong.
Please try below code
function myFunction() {
var sel1 = document.getElementById('background').value;
document.body.style.backgroundColor = sel1;
}

To point out your mistakes:
The id attribute of your <select> is missing quotes.
The getElementId function should be getElementById.
You need a proper JavaScript function to handle the actual change, which can be triggered by either click of a button or by the change event in the dropdown itself. I have written a snippet using the latter method, but you can fetch the selectElem from inside the function using either document.getElementById('background') or the modern document.querySelector('#background') if you are required to use a button.
If you use a valid CSS value for background-color in the value attributes of your <option>s, you can use that value without complex switch or if statements.
The this bit in our function call refers to the calling HTML element.
function updateBackgroundColour(selectElem) {
var i = selectElem.selectedIndex; // Get the selected option's index.
if (i < 0) {
return; // Nothing is selected.
}
// Set the background-color CSS attribute of the <body> element to
// the value attribute of the selected option in our <select> element.
document.body.style.backgroundColor = selectElem.options[i].value;
}
<form>
Background color:
<!-- Note the onchange attribute. "this" refers to the changing element. -->
<select id="background" onchange="updateBackgroundColour(this)">
<option value="red">Red</option>
<option value="MediumSpringGreen">Medium Spring Green</option>
<option value="#34495e">Wet asphalt</option>
</select>
<form>

function myFunction() {
var sel1 = document.getElementId('background').value;
if(sel1 =="Green"){
document.body.style.backgroundColor = "Green" ;
}
}
And this should be your html
<select id="background" onchange="myFunction() ">

Simply edit a jQuery script to display a GIF when you click on the dropdown and change the value of background image.

Related

Alert on change of select option using jQuery in console [duplicate]

is there anyway i could trigger a change event on select box on page load and select a particular option.
Also the function executed by adding the trigger after binding the function to the event.
I was trying to output something like this
<select class="check">
<option value="one">one</option>
<option value="two">two</option>
</select>
$(function(){
$('.check').trigger('change'); //This event will fire the change event.
$('.check').change(function(){
var data= $(this).val();
alert(data);
});
});
http://jsfiddle.net/v7QWd/1/
Use val() to change to the value (not the text) and trigger() to manually fire the event.
The change event handler must be declared before the trigger.
Here's a sample
$('.check').change(function(){
var data= $(this).val();
alert(data);
});
$('.check')
.val('two')
.trigger('change');
To select an option, use .val('value-of-the-option') on the select element. To trigger the change element, use .change() or .trigger('change').
The problems in your code are the comma instead of the dot in $('.check'),trigger('change'); and the fact that you call it before binding the event handler.
Another working solution for those who were blocked with jQuery trigger handler, that dosent fire on native events will be like below (100% working) :
var sortBySelect = document.querySelector("select.your-class");
sortBySelect.value = "new value";
sortBySelect.dispatchEvent(new Event("change"));
$('#edit_user_details').find('select').trigger('change');
It would change the select html tag drop-down item with id="edit_user_details".
Give links in value of the option tag
<select size="1" name="links" onchange="window.location.href=this.value;">
<option value="http://www.google.com">Google</option>
<option value="http://www.yahoo.com">Yahoo</option>
</select>
If you want to do some checks then use this way
<select size="1" name="links" onchange="functionToTriggerClick(this.value)">
<option value="">Select a Search Engine</option>
<option value="http://www.google.com">Google</option>
<option value="http://www.yahoo.com">Yahoo</option>
</select>
<script>
function functionToTriggerClick(link) {
if(link != ''){
window.location.href=link;
}
}
</script>
Based on Mohamed23gharbi's answer:
function change(selector, value) {
var sortBySelect = document.querySelector(selector);
sortBySelect.value = value;
sortBySelect.dispatchEvent(new Event("change"));
}
function click(selector) {
var sortBySelect = document.querySelector(selector);
sortBySelect.dispatchEvent(new Event("click"));
}
function test() {
change("select#MySelect", 19);
click("button#MyButton");
click("a#MyLink");
}
In my case, where the elements were created by vue, this is the only way that works.
You can try below code to solve your problem.
By default, first option select:
jQuery('.select').find('option')[0].selected=true;

How get html select > option tag custom attribute value using jquery?

I have research that in html you can add a custom attribute by simply adding data-* attribute inside html tag. I populate my select > option tag from my database:
<td>
<select onchange='setattr(this)' id='pitemnamerow"+ cnt +"' class='pitemname select2bs4 tselect'>
<option selected='selected'></option>
</select>
</td>
My Jquery and already set my custom tag
for (i in data.branditms) {
$('#pitemname'+brndid.id).append($('<option>', {
value: data.branditms[i]['item_id'],
text: data.branditms[i]['item_name'],
data-um: data.branditms[i]['um'], //custom-tag
}));
DOM result:
<select onchange="setattr(this)" id="pitemnamerow1" class="select2bs4 pitemname tselect select2-hidden-accessible" data-select2-id="pitemnamerow1" tabindex="-1" aria-hidden="true">
<option selected="selected" data-select2-id="81"></option>
<option value="0-RKM51" data-um="PC/s" data-select2-id="84">0-RING 2"DIAMETER</option>
<option value="UYD983" data-um="M" data-select2-id="84">Parts Wheel</option>
</select>
now when i try to access the custom attribute value it says undefine:
function setattr(brnditem){
var test = $(this).find('.pitemname').data('um');
console.log(test);
}
PS: My table row and select > options are also dynamic.
Any idea?
Try checking this:
var test = $(brnditem).find('option:selected').data('um');
also make sure the function was defined right before calling it on the 'select' tag
You should call data() instead attr(), rewrite you code like this :
function setattr(brnditem)
{
var test = $(brnditem).find("option:selected").data('um');
console.log(test);
}

Html DropDownList not generating events

In my web page I use something like this, but when a option is selected, onchange is not fired. I don't know where I have made a mistake. Actually my requirements is that I need to fetch location details based on the city selected, but it is not working here. Is there any other better way to do so?
#Html.DropDownList("cities", ViewBag.cities as SelectList, new { onselect = "getLoca();"});
<script type="text/javascript">
function getLoca() {
alert("yes");
$.post('#Url.Action("getLocations","Home")', { 'id': $("#cities").val() },
function (data) {
$("#loca").html(data).show();
});
}
</script>
EDIT:
This is the generated HTML code
<select id="cities" name="cities" onselect="getLoca()"><option value="0">--City-- </option>
<option value="1">City1</option>
<option value="2">City2</option>
<option value="3">City3</option>
<option value="4">City4</option>
<option value="5">City5</option>
</select>;
<select id="loca" name="loca" style="width: 170px" ></select>
Use onchange instead of onselect.
jsFiddle Demo
onselect does not do what you expect - it fires when the user selects text (you know, by dragging the mouse or holding shift and using the arrow buttons), so it is not applicable to a select box, which has no selectable text. It works on certain input elements (like text) and textareas, or you can use it on the window.
onchange fires when the value of a form element changes - so this is what you need.
Note: using inline event handlers in your HTML is not a good idea most of the time. If you can, use addEventListener instead.

getting the NAME of a select tag with javascript

I haven't found this question anywhere so I'm posting it here.
I have a bunch of select tags that are partially named using VBScript. I want to be able to get the name of a select tag that was called from the onchange event in javascript.
here is the code.
<select name="optWeeks_<%=intLineCnt%>" id = "name" onchange="changeWeek()">
<option value=""></option>
<option value="1">1</option>
<option value="2">2</option>
</select>
<SCRIPT LANGUAGE = "JavaScript">
function changeWeek(){
var chosenoption = document.getElementsByTagName("select").name
}
</SCRIPT>
The select name - "optWeeks_<%=intLineCnt%>" is optWeeks prefixed with a number
I would like to know if I can get each name of the select tag that is called? Ex. optWeeks_1, optWeeks_2 etc.
Change the call to:
... onchange="changeWeek(this);">
Then you can simply;
function changeWeek(caller) {
var chosenoption = caller.name;
}
You need to get a reference to the element. this will be one in your event handler function. You can pass it to the function you are calling from there:
onchange="var element = this; changeWeek(element)">
I included the variable assignment above for clarity, you don't need it:
onchange="changeWeek(this)">
You can then get the name from the name property on that object:
function changeWeek(element) {
var name = element.name;
I'd generally recommend binding your event handlers with JS rather than HTML, not using HTML 3.2 though:
<select name="optWeeks_<%=intLineCnt%>" id="name">
<!-- … -->
</select>
<script>
var select = document.getElementById('name');
select.addEventListener('change', changeWeek);
function changeWeek(evt) {
var name = this.name;
}
</script>
Or you can use:
onchange="changeWeek(this.name)"
Or: (keep in mind that the changeWeek function will have to already have been defined)
<script>
var select = document.getElementById('name');
select.onchange = changeWeek;
</script>
addEventListener vs onclick -- for information between adding event listeners and the method I provided above.
An alternative JavaScript way:
var selects = document.getElementsByTagName('select');
for(var i in selects)
{
selects[i].onchange = function changeWeek(e) {console.log(e.target.name);}
}
HTML:
<select name="test">
<option>One</option>
<option>Two</option>
</select>
<select name="test2">
<option>One</option>
<option>Two</option>
</select>
Fiddle:
http://jsfiddle.net/bddwW/

html - how can I display images when option from drop down menu is selected

I have the code for a drop down menu:
</center>
<p>
<center><select>
<option value="none">None selected</option>
<option value="cat">cat</option>
<option value="dog">dog</option>
</center></select>
</p>
I want to be able to display an image of a cat (such as http://www.petfinder.com/wp-content/uploads/2012/11/95142833-crate-training-cat-632x475.jpg) when the "cat" option is selected and also alternate text (such as "image of cat could not be loaded") if the image could not be loaded. How can I do this?
you can insert an image on value change in select box, i would do it like this:
html:
<select id="pic-changer">
<option value="none">None selected</option>
<option value="cat" data-picture="cat.png">cat</option>
<option value="dog" data-picture="dog.jpg">dog</option>
</select>
<div id="image-location></div>
jquery (javascript) code:
$('#pic-changer').change(function(){ //if the select value gets changed
var imageSource = $(this).find(':selected').data('picture'); //get the data from data-picture attribute
if(imageSource){ //if it has data
$('#image-location').html('<img src="'+imageSource+'">'); // insert image in div image-location
} else {
$('#image-location').html(''); //remove content from div image-location, thus removing the image
}
})
if you dont need the select box value, I would suggest putting the picture link in there:
<select id="pic-changer">
<option value="">None selected</option>
<option value="cat.png">cat</option>
<option value="dog.jpg">dog</option>
</select>
jQuery code becomes:
$('#pic-changer').change(function(){ //if the select value gets changed
var imageSource = $(this).val(); //get the selected value
if(imageSource && imageSource != ""){ //if it has data
$('#image-location').html('<img src="'+imageSource+'">'); // insert image in div image-location
} else {
$('#image-location').html(''); //remove content from div image-location, thus removing the image
}
})
You can do much more with javascript and jQuery i suggest you learn it, it ain't hard at all. http://jquery.com/
You asking Something which is not Possible by Simple HTML.
In Addition Of HTML Code you should use JavaScript.
I suggest you to Start learning Javascript.
here is the Link. http://www.tutorialspoint.com/javascript/
Lean it.. Implement it. You will reach your Goal.
All The Best..!!