Default dropdown value on load from hyperlink with JavaScript - javascript

I did some searching and couldn't find an exact answer on how to do this (especially for a noob like me) I would like to set a dropdown value on page load based off a variable in the href hyperlink.
Example with default dropdown: mywebsite.com&value=4
This would apply the dropdown item associated with value 4 when the page loaded.Below is the HTML for the drop down selector but I currently have no JavaScript for it. Is it possible for it to pull a variable from hyperlink? Thanks for any help.
<select id="subject" name="subjectlist" size="1" onchange="SetActivity();">
<option value="1^Non-Urgent Medical Question">Non-Urgent Medical Question</option>
<option value="2^Medication Question">Medication Question</option>
<option value="3^Test Results Question">Test Results Question</option>
<option value="4^Visit Follow-Up Question">Visit Follow-Up Question</option>
<option value="5^Medical Record Question / Correction">Medical Record Question / Correction</option>
</select>

If you have control of the URL, you can change the format and use a hash.
So for value=4, the URL is: http://example.com/#value=4
if (window.location.hash.length > 0){
var matches = window.location.hash.match(/value=([0-9]+)/i);
if (matches.length > 1){
var value = matches[1];
$("#subject option[value^='"+value+"^']").attr('selected', true);
}
}
Alternatively, you could filter the options based on value. Safer than the above code:
if (window.location.hash.length > 0){
var matches = window.location.hash.match(/value=([0-9]+)/i);
if (matches.length > 1){
var value = matches[1];
$("#subject option").filter(function(){
return $(this).val().indexOf(value+'^') === 0;
}).attr('selected', true);
}
}
If you don't want to use a hash (#), you could use window.location.href instead. You'd just modify the RegEx a bit (so it's guaranteed to be at the end of the URL).

Related

How to return the length and value of a selection in a datalist?

I would like to fabricate some code, that tracks the amount of unfiltered options in a datalist. So how could I keep track of this?
Secondly when there is only one option left in the list I want to access the value of this option.
Here is a link to the w3c spec: https://www.w3.org/TR/html5/forms.html#the-datalist-element
Note: I want to use the datalist, so I don't want to create my own filter on the datalist and get the values from there.
I came up with this code so far:
Fiddle: https://jsfiddle.net/6usf7j9g/
html
<h3>Anything you'd like?</h3>
<input id="your-favourite" list="choices"/>
<datalist id="choices">
<option value="Laphroaig"></option>
<option value="Jameson"></option>
<option value="Talisker"></option>
<option value="Oban"></option>
<option value="Dalwhinnie"></option>
<option value="Glennfidich"></option>
<option value="Glenlivet"></option>
</datalist>
jQuery/js
var selectedChoices = null; //in this variable I need to know how many items are left in the list after filtering. If you type "Glen" it should be two, if you type "Glenn", "J", etc. it should give a value of 1. It only needs to work on google chrome.
$("#your-favourite").on("keyup", function(){
selectedChoices = null; //PART OF THE ISSUE: Should change the value of the variable here, depending on the options that are showing.
if(selectedChoices === 1){
let finalOption = "unknown"; //PART OF THE ISSUE: Should load the value of the remaining option
// validate success
alert("There is only one value left in the list! It is called: " + finalOption);
selectedChoices = null; // reset value to 0.
}
// log the datalist and input elements, it might have some info that helps finding a solution.
console.log($("#your-favourite"));
console.log($("#choices"));
}); // end on keyup

Hide dropdown options with Javascript based on keyword in the URL

I need to hide certain options for a product based on the URL they came from. However its a bit tricky for me since I cant target the option value in this situation.
Example URL: http://www.website.com/department/alabama/shirt.html
<select id="select_135">
<option value="">-- Please Select --</option>
<option value="1849" selected="selected">NONE </option>
<option value="1850">Alabama 1</option>
<option value="1851">Alabama 2</option>
<option value="1852">Arizona</option>
<option value="1853">California</option>
<option value="1854">Texas</option>
</select>
Is this case I want to hide all options that DONT have the word Alabama, without using the value number. The goal is for this to work site wide, so if they are on another category, it will do the same thing but with the new URL.
So for the next state: http://www.website.com/department/texas/shirt3434.html , it will do the same thing but for the word Texas.
Any ideas on how I can do that?
use below code . check DEMO
$( document ).ready(function(){
var url = " http://www.website.com/department/alabama/shirt.html";
// to get URL use below code
// var url = window.location.href;
url = url.split('/');
var word = url[url.length-2];
$("#select_135 option").each(function(){
if($(this).text().toLowerCase().indexOf(word) == -1){
$(this).hide();
}
});
});
Use indexOf to check the occurance of a substring.
var url = "http://www.website.com/department/alabama/shirt.html";
var s = $('#select_135 option');
var pieces = url.split("/");
var state = pieces[pieces.length-2];
for(var i = 0; i < s.length; i++) {
if(s[i].text.toLowerCase().indexOf(state) > -1) $(s[i]).show();
else $(s[i]).hide();
}

Select and Deselect not working in IE9?

I have a dropdown <select> element to select states from the list of 50 states, I select the 1st value, save it, and show the value in DOM. I changed and select to the 5th value, saving it shows the value updates in DOM. Now back i am selecting the 2nd Value, and saving it. It's not saving the value in DOM and it's showing the previous selected 5th value. I Checked with different values, and found that, after selecting any higher index value, selecting back, lower values are not affecting in DOM, and hence i am not getting the correct values in POST.
This is the function i am calling on change.
function updateDOM(inputField) {
var elementId = inputField;
if (inputField.type == "select-one") {
var prev_select = inputField.selectedIndex;
$('#'+inputField.id+' option').each(
function() {
$(this).removeAttr('selected');
}
);
document.getElementById(elementId.id).selectedIndex = prev_select;
if (browserVersion == 9) {
document.getElementById(elementId.id)
.options[prev_select].setAttribute("selected","selected");
}
else {
document.getElementById(elementId.id)
.options[prev_select].setAttribute("selected","selected");
}
document.getElementById(elementId.id).value
= document.getElementById(elementId.id).options[prev_select].value;
}
The HTML
<select id="abc" name="abc" onchange="javascript:updateDOM(this);" class="required" >
<option name="" value="" title="null" selected ></option>
<option name="AK" value="Alaska" title="null" >Alaska</option>
<option name="AL" value="Alabama" title="null" >Alabama</option>
<option name="AR" value="Arkansas" title="null" >Arkansas</option>
<option name="AZ" value="Arizona" title="null" >Arizona</option>
</select>
First of all, why don't you use ":selected" selector of jQuery, which you are using anyway? Also, why are you using jQuery only once?
I would recommend doing it in jQuery-style (sorry, I'm not quite sure what you are trying to do exactly in your code):
http://jsfiddle.net/msLXt/1/
P.S. What is the difference between these conditions?
if (browserVersion == 9) {
document.getElementById(elementId.id)
.options[prev_select].setAttribute("selected","selected");
}
else {
document.getElementById(elementId.id)
.options[prev_select].setAttribute("selected","selected");
}

Select Download File from One of Two Select Boxes with One Button - JavaScript

I have two select boxes like so:
<select id="one">
<option value="default">Select File</option>
<option value="path/to/file1">File One</option>
<option value="path/to/file2">File Two</option>
<option value="path/to/file3">File Three</option>
</select>
<select id="two">
<option value="default">Select File</option>
<option value="path/to/file4">File Four</option>
<option value="path/to/file5">File Five</option>
<option value="path/to/file6">File Six</option>
</select>
<p class="button_image">
<a onclick="download(document.getElementById("one").value)"></a>
</p>
Here is my download function:
function download(file) {
if (file == 'default') return;
window.location = 'http://www.mysite.com/download/' + file;
}
This works fine for one select box, but I can't seem to figure out how to use the same button image. Oh yah, the p.class=button_image has background image that is a button with hover effects.
The reason I want these select boxes to be separate is because they each represent a group of files, eg, 32-bit versus 64-bit. So they cannot be combined, because it won't flow with the page design.
I've tried some if/else blocks in PHP using the getElementById but I'm getting stuck. This is what I tried and it seems to only partially work:
<?php
if ('document.getElementById(\"one\")' == 'one') {
echo "<a onclick='download(document.getElementById(\"one\").value)'></a>";
}
else if ('document.getElementById(\"two\")' == 'two') {
echo "<a onclick='download(document.getElementById(\"one\").value)'></a>";
}
?>
I should note that I don't necessarily need to use PHP in this case to solve this problem. It was just an option I tried because I'm using PHP for the server-side programming. I could be happy with any number of options, so long as they work.
Thanks.
** EDIT **
This design might be flawed. But the intention is that either a file from box one is downloaded OR a file from box two is downloaded. If one selection is made, then the other should be rest to default and vice versa. This is what I'm working on now.
** EDIT **
I ended up goign with Dawson Loudon's answer for one part and I created another function based on Barmar's comment that looks like this:
// resets other select box when selected
function reset_index(id) {
document.getElementById(id).selectedIndex = 'default';
}
An A element as a button doesn't seem appropriate, just use an img.
Anyhow, a function to use the first select with a selected option other than the first can be something like:
function getPath() {
var select;
var args = arguments;
for (var i=0, iLen=args.length; i<iLen; i++) {
select = document.getElementById(arg[i]);
if (select && select.selectedIndex > 0) {
window.location = 'http://www.mysite.com/download/' + select.value;
}
}
}
The above expects the first option to be the default selected, so if it's selected, or no option at all is selected, the select's selectedIndex will be 0 or -1 respsectively. I would ensure one option is selected by adding the selected attribute to the first one:
<option value="default" selected>Select File</option>
and the call is:
<img src="buttonImage.jpg" onclick="download('one', 'two');">
though you might want to add a class to the select elements and get them using getElementsByClassName or similar and loop over that collection, rather than hard code the ids.
Try replacing this:
<p class="button_image">
<a onclick="download(document.getElementById('one').value)"></a>
</p>
with:
<p class="button_image">
<a onclick="download(document.getElementById('one').value, document.getElementById('two').value)"></a>
</p>
and then replace your download function with this:
function download(file1,file2) {
if (file1 == 'default' && file2 == 'default'){
return;
}
else if(file1 != 'default'){
window.location = 'http://www.mysite.com/download/' + file1;
}
else{
window.location = 'http://www.mysite.com/download/' + file2;
}
}

Check if dropdown's selected option is not the first with JavaScript

Below are the options that I have in my HTML code:
<label id="subn">
<select name="subs" id="subs">
<option value="nothing">Choose a Subject</option>
<option value="General Question">General Question</option>
<option value="MemberShip Area">MemberShip Area</option>
<option value="Others">Others</option>
</select>
</label>
I want to create JavaScript code that will check whether the user selected an option other than the first one.
Here is what I tried:
if (document.getElementsByTagName('option') == "nothing"){
document.getElementById("subn").innerHTML = "Subject is Required!";
document.getElementById("subs").focus();
return false;
}
You can check like this if nothing is the first option (usually the case in my experience):
if (document.getElementById('subs').selectedIndex == 0){
To still compare based on the value, do this:
var sel = document.getElementById('subs');
if (sel.options[sel.selectedIndex].value == 'nothing') {
You may want to change your markup so the label is beside, like this:
<select name="subs" id="subs"></select><label id="subn" for="subs"></label>
Otherwise this part: .innerHTML = "Subject is Required!"; will erase your <select> :)
This should do it:
var index = document.your_form_name.subs.selectedIndex;
var value = document.your_form_name.subs.options[index].value;
if (value === "nothing"){
// your further code here.........
}
document.getElementsByTagName('option') gives a collection of all option elements in the document and "nothing" is a string. Comparing a collection to a string is quite useless.
Also setting document.getElementById("subn").innerHTML = "Subject is Required!"; will delete the select element, so document.getElementById("subs") wouldn't find anything any more.
If you just need to know if anything is selected check the selectedIndex property of the select element:
if (document.getElementById("subs").selectedIndex <= 0) {
// nothing is selected
}
EDIT: Changed > 0 to <= 0. I would assume that it should be checked if the user didn't select anything, too.

Categories