Each time the web page is loaded the onchange method works, but it only works once per value. When summer is selected the classes are added, when i chose winter the class is added but then if i chosesummer again it will not work. Why is this?
const landingBGR = document.querySelector(".landing-wrapper");
const landingBTN = document.getElementById("l-btn");
function selectedSeason(season) {
switch(season) {
case "summer":
landingBTN.setAttribute("href","summer.html");
landingBGR.classList.add("summer-bgr");
break;
case "winter":
landingBTN.setAttribute("href","winter.html");
landingBGR.classList.add("winter-bgr");
break;
}
}
<select name="" id="landing-drop" onchange="oninput(this.value)">
<option value="">Ireland in the four Seasons</option>
<option value="summer">Summer</option>
<option value="winter">Winter</option>
</select>
try to delete the old class when you select a new option.
landingBGR.classList.remove("summer-bgr");
landingBGR.classList.remove("winter-bgr");
you will maybe need
if(landingBGR.classList.contains("classname"))
Related
I've looked around and I don't see this being asked before.
I have a select box, like so:
<select onchange="change()">
<option value="" selected>Option 1</option>
<option value="30">Option 2</option>
<option value="90">Option 3</option>
</select>
I want to add another option...
<option value="custom">Option 4</option>
...that when chosen (clicked) an alert box will popup asking the user to type in a number (in the case 30 or 90 weren't viable options, as in the values of the option's) to replace the value of the option.
<script>
function change() {
if(value == "custom") {
value = prompt("Please enter a new number:", "60");
}
}
</script>
I wanted to know what the best way to do this is with plain old javascript - I'll use jQuery if I have to.
Any ideas? An example would be great as well.
Take a look at this code. I think this is what you're trying to do:
HTML
<select id="optionvals" onclick="change()">
<option value="" selected>Option 1</option>
<option value="30">Option 2</option>
<option value="90">Option 3</option>
<option value="custom">Option 4</option>
</select>
JS
function change() {
var oItem = document.getElementById('optionvals');
var value = oItem.options[oItem.selectedIndex].value;
if(value == "custom") {
alert("you've clicked b");
value = prompt("Please enter a new number:", "60");
oItem.options[oItem.selectedIndex].value = value;
console.log(oItem.options[oItem.selectedIndex].value)
}
}
What this does is prompt you on the change only if the selected value in the options is custom. Then after you choose a custom value, it will rewrite the value of that the custom option element to the value you just entered in the prompt. I logged the new value after assigning it to show you that it is working.
Here is a fiddle: https://jsfiddle.net/ng7xvy05/
Your onchange event is the appropriate way to handle this. This is mostly a matter of user interface (UX) design though. To do this in the prompt fashion you ought to use parseFloat:
change() {
var value = prompt('You\'ve chosen Other. Please enter a value', '60');
if(value) {
value = parseFloat(value);
// apply it to your model
} else {
// apply NULL to your model
}
}
From a UXD point of view I would use a typeahead input. It would autosearch known answers but also allow the user to input their own. This is not standard html so you would need to write this yourself or use jquery. But from a user interface design point of view, prompts suck.
This is using react. The problem in a nutshell is that I have two select menus in a form (as part of the same component) and I want selecting one to set the options of the other.
One select shows months and one shows days in that selected month. Depending on which month is selected the days should show the correct number for that month (so 31 days in the days select if "January" is selected in month, 28 if "February" and so on).
I cannot get the initial value to change in response to the select. I can log the correct value but what actually appears in the days select never updates from its initial state.
Some code...
I trigger with:
<select defaultValue="Jan" onChange={() => { setMonthNumber(this.refs["month"]["value"]) }} ref="month">
setMonthNumber is an action:
export const setMonthNumber = (monthNumber) => {
store.dispatch({type:'GUEST_INFORMATION_SET_MONTH', message:monthNumber});
}
The reducer that handles that action is:
const initialState = {
currentMonth: "Jan"
};
const guestInformationEditReducer = (state = initialState, action) => {
let localState = merge({}, state);
switch (action.type) {
case 'GUEST_INFORMATION_SET_MONTH':
localState.currentMonth= action.message;
return localState;
}
return state
};
export default guestInformationEditReducer;
I aggregate my reducers and in that file I set (leaving out other reducers):
export default {
guestInformationEditComponent: guestInformationEditReducer
}
and then in my component (named GuestInformationEdit) I connect things with:
const getGuestInformationComponentProps = state => {
return {
month: state.guestInformationEditComponent.currentMonth
}
}
export default connect(getGuestInformationComponentProps)(GuestInformationEdit);
In my component's render method I access the value with:
const days = this.getDaysFromMonth(this.props.month);
getDaysFromMonth is simply a switch that builds a collection of jsx options like:
days.push(<option key={stringNum} value={stringNum}>{stringNum}</option>);
so that I end up with an array of options with the correct values depending on the selected month. This all works (logging shows the correct values). My problem... when I add {days} to my jsx like so:
<select defaultValue="1">
{days}
</select>
I only ever get 31 days, the value set by the initialState in the reducer. It never changes in the view in spite of changing in any console logs I may try. Why? What am I doing wrong/missing? Also, is all of this really necessary for such a change? It seems wickedly complex for such a simple thing.
**edit
In my component I have this outputting the selects:
<BootstrapFormGroup model="guestModel.BirthMonth" classes="col-xs-12 col-md-1 extra-four-percent" formLabel="Birth Month">
<select defaultValue="Jan" onChange={() => { setMonthNumber(this.refs["month"]["value"]) }} ref="month" className="form-control">
<option value="Jan">Jan</option>
<option value="Feb">Feb</option>
<option value="March">March</option>
<option value="April">April</option>
<option value="May">May</option>
<option value="June">June</option>
<option value="July">July</option>
<option value="Aug">Aug</option>
<option value="Sept">Sept</option>
<option value="Oct">Oct</option>
<option value="Nov">Nov</option>
<option value="Dec">Dec</option>
</select>
</BootstrapFormGroup>
{days}
<BootstrapFormGroup model="guestModel.BirthDay" classes="col-xs-12 col-md-1 extra-four-percent" formLabel="Birth Day">
<select defaultValue="1" className="form-control">
{days}
</select>
</BootstrapFormGroup>
See those two instances of {days}? With my above code the first one updates correctly in response to onChange of the month select, the second one does nothing except display the initial state and then never update.
New to Javascript. Here is the story:
I need to create a dynamic link to redirect to one of the 6 different courses, depending on the options chosen by the user. This can be done via 3 dropdown menus or via 3 sets of checkboxes:
img. 1: http://i.imgur.com/oi8WYYv.png
or
img. 2: http://i.imgur.com/tRIdxBv.png
I tried to combine codes from several examples from stackoverflow, but it's a mess... Any idea is highly appreciated.
[edit 06.04.2015]
Thanks for your suggestions, but the story is a little more complicated:
The links are fixed, i.e. they are quite complicated to write it via a "generate" function (they are something like: base_url + id_1 + base_url_2 + id_2 + base_url_3)
There are 6 different courses, each one with its own link:
a) regular user - in English b) regular user - in German c) user with access to confidential data - in English d) user with access to confidential data - in German e) user manager - in English f) user manager - in German
To select the proper course, you would need to meet criteria from more than one form. I think there should be a lot of "if" statements in place in order to select the proper course via the questions. Or the questions are not the correct ones...
This is fairly trivial; all you have to do is check the values of each select tag, and set the href of the anchor accordingly.
Here's a tiny mockup:
window.onload = function(){
var select = document.getElementById('language');
var anchor = document.getElementById('next');
select.onchange = function(){
anchor.href = select.value;
}
}
Which is your preferred language?
<select id="language">
<option value="#">--------------</option>
<option value="http://stackoverflow.com/questions/tagged/javascript">JavaScript</option>
<option value="http://stackoverflow.com/questions/tagged/python">Python</option>
<option value="http://stackoverflow.com/questions/tagged/c%2b%2b">C++</option>
</select>
<br>
<a id ="next" href="#">Next</a>
Basically, I'm listening to onchange on the select element, and can therefore update the link whenever the chosen option changes.
If you aren't using an <a> anchor tag, but something else, for the Next page button, you can always just check the values before redirecting the user:
window.onload = function(){
var select = document.getElementById('color');
var next = document.getElementById('next');
next.onclick = function(){
switch (select.value){
case '1':
window.location.href = "http://blog.xkcd.com/2010/05/03/color-survey-results/";
break;
case '2':
window.location.href = "http://www.omglasergunspewpewpew.com/";
break;
default:
break;
}
}
}
What is your least favourite colour?
<select id="color">
<option value="1">puke</option>
<option value="2">The best color in the world!</option>
</select><br>
<button id="next">Next</button>
Basically, whatever you're doing, you can just check select.value, and perform an action accordingly.
first draft, not working but that's the best I got so far:
<script type="text/javascript">
window.onload = function(){
var language = document.getElementById('lang');
var confidential = document.getElementById('conf');
var manager = document.getElementById('mgr');
var next = document.getElementById('next');
next.onclick = function(){
switch (true){
case language === "isEnglish":
window.open('link/regular_user_in_English', '_blank');
break;
case language === "isGerman":
window.open('link/regular_user_in_German', '_blank');
break;
case language === "isGerman" && confidential === "isConf":
window.open('link/conf_in_German', '_blank');
break;
default:
break;
}
}
</script>
Which language would you prefer to do the training in?
<select id="lang">
<option value="isEnglish">English</option>
<option value="isGerman">German</option>
</select><br />
Are you a confidential data handler?
<select id="conf">
<option value="notConf">No</option>
<option value="isConf">Yes</option>
</select><br />
Are you a people manager?
<select id="mgr">
<option value="notManager">No</option>
<option value="isManager">Yes</option>
</select>
<br />
<button id="next">Next</button>
I have a select list that I would like to display a different image in the same div each time the user changes the select list. Here's what I have so far:
HTML
<div id="branches">
<h3>British Columbia Old Age Pensioners' Organization — Branches</h3>
<select id="branch-number" class="form-control">
<optgroup label="British Columbia">
<option value="1">Branch 1</option>
<option value="2">Branch 2</option>
<option value="http://placehold.it/350x350">Branch 3</option>
<option value="http://placehold.it/350x450">Branch 4</option>
</optgroup>
<optgroup label="Alberta">
<option value="5">Branch 5</option>
<option value="6">Branch 6</option>
...etc...
</select>
<div id="img-window">
<img id="branch-img" src="http://placehold.it/350x150" class="img-responsive">
</div><!-- end img-window -->
</div><!-- end branches -->
jQuery
$(document).ready(function () {
$('#branch-number').on('change', function () {
alert('something happened');
// var branchVal = $('this').val();
var branchVal = $('option:selected').val();
switch (branchVal) {
case 1:
$('#branch-img').attr('src', 'http://placehold.it/150x150');
break;
case 2:
$('#branch-img').attr('src', 'http://placehold.it/250x250');
break;
case 3:
$('#branch-img').attr('src', 'http://placehold.it/350x350');
break;
default:
$('#branch-img').attr('src', 'http://placehold.it/1450x1450');
}
});
});
Right now, nothing happens when the user changes the select list. I am trying to do this with an <img> tag instead of CSS so that for increased accessibility of the alt="" attribute.
I'm just starting to get the hang of javascript / jQuery ... any help appreciated.
Here's a fiddle:
https://jsfiddle.net/r1fcvs7s/4/
edit: syntax should be all good now.
Your case syntax is wrong. It should be:
switch(branchVal) {
case 1:
$('#branch-img').attr('src', 'http://placehold.it/150x150');
break;
case 2:
$('#branch-img').attr('src', 'http://placehold.it/450x450');
break;
}
The : comes after the value, not before. And you need break between the cases unless you want to fall through into the next case (which you obviously don't in this code).
You should have gotten a syntax error in the Javascript console. How did you miss that?
BTW, to get the value of the <select>, you can use $(this).val(). You don't need to access option:selected.
HTML
<select id="branch-number" class="form-control">
<optgroup label="British Columbia">
<option>1</option>
<option>2</option>
<option>Three</option>
<option>Four</option>
</optgroup>
</select>
jQuery
$(document).ready(function() {
$('#branch-number').on('change', function() {
// var branchVal = $('this').val();
var branchVal = $('#branch-number').find(':selected').text();
switch(branchVal) {
case "1":
$('#branch-img').attr('src', 'http://placehold.it/350x350/9d9999/000000&text=Abbotsford+Branch');
break;
case "2":
$('#branch-img').attr('src', 'http://placehold.it/250x250/9d9999/000000&text=Chilliwack+Branch');
break;
case "Three":
$('#branch-img').attr('src', 'http://placehold.it/150x150/9d9999/000000&text=Mission+Branch');
break;
case "Four":
$('#branch-img').attr('src', 'http://placehold.it/350x350/9d9999/000000&text=Vancouver+Branch');
break;
}
});
});
Had to use the .find(:selected).text(); method instead of the .val(); method. This is because the value attribute is only used for forms and other things but, not boxes.
I have a selectbox with a couple of options in it. When an option is selected, the Javascript code gets the value of the selected option and has to change the font of a text accordingly.
I figured I would use the Switch-Case statement because I have multiple options, but it doesn't seem to work, nothing changes.
Javascript
function font() {
var sf = document.getElementById('box').value;
var generate = document.getElementById('generate');
switch (sf) {
case 'TimesNewRoman':
generate.style.fontFamily('Times New Roman')
break;
case 'Georgia':
generate.style.fontFamily('Georgia')
break;
case 'PalatinoLinotype':
generate.style.fontFamily('Palatino Linotype')
break;
default:
generate.style.fontFamily('Arial')
}
}
HTML
<select id="box" onchange="font();">
<option id="TNR" value="TimesNewRoman">Times New Roman</option>
<option id="GRG" value="Georgia">Georgia</option>
<option id="PLT" value="PalatinoLinotype">Palatino Linotype</option>
</select>
<br />
<div id="generate">This is some text</div>
NOTE
I have more options in the list but I have shorten it for the sake of simplicity.
Am I wrong for using this statement, or am I missing something entirely?
You haven't made an assignment, use generate.style.fontFamily = "Arial";