Display an option in a select based on a specific value - javascript

I need to display a specific option inside a select based on certain values of the zip code.
So far I've managed to do the opposite, hide it based on values of the zip, but that is too easy to game.
<script type="text/javascript">
$(function(){
var $location = $('#ShippingOptions');
$location.data('options', $location.find('option')); //cache the options first up when DOM loads
$('#zip').on('change', function () { //on change event
$location.html($location.data('options')); //populate the options
if ($(this).val() == "12345" ) { //check for condition
$location.find("option[value='300305']").remove(); //remove unwanted option
}
if ($(this).val() == "54321" ) { //check for condition
$location.find("option[value='300305']").remove(); //remove unwanted option
}
});
});
</script>
<!--Zip-->
<div class="zip-field">
<label for="zip">Zip Code</label>
<input type="number" id="zip" name="zip" />
</div>
<!--Location-->
<div class="location-field">
<label for="location">Location</label>
<select class="shippingDropDown" id="ShippingOptions" name="ShippingOptions"><option value="-1">Choose Shipping Option</option>
<option value="300305">Free Shipping $0.00</option></select>
</div>
I do no have access to add classes to the options, they are dynamically generated by a rendering engine. I can however target values which stay fixed.
The plan was to have it hidden by default, then adding conditions in which to show it. This is not about setting a value to an option but showing/hiding an option with a certain value
A little background story: the system I work with gives me the option to add various types of shipping some free some paid. However, because there is no way to discern/filter between them, especially by zip, I am left in the hilarious position of letting the users choose either free shipping or paid shipping which, as human nature goes, it's pretty much pointless. So my idea was to have the user enter their zip and show the free option, which can only be identified by value, only to those that have a specific zip (full number) and not to anybody else. I am aware of the security issues and willing to live with them.
Is there a way to add/show that option instead of removing it? Is there a way to set it selected?

<select class="zip-list">
<option value="26598">New York</option>
<option value="19356">Mexico</option>
<option value="26825">Artic Ocean</option>
<option value="93583">A Village</option>
</select>
<p><input type="text" class="zip-filter" /></p>
var $zipList = $('.zip-list');
var $zipOptions = $('option', $zipList);
var $zipOptionsAll = $zipOptions.clone();
$('.zip-filter').on('change', function () {
var filterText = $(this).val();
var $filteredOptions = $zipOptionsAll.filter(function(e) {
return $zipOptions.eq(e).val().indexOf(filterText) === 0;
});
if ($filteredOptions) {
$zipList.empty().append($filteredOptions);
} else {
$zipList.empty().append($zipOptionsAll);
}
});
Fiddle: http://jsfiddle.net/ekEY4/
Should be pretty self explanatory. Note that since you are listening to the change event you have to loose focus on the text by clicking/tabbing out or pressing return before it updates.
I am also doing a "begins with" string check (indexOf) as I figure with something like postcode/zipcode you will want to show all results that begin with a certain area code before narrowing down. That means if you had "26598" and "26825" in the list and they searched for "26" both would come up.
"When the filter changes loop through and filter all the options that begin with the query. If something is found set those options, otherwise reset back to all options as nothing was found."
Edit:
Oh you want the inverse - easy. Simply change indexOf(filterText) === 0 to indexOf(filterText) !== 0.
Fiddle: http://jsfiddle.net/v3ZDE/

Related

How do I replace an HTML element on click?

I am developing this code for a storytelling type game and I need to change the dropbox options after the user or player is done selecting their option. I am trying to make the options in the dropbox relevant to what is happening in the game at the given moment. I was told to do research on a possible change of element(with different options in the dropbox) every time the user has chosen their option.
I have tried some jquery, but only moved the dropbox on click. I could not find any type of operator that could help me with changing it. The append bit in my code is submitting the input and getting an outcome
<div id="actions">
<select id="chosen_action">
<option value="You have entered the dungeon...">Yes</option>
<option value="You turned and left THE END">No</option>
<option value="You attempted to communicate with the enemy...">Talk</option>
</select>
<button onclick="append_to_history()">Go!</button>
</div>
You can do this really easily with .innerHTML:
$("#chosen_action").innerHTML = `
<option>You turn away from the castle</option>
<option>You take a closer look at the old drawbridge</option>
<option>You decide to consult your map</option>
`;
.innerHTML simply changes the HTML content of a given element. The backtick operators (`) form a template string, which is capable of spanning multiple lines, making it easier to lay out your new options. You could use a regular string here instead if you'd like (and of course can generate this value with a loop, array, etc).
const choice = document.getElementById('chosen_action');
const opt1 = document.getElementById('option1');
const opt2 = document.getElementById('option2');
const opt3 = document.getElementById('option3');
const go = document.getElementById('goButton');
go.addEventListener('click',(e) => {
if(choice.value !== ""){
if(choice.value === opt1.value){
opt1.value = ... //change the value of this element
opt2.value = ...
opt3.value = ...
//if need to change value of text shown to user for selection you can:
opt1.textContent = ...//change the text of this element
opt2.textContent = ...
opt3.textContent = ...
} else if(choice.value === opt2.value){
...
...
...
} else{
...
...
...
}
} else {
alert("You must make a choice to continue!")
}
})
<div id="actions">
<select id="chosen_action">
<option id="option1" value="You have entered the dungeon...">Yes</option>
<option id="option2" value="You turned and left THE END">No</option>
<option id="option3" value="You attempted to communicate with the enemy...">Talk</option>
</select>
<button id="goButton" onclick="append_to_history()">Go!</button>
</div>
I can't comment to gather more information, so, without knowing more about what you are asking, or where your game is going, or what "append_to_history()" does, or how many possible combinations there are, etc., this is one way of doing what you need to do.
In the end, I would guess you will have to make a giant object, or a great deal of smaller objects, and come up with a naming system that you can programmatically grab the proper values from when it comes time. Probably a tracker to count the number of choices (each button click) and then name your objects accordingly, so that you can use the tracker value and the option number to call the correct value. You will have to figure out, at some point, every single possible value and then programmatically call them for each new value depending on the value chosen at time of click.
Would be interested to know if anyone else has any different perspective on this, though!

Set input attribute based on selected option

I'm trying to set the value of a hidden input field based on the value of a selected option from a select box
This is what I've tried.
HTML
<select id="track_type_selected">
<option value="0">51 Track 3m</option>
<option value="1">64 Track 3m</option>
<option value="2">103 Track 3m</option>
</select>
<input type="number" name="required_tracks_name" id="required_tracks_id" class="sku" sku="" disabled="">
Javascript
if ('#track_type_selected' == 1) {
'#required_tracks_id'.sku('TRACK3');
}else if('#track_type_selected' == 2) {
'#required_tracks_id'.sku('TRK30');
}else if ('#track_type_selected' == 3) {
'#required_tracks_id'.sku('TRACK-1033');
}
When the option is selected I want to set the value of the SKU.
Before i go on with the solution, i can understand that you have basic to zero knowledge about JavaScript.. make sure you understand how JavaScript syntax works then continue.
To get the selected option use this code:
var e = document.getElementById("track_type_selected");
var selectedIndex = e.options[e.selectedIndex].value;
selectedIndex variable should now include the current selected index. (1,2,3.. etc)
So you can do this:
if(selectedIndex==1){/* some code */}
Now, to get sku attribute (since you confirmed that you use jquery) you can do this:
$("#required_tracks_id").attr("sku");
Make sure you check .attr usage and edit it to your needs.

<HTML> Can't select same values in drop down list. Validation <HTML>

I want to be able to validate my drop down lists.
There are 6 destinations, and if the user was to select Cardiff in the "Departure" drop down, then if they was to select Cardiff again in the "Destination" drop downn, it should give a message box saying 'Destination can't be the same as Departure'.
This needs to be done in HTML and JavaScript/JQuery.
Thanks
Departure: <br> <select>
<option value="" disabled selected>Please Select</option>
<option>Birmingham</option>
<option>Bristol</option>
<option>Cardiff</option>
<option>Liverpool</option>
<option>London</option>
<option>Manchester</option>
</select><br><br>
Destination: <br><select>
<option value="" disabled selected>Please Select</option>
<option>Birmingham</option>
<option>Bristol</option>
<option>Cardiff</option>
<option>Liverpool</option>
<option>London</option>
<option>Manchester</option>
</select><br><br>
Very quick example but essentially you can do something like this:
Fiddle: http://jsfiddle.net/6hojsqhr/
$('#select1, #select2').on('change',
function () {
if ($('#select1').val() == $('#select2').val()) {
// Display message
}
else {
// Remove message if displayed
}
}
);
Well I am feeling slightly called out so let me explain what is happening here.
$('#select1, #select2').on('change',
First I select the two inputs we want to test against and attach a change event to them. This will fire this event every time the input's value changes and loses focus.
if ($('#select1').val() == $('#select2').val()) {
// Display message
}
else {
// Remove message if displayed
}
In this function we get both values of the two inputs we want to test for equivalent values. If they are the same we display the message. If not don't do anything or in some cases remove a displayed message.
Again this is a very quick solution that can be much more dynamic and thought out depending on your specific scenario. This is very simple JavaScript/jQuery. I would recommend doing some reading and perhaps free courses online that can teach these basics. A simple google search will pull up a ton of examples of code like this and websites that teach how to do this.

Change the query string of an iframe src when select options are clicked

I have several dropdown boxes on a site and I need to append/add/remove query string depending on what the user has chosen. How can I accomplish it? Here is some generic code for demo purposes:
<select name="status" onchange="document.getElementById('Iframe2').src = document.getElementById('Iframe2').src + this.options[this.selectedIndex].value">
<option></option>
<option value="&A=1">1</option>
<option value="&A=2">2</option>
</select>
<select name="plan" onchange="document.getElementById('Iframe2').src = document.getElementById('Iframe2').src + this.options[this.selectedIndex].value">
<option></option>
<option value="&FilterGarage=Right">Right</option>
<option value="&FilterGarage=Left">Left</option>
</select>
So what I would like to happen is let's say the user selects the "1" option and then the "Right" option. The way I have it now, it works fine. The problem happens when the user then goes back and changes the "Right" option to "Left". At that point what's happening is it's just adding another &FilterGarage parameter and ends up not showing anything.
I guess what I need to know is how to remove the option value and regenerate it depending on what the user picks each time.
You can achieve this by pure JavaScript. Just add id to your <select> elements.
<select name="status" id="status">
and
<select name="plan" id="plan">
And add the JavaScript at the end of HTML <body>.
<script type="text/javascript">
function set_url(){
status = document.getElementById("status").value;
plan = document.getElementById("plan").value;
s = url + status + plan;
//alert(s);
document.getElementById("Iframe2").src = s;
}
url = "http://www.google.com/search?q=JavaScript";
document.getElementById("status").onchange = set_url;
document.getElementById("plan").onchange = set_url;
</script>
NOTE: The base URL should be stored in a variable; like url in above example.
capture combo's change event, then you change link href depending on the selected value. The first time, you save the base_href, to avoid to compute it each time. Everytime you save the changed values to a var and add the two variables to the url.
var base_href="",status="",plan="";
$('#plan').on('change', function() {
plan=$(this).val();
if (base_href=="")
base_href = $("#Iframe2").attr("src");
$("#Iframe2").attr("src",base_href+plan+status);
});
$('#status').on('change', function() {
status=$(this).val();
if (base_href=="")
base_href = $("#Iframe2").attr("src");
$("#Iframe2").attr("src",base_href+plan+status);
});
I am doing it with jquery(im writing with my mobile and it less code to write) but if you dont want to use jquery the only thin that changes is the name of the functions. The idea is the same!

Multiple Dynamic Javascript Dropdowns?

I have currently got a 2-tier javascript drop down box attached to my form, and i am looking to add another 3-tiers, but completely seperate to my current javascript and can't unfortunately figure it out (quite new to javascript :( )
Here what I have so far, it all works ( not even sure what framework to select on fiddle for it to display properly lol :( the embarassment haha
Any help is appreciated <3
This will probably be enough code for you to get the idea.
jsFiddle here
I used jQuery to get handles to the various DOM elements. Here is a quite decent resource for browsing all jQuery selectors, events, effects, css, etc - despite the source. (Just keep hitting Next Chapter)
First, this is your code for catching the optone select element's change event, removed from inline javascript (which is never a good idea):
$('select[name=optone]').change(function() {
var selval = $(this).val();
setOptions(selval);
});
Simple enough, yes?
I left your first setOptions function as is, because it works. However, I wrote the next function setOptions2() in jQuery, to show you how much less typing is required.
To catch the next select element's change event:
$('select[name=opttwo]').change(function() {
var sel2val = $(this).val();
alert('You selected: ' + sel2val);
setOptions2(sel2val);
$('#selthreeDiv').show();
});
Notice in my jsFiddle that I added a hidden div containing the 3rd select control, and I display that control when the 2nd select is changed...
Hopefully this will be of assistance.
ok I did something like this and it worked for me.
your new javascript
function setOptions2(chosen) {
var selbox = document.myform.optthree;
selbox.options.length = 0;
if (chosen == "1") {
selbox.options[selbox.options.length] = new Option('Worked', ' ');
}
}
then added some new html
<select name="opttwo" size="1" onchange="setOptions2(document.myform.optone.options[document.myform.optone.selectedIndex].value);" >
<option value="Please Select Prompt Category" selected="selected">Please Select Prompt Category</option>
</select>
<select name="optthree" size="1">
<option value="Please Select Prompt Category" selected="selected">Please Select Prompt Category</option>
</select>

Categories

Resources