What is the best way to incorporate a function that works seamlessly with elements?

For the elements with corresponding 'li' that has a selected class, I need to set the selected property only for those specific 'option' elements. The value is determined by the data-input-value attribute in the 'li' and the value attribute in 'option'.

<div class="wrapper">
        <select name="name">
          <option value="val1">name1</option>
          <option value="val2">name2</option>
        </select>
        <ul data-input-name="name">
          <li data-input-value="val1" class="disabled">name1</li>
          <li data-input-value="val2" class="enabled selected">name2</li>
        </ul>
      </div>

Answer №1

$('select[name="name"] option').each(function() {   
  if ($('li[data-input-value="' + $(this).val() + '"]').hasClass('selected')) {
    $(this).prop('selected', true);   
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="wrapper">
  <select name="name">
    <option value="val1">name1</option>
    <option value="val2">name2</option>
  </select>
  <ul data-input-name="name">
    <li data-input-value="val1" class="disabled">name1</li>
    <li data-input-value="val2" class="enabled selected">name2</li>
  </ul>
</div>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The best way to horizontally arrange card-images side by side in react native

Recently delving into the world of react native, I encountered an issue with aligning card images side by side using react-native-elements. My goal is to have two rows on phones and three rows on tablets. However, despite setting the flex-direction to row ...

In what way can the button display the permission directly on the page?

When the website notification is granted, a green button should be displayed. If it is denied, show a red button instead. The button comes with a CSS style and a checkbox but does not have the permission to grant or allow any permissions on the page. Butt ...

I'm having trouble inserting my object into the scene: THREE.Object3D.add: the item is not a valid instance of THREE.Object3D

Recently, I started using three.js. Initially, I utilized a JSON file for my 3D model but encountered issues when exporting it from Blender. To resolve this, I decided to switch to obj files. Although the new obj model is working fine, I am struggling with ...

Is `send()` considered an anonymous function?

I am testing ajax on a local server, but encountering an issue where the console is showing that send() is being identified as an anonymous function and I am receiving a blank document. The console displays: XHR finished loading: GET "http://localhost/js ...

Inheritance best practices for node.js applications

In C#, the concept of inheritance can be easily demonstrated through classes like Animal and Dog. class Animal { string name; public Animal() { } } class Dog : Animal { public Dog() : base() { this.name = "Dog"; } } When working ...

Assign the returned auth2 value to an Angular variable

I've been searching for a solution to my issue without much success, even though it seems like it should be an easy fix. Currently, I am using AngularJS and Google auth2 for authentication to fetch the logged in user's information. My goal is to ...

Unable to execute main JS template in Angular partial view, JQuery function also fails to work on the partial view

As a newcomer to angular, I am facing a challenge with the JS file that I have initiated on the index.html page. While working with angular, I have had to create partial views of different pages. The functions in this file handle tasks such as minimizing a ...

Angular is having trouble establishing a connection to the WebSocket server using the socketio-client library

I've been tackling a project that requires the use of websockets. I have successfully set up a websocket server (quarkus) and tested it with insomnia, where I was able to connect and send messages without any issues. However, when attempting to conne ...

Transform a PHP array into a JavaScript array with UTF-8 encoding

I am currently facing an issue with a products table that contains foreign characters. My goal is to utilize a PHP array in JavaScript to filter a dropdown box as the user types. Everything seems to be working fine except when encountering foreign characte ...

Does GIF animation operate on the same thread as JavaScript in all popular web browsers?

When my AJAX request is in progress, an animated GIF is displayed to show activity. However, I have noticed that the animation freezes while the response from the request is being processed by a script that heavily updates the DOM. After researching this ...

Can you explain the function of the /echo/json/ url on this jsfiddle?

I'm clear on the code below, but I'm intrigued by this URL structure: /echo/json/. Take a look at this jsfiddle. In the code snippet, data is being posted to the URL /echo/json/, even though it doesn't seem to be a valid endpoint. Can some ...

Using Angular to display error messages based on conditions with ngIf and Else statement

Hey there! I have an array that I am looping through and displaying the id as a link. errMsg: string const group = [ { "name": "TSPM Process Connector Validation", "values": [ { ...

My Contentful code is not functioning properly in NodeJS

I am encountering an issue with the code below, which is meant to display content of type "course." When I try to access http://localhost:3000/api/courses, the browser keeps loading indefinitely without any error messages in the console. Interestingly, t ...

Troubleshooting Problems with Adjusting Left Margin Using JQuery

function adjust_width() { $('#cont').toggle(function(){ $('#cont').animate({marginLeft:'0%'}); },function(){ $('#cont').animate({marginLeft:'18.4%'}); }); } The code above is in ...

using style binding with event handling in vue.js

I am trying to toggle one element and, at the same time, bind styles to another element. I'm having trouble figuring out how to do this using @click. data(){ return { show:false, filterStyle: { top: 0, back ...

What is the best way to modify the state of an array of objects by applying a filter in Vue 3?

I am currently facing an issue with a component that is listening for an emit and then attempting to filter out a user with a specific userId from the users state. The challenge lies in the fact that assigning filteredUsers to users does not appear to be ...

What is the method for assigning a value to a knockout observable using jQuery?

There is a span element present on an HTML page. <span id="Amount" value="<?php echo $userProvidedAmount ; ?>"></span> Within my knockout code, I am attempting to incorporate this value into an observable using jQuery. However, despite ...

Looking to optimize this code? I have three specific tags that require reselection within a given list

for (var i=0; i<vm.tags.length; i++) { if (selectedTags[0]) { if (vm.tags[i].term_id === selectedTags[0].term_id) { vm.tags[i].border1 = true; } } if (selectedTags[1]) { if (vm.tags[i].term_id === selecte ...

Encountering an unexpected token error in React.js

As a new learner of React, I am still getting acquainted with JavaScript. It has been my first week attempting to import React, and finally adding the CDN script tag into my index.html. Normally, I can easily add XML tags into JS files, but when trying to ...

Notification that appears when accessed on a mobile device

I have encountered an issue with my website where mobile users are being continuously redirected to the mobile site due to the hosting of the sites in different places preventing the use of cookies to remember the redirection. As a result, a loop occurs. ...