Hide dropdown options with Javascript based on keyword in the URL - javascript

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();
}

Related

Pre-select a dropdown in a form from an external URL link

I have this form, and I can't change anything about it (ids, vals, etc) because its auto generated by my website builder. Is it possible to use code or even better, just use the URL to auto select an option? For example, use the URL
https://mywebsite.com/GCValue=50/
to select the 50 option in the form below, instead of the 10 that it will default on? I'm a beginner with JS and JQuery, so I'm happy to use those and learn a little bit about it during the process, if its possible.
<select id=GCValue>
<option val="10">10</option>
<option val="25">25</option>
<option val="50">50</option>
<option val="100">100</option>
<option val="250">250</option>
</select> <br />
Any help or external links pointing me in the right direction appreciated.
Using Just One Variable from JS Document Pathname
Use window.location.pathname to get the path of the current page, then use a simple regex.exec(url) to capture anything that matches /=([0-9])+/. This will match anything in the format of "=12345", and return "12345" as the match.
var url = "https://mywebsite.com/GCValue=50/";
// in reality, use this:
// var url = window.location.pathname;
var regex = /=([0-9]+)/g;
var match = regex.exec(url);
document.getElementById("GCValue").value = match[1];
<select id="GCValue">
<option val="10">10</option>
<option val="25">25</option>
<option val="50">50</option>
<option val="100">100</option>
<option val="250">250</option>
</select> <br />
Using Many Variables from JS Document Pathname
If you wanted to use many parameters, just extend the same logic. For instance, imagine: /GCValue=50/Page=765/Index=42/...
var url = "https://mywebsite.com/GCValue=50/Page=765/Index=42/";
// in reality, use this:
// var url = window.location.pathname;
var regex = /([A-Za-z0-9]+)=([0-9]+)/g;
var match;
while ((match = regex.exec(url)) != null) {
document.getElementById(match[1]).value = match[2];
}
<select id="GCValue">
<option val="10">10</option>
<option val="25">25</option>
<option val="50">50</option>
<option val="100">100</option>
<option val="250">250</option>
</select> <br />
<input id="Page" type="text"><br>
<input id="Index" type="text">
UPDATED
Here is a solution using url query parameters.
// Your link should look like this: https://www.boothemusic.com/gift-card/?price=50
const selectList = document.getElementById('GCValue');
const queryString = window.location.search;
const urlParams = new URLSearchParams(queryString);
const price = urlParams.get('price'); // change "price" to anything you want.
for (let option of selectList.options) {
let chosen = option.value;
if(chosen === price) {
selectList.value = price;
}
}
<select id="GCValue">
<option value="10">10</option>
<option value="25">25</option>
<option value="50">50</option>
<option value="100">100</option>
<option value="250">250</option>
</select>
const price = urlParams.get('price'); assigns the value associated with the given search parameter to price (Check this article to learn more about URLSearchParams).
Then for-of loop skims through select options and looks for a match for price variable. If any of the options match price (50 in this case), then its value is set as price hence selecting 50 on your dropdown.

There is a way to get all the option values in the SELECT TAG without an ID?

do you know if there is a way to take all the values in the OPTION VALUE included in a SELECT?
i Will show you an example, I have this code:
<SELECT onChange="chData(this,this.value)">
<OPTION VALUE=MIPS1 >MIPS
<OPTION VALUE=MSU1 >MSU
<OPTION VALUE=PERCEN1 >% CEC
<OPTION VALUE=NUMGCP1 >nCPU
</SELECT>
I only know the first value which is MIPS1, and I need to take the other values. The is a way to write that if I know the first MIPS1 I will search for the other values Included from the ?
Thanks in advance :)
You can get the <select> element that has an option with a specific value using something like this:
const select = document.querySelector('option[value=MIPS1]').closest('select');
Once you have the <select> element you can retrieve it's options using something like this:
const options = select.querySelectorAll('option');
Or:
const options = select.options;
As #charlietfl mentioned, .closest is not supported by all browsers, instead of that, you could use .parentElement.
jQuery version
var opt = "MIPS1";
const $sel = $("option[value='"+opt+"']").parent()
const options = $("option",$sel).map(function() { return this.value }).get()
console.log(options);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<SELECT onChange="chData(this,this.value)">
<OPTION VALUE=MIPS1>MIPS
<OPTION VALUE=MSU1>MSU
<OPTION VALUE=PERCEN1>% CEC
<OPTION VALUE=NUMGCP1>nCPU
</SELECT>
The example below shows how you can do this. The Jquery is fully commented.
Let me know if it isn't what you were hoping for.
Demo
// Create array
var options = [];
// Load option value you're looking for into a variable
var search_term = "MIPS1";
// Find option with known value, travel up DOM tree to select and then find all options within it
$("option[value='" + search_term + "']").closest("select").find("option").each(function() {
// Add values to array
options.push($(this).val());
});
// Print the array
console.log(options);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<SELECT onChange="chData(this,this.value)">
<OPTION VALUE=MIPS1>MIPS
<OPTION VALUE=MSU1>MSU
<OPTION VALUE=PERCEN1>% CEC
<OPTION VALUE=NUMGCP1>nCPU
</SELECT>
I think it is a bad idea not to give id to your html element in the first place, however if you need to do it that way, then the code below assumes you have only one select tag on your page.
let select = document.querySelector('select');
options = select.childNodes.filter((c) => c.tagName==='OPTION')
.map((o) => o.value);
console.log(options)
This will help you get: selected value, selected text and all the values in the dropdown.
$(document).ready(function(){
$("button").click(function(){
var option = $('option[value="MIPS1"]');
var select = option.parent();
var value = $(select).find(":selected").val();
var optionName = $(select).find(":selected").text();
var result = "value = "+value+"\noption name = "+optionName+"\nall values = ";
$(select).each(function(){
result+=($(this).text()+" ");
});
console.log(result);
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select>
<option value=MIPS1 >MIPS</option>
<option value=MSU1 >MSU</option>
<option value=PERCEN1 >% CEC</option>
<option value=NUMGCP1 >nCPU</option>
</select>
<button>click</button>

Default dropdown value on load from hyperlink with 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).

click on the link passing dropdownlist value to populate on clicked link

This opens url webpage but does not populate the dropdown list value.
Contact
function shout(){
var selectval = 'I am select value to set';
var selectname = 'I am name of the select dropdown';
var url = "http://example.com/shout?selected=" +selectval;
window.open(url);
}
I think you have to make some html elements
<select id="select">
<option value="value1">Value1</option>
<option value="value2">Value2</option>
<option value="value3">Value3</option>
<option value="value4">Value4</option>
</select>
Then add a javascript
var s = document.getElementById("select");
var val = s.options[s.selectedIndex].value;
var url = "http://example.com/shout?selected=";
var newurl = url+val;
window.location = newurl;
This is one method. Personally I would recommend php to use this the use the $_GET and $_POST and use a .htaccess to make the url not be like www.site.com/store/php?s=value1
Hope This helps.

How to give selected value to option with no value - javascript

I have a select witch is generated dynamically, it looks like this
<select id="elem">
<option value="3">value 1</option>
<option value="6">value 2</option>
<option value="18">value 3</option>
<option>value 4</option>
</select>
The last option has no value. I am trying to make the select to display the "value 4" option on the first position when the page is loaded, using javascript
Here is what i tried in javascript
var elem = document.getElementById("elem"),
selectedNode = elem.options[elem.selectedIndex];
if ( selectedNode.value === "" ) {
selectedNode.setAttribute('selected','');
}
How can it be done ?
When no value is specified, the value will be the text. You can use hasAttribute to check for the value as well:
var select = document.getElementById("elem");
for (var i = 0; i < select.options.length; i++) {
if (!select.options[i].hasAttribute('value')) {
select.options[i].selected = true;
}
}
Demo: http://jsfiddle.net/tymeJV/682Ap/1/
several ways to do it. if you need to find the option first, the code would be like this . It's looking for an option with non numeric value - unfortunately if you omit the value the text of the option becomes its value
var sel = document.getElementById("elem");
var index = 0;
for(var i = 0;i<sel.options.length;i++){
if (isNaN(sel.options[i].value))
index = i;
}
if you know the index, you can set the selected option as
sel.selectedIndex = index;

Categories