Are there alternative approaches to using a for loop to determine if a value is present in a select box with JavaScript
?
I am interested in something similar to
document.getElementById('selbox').valueExists('myval');
Are there alternative approaches to using a for loop to determine if a value is present in a select box with JavaScript
?
I am interested in something similar to
document.getElementById('selbox').valueExists('myval');
using ES6 syntax:
const option = document.getElementById('selbox').querySelector('[value="' + my_value + '"]');
this code snippet will locate the first element with the attribute value="my_value".
Note: Apologies for any spanglish in my explanation :)
The functionality of the select
element cannot be extended, meaning that a separate function is required to determine if a value exists within it.
An alternative approach without using a loop entails...
function CheckSelectHasValue(select, value) {
var elem = document.getElementById(select);
if (elem !== null) {
return (elem.innerHTML.indexOf('value="' + value + '"') > -1);
} else {
return false;
}
}
if(!$('#select-box').find("option:contains('" + thevalue + "')").length){
//execute code block
}
When loading values from post parameters, I found success with this approach: if a value is missing from the select dropdown, an alert is shown to notify the user; otherwise, proceed as normal:
let selectElement = document.getElementById('your_select_id');
selectElement.value = target_value;
if (selectElement.value !== target_value) {
alert('The selected value is not available in the dropdown');
return;
}
accomplishing this task is possible using jquery
Utilize the Attribute Equals Selector
refer to
Verify value existence in select list with JQuery
implementing it in javascript can be done as follows
for (var i=0; i<document.getElementById('mySelect').options.length; i++)
{
if (document.getElementById('mySelect').options[i].text == seachtext)
{
alert('found');
break;
}
}
According to @Haim Evgi:
To filter the `select.options` as an array, you can use this method:
Array.from(nSelect.options).filter(nOption => /*true or false)*/
If the filtered array still has options after the filtering process, it means a match has been found so the length should be > 0.value
, while the second one is for searching by innerText
.function selectContainsOption(nSelect, nValue, nCheckValue, nCheckText){ // HTMLElement, ~String, ~boolean, ~boolean
nValue = (nValue == null ? "" : nValue);
nCheckValue = (nCheckValue == null ? true : nCheckValue);
nCheckText = (nCheckText == null ? false : nCheckText);
// get options as array, filter the array and check if there is any option left
return (
Array.from(nSelect.options).filter(
nOption => (nCheckValue && nOption.value == nValue) || (nCheckText && nOption.innerText == nValue)
).length > 0
);
}
<select>
<option value="1">Number 1</option>
<option value="2">Number 2</option>
<option value="3">Number 3</option>
<option value="4">Number 4</option>
<option value="5">Number 5</option>
<option value="6">Number 6</option>
<option value="7">Number 7</option>
<option value="8">Number 8</option>
<option value="9">Number 9</option>
<option value="a">Character a</option>
<option value="b">Character b</option>
<option value="c">Character c</option>
<option value="d">Character d</option>
<option value="e">Character e</option>
<option value="f">Character f</option>
</select>
<b> search: </b>
<input type="text" value="0" onchange="this.nextElementSibling.nextElementSibling.nextElementSibling.nextElementSibling.innerText = selectContainsOption(this.previousElementSibling.previousElementSibling, this.value, this.nextElementSibling.checked, this.nextElementSibling.nextElementSibling.checked);"/>
<input type="checkbox" checked="checked" onchange="this.previousElementSibling.onchange()"/>
<input type="checkbox" checked="checked" onchange="this.previousElementSibling.previousElementSibling.onchange()"/>
<b> contains: </b>
<span>false</span>
I'm encountering an issue with my javascript/jquery function that retrieves the selected dropdown value. Everything works fine in Chrome, but when I try to run my application in IE, it throws an error. $("#Application_AppCountries").change(function ( ...
In the world of JavaScript (ECMAScript 5), functions are highly esteemed (referred to as "first-class functions"). This unique characteristic allows us to treat functions as expressions, which means they can produce values and even include other expressio ...
After extensively searching and reviewing issues and documentation, it seems that apart from establishing a constraint between two Cannon bodies, there is no direct method to unite shapes of varying masses. Currently, I am using the lockConstraint approac ...
I am facing an issue with a PHP script that is supposed to parse an array using the json_encode() method, but it returns a blank output. Here is the PHP code snippet: $companies = $db->getCustomerNames(); print_r($companies) if (!empty($companies)){ $ ...
When I run the code below, I encountered an error stating: Uncaught exception: TypeError: Cannot convert 'validation.messages.field' to object $.fn.validate = function(validation) { $.each(validation.rules, function(field, fieldRules){ ...
I'm currently diving into Vue.js 2 and I have a goal of crafting a unique custom component in the form of <bs-container fluid="true"></bs-container>. My intention is for Vue.component() to seamlessly handle the bootstrap 3 container classe ...
Is there a clever method (perhaps using a map function) to restructure my data object from this: [ {id: 1, from: "1/1/2021", to: "1/2/2022"}, {id: 2, from: "1/3/2021", to: "1/4/2022"}, {id: 1, from: "1/5/2 ...
For my school project, I am using Express.js with TypeScript to create a simple app. This router is used for the edit page of a contact list we are developing. It displays the ID of the current contact being edited in the search bar. The problem arises whe ...
Having an issue with the Slick carousel where images are not resizing based on browser size (original size is 300x228px). Just to clarify: When I shrink the browser window, the number of slides decreases but the images remain the same size. I've bee ...
In my current project, I'm implementing mobile support by creating separate styles for desktop and mobile. Although most components are the same on both platforms, I have two .scss files dedicated to each. To apply the correct styles, I use a combina ...
Can anyone help me with a sorting issue I am having with a table on my website? I am using the jQuery plugin tablersorter to sort the table, but I have two headers that I do not want to be sortable. I tried to disable them using the example provided on the ...
I am facing an issue with creating a router-link in Vue and passing a route name as a prop. What I am trying to achieve is the following: <template> <div> <router-link :to="myProps">Login</router-link> </div> </tem ...
I have designed a mockup and now I am trying to bring it to life by creating a real component. View my component mockup here Starting with something simple, I created 3 buttons and an array. However, when I click on any button, all features are displayed ...
I'm currently facing a challenge in combining objects from an array of Objects in typescript. The structure of the array is as follows: 0: {type: 'FeatureCollection', features: Array(134)} 1: {type: 'FeatureCollection', features: ...
Is there a way to format a string as HTML when using it in the following syntax: <div> {{ text }} </div> Instead of displaying the actual HTML, only the text is shown - for example " ab " ...
Suppose you have a React component: interface Chat { someId: string; } export const Chat = (props: Chat) => {} and someId is defined in your mapStateToProps: function mapStateToProps(state: State) { return { someId: state.someId || '' ...
I've been working on a custom JQuery Calendar for selecting appointments, with the requirement to disable dates prior to the current date and highlight available dates in an orange color (#f48024). Unfortunately, my attempt using minDate hasn't b ...
Is there a way to create a custom function that changes the default ajax functionality? I currently have this ajax function implemented: $.ajax({ type: "POST", url: "http://" + document.location.host + '/userajax', data: 'type= ...
In the popular web browser Google Chrome, users can quickly jump to the next tab by pressing CTRL + TAB. Is there a way to change or disable this shortcut? The provided code snippet does not seem to work as intended. $(document).keydown(function(e){ ...
I've been struggling with a persistent issue that I just can't seem to solve. So, here's the situation: I have a blog post on a CMS that I'm developing. The content is saved within a div with its own unique ID. When the user clicks an ...