Choose from the dropdown menu that selects the same nth occurrence of an element

I have a series of buttons listed below:

<button id="serviceModal1" data-toggle="modal" data-target="#serviceModal1" tabindex="-1">Price 150€</button>
<button id="serviceModal2" data-toggle="modal" data-target="#serviceModal2" tabindex="-1">Price 250€</button>

And there's a contact form inside a modal with a dropdown menu.

<select name="menu-89" class="wpcf7-form-control wpcf7-select dropdown-menu" aria-invalid="false">
<option value="TOP 300 companies by fleet">TOP 300 companies by fleet</option>
<option value="TOP 300 companies by fleet">TOP 300 companies by fleet</option>
</select>

When button:nth-of-type(1) is clicked, option:nth-of-type(1) should be pre-selected, and so on.

$('#serviceModal1').click(function () {
    $('select option:eq(1)').attr('selected', 'selected');
});

How can I achieve this dynamically?

The modals are generated dynamically using ACF and Contact Form 7. Could this affect the functionality of some of the codes provided below?

<?php if( have_rows('modal','option') ):
    $counter3 = 1;
    while ( have_rows('modal','option') ) : the_row(); ?>
<div class="modal fade" id="serviceModal<?php echo $counter3; ?>" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
    <div class="helper">
    <div class="modal-dialog wide-grid">
        <div class="modal-controls">
            <div class="btn-next">
                <span class="ion-chevron-right"></span>
            </div>
            <div class="btn-prev">
                <span class="ion-chevron-left"></span>
            </div>
        </div>
        <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span class="ion-close"></span></button>
      <div class="modal-content">
        <div class="modal-body content-inner">
         <div class="flexing">
            <div  class="flex">
                <?php the_sub_field('modal-1','option'); ?>
            </div>
            <div class="flex">
                <?php the_sub_field('modal-2','option'); ?>
                <?php the_sub_field('form','option') ;?>
            </div>
         </div>
        </div>
      </div>
    </div>
    </div>
  </div>
<?php $counter3++; endwhile; endif; ?>

Even for testing purposes, the following code does not trigger the expected result:

$('button').click(function(){
    $('select.dropdown-menu option:eq(2)').attr('selected', 'selected');
});

Answer №1

To achieve this, you can retrieve the index() of the clicked button and then use it to select the corresponding option by utilizing eq(). Finally, set the selected option using prop(). Give this a try:

$('button').click(function() {
  $('select option').eq($(this).index('button')).prop('selected', true);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button data-toggle="modal" data-target="#serviceModal1" tabindex="-1">Price: 150€</button>
<button data-toggle="modal" data-target="#serviceModal2" tabindex="-1">Price: 250€</button>

<select name="menu-89" class="wpcf7-form-control wpcf7-select dropdown-menu" aria-invalid="false">
  <option value="TOP 300 companies by fleet">TOP 300 companies by fleet 150€</option>
  <option value="TOP 300 companies by fleet">TOP 300 companies by fleet 250€</option>
</select>

Answer №2

Make sure to select the option with the ID number at the end.

$("button[id^='serviceModal']").click(function () {
var num = /\d+(?=\D*$)/.exec($(this).attr('id'));
 $('select option:eq('+(num-1)+')').prop('selected', 'selected');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="serviceModal1" data-toggle="modal" data-target="#serviceModal1" tabindex="-1">Hind 150€</button>
<button id="serviceModal2" data-toggle="modal" data-target="#serviceModal2" tabindex="-1">Hind 250€</button>


<select name="menu-89" class="wpcf7-form-control wpcf7-select dropdown-menu" aria-invalid="false">
<option value="TOP 300 ettevõtet autopargi järgi">TOP 150 ettevõtet autopargi järgi</option>
<option value="TOP 300 ettevõtet autopargi järgi">TOP 250 ettevõtet autopargi järgi</option>
</select>

Answer №3

$('button[id^=serviceModal]').on('click', function(){
  var serviceId = $(this).attr('id').substr(12) - 1;
  $('select option:eq('+serviceId+')').prop('selected', true);
});

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

Navigating through a DOM string in Nuxt.js

I'm in search of a solution to parse a string containing DOM elements within Nuxt.js. The challenge lies in finding a parser that functions seamlessly on both the client and server side. Thus far, I've come across options that are limited to eit ...

Issues encountered with jQuery Form Plugin failing to pass a string value to PHP

I'm currently experimenting with the jQuery form plugin (http://jquery.malsup.com/form) to handle photo uploads and previews. However, I'm encountering an issue where the data strings expected to be sent to PHP using the ajaxForm function are com ...

Trigger jQuery to play audio files

Something seems off with this code. The audio file isn't playing when the webpage loads. $(document).ready(function() { var audioElement = document.createElement('audio'); audioElement.setAttribute('src','content/aud ...

What is the best way to iterate through a JSON AJAX response?

After receiving an array from my ajax query, I have the following code: .... success:function(response){ alert(response); } .... To achieve this, I want to implement a jQuery loop that triggers an alert() function for every item in the JSON array. ...

Tips for implementing jQuery on HTML loaded post document.ready():

I've encountered a scenario where I have multiple HTML elements being rendered by a JavaScript function on the page: <a href="#" class="test1">Test</a> <a href="#" class="test2">Test</a> <a href="#" class="test3">Test< ...

However, when it comes to the jQuery dropdown menu, the submenus open inwards rather than extending

I recently developed a jQuery menu that includes dropdowns. However, I encountered an issue where the subMenu items do not open to the left when hovered over. Despite my attempts to adjust the position using CSS properties such as absolute or relative posi ...

Using jquery Ajax to reference PHP functions through a specified URL

Hello, I am wondering if it is possible to fetch data from a PHP function using Ajax. I would like the URL in my Ajax request to target one of my functions. Here is an example of what I have: <?php class employee{ public function __c ...

The browser message states: Variable $? Not Found

As a newcomer to javascript (jquery/json), I've created code to display a chart using CanvasJS with a php/json data fetching script. However, I'm facing an issue where the chart is not rendering when I integrate my code. Upon inspecting the brows ...

Implementing the passing of value from view to controller in CodeIgniter through an onclick feature

I need to pass the button's id onclick from the view to the controller using ajax, but I keep getting this error: 500 Internal Server Error This is my view: <a data-toggle="modal"data-target="#Add_Money_to_campaign" ><button onclick="add ...

Binding data to buttons in Asp.net core

I'm currently studying ASP.NET Core MVC and I have a model that looks like this: public class Todo { public int Id { get; set; } [Required] public string Name { get; set; } [MaxLength(4096)] public string Content { get; set; } ...

Script fails to load upon accessing page through index hyperlink

I am facing an issue with my JavaScript elements not loading when I navigate to a form page from a link in the index. However, if I enter the URL manually or redirect from the login page, the JavaScript loads perfectly fine. The JavaScript code is consolid ...

Tips on Updating Array Value with jQuery

I have been working on using jQuery to edit array values. Here is my approach: From a modal, each time I click the "Add item" button, it pushes values to an array and appends the data to a table. var iteminfo = { "row": 'row' + cnt, "ma ...

"Enhance your website with autocomplete feature using the power of jQuery 1.4.2 and jQuery UI 1

Struggling to make jQuery autocomplete work. Despite searching for examples, most seem outdated. Modeled after a good example from the jQuery UI site but still can't get it to display data. My JSON data source is accessed via URL. [{ "pk": 1, "mo ...

developing a fresh node within the jstree framework

Recently, I have been working on creating a node using crrm as shown below $("#TreeDiv").jstree("create", $("#somenode"), "inside", { "data":"new_node" }); This specific function is triggered by a wizard, enabling me to seamlessly create a new node withi ...

Adjusting the navigation image as it passes through various div elements during scrolling

Is it possible to dynamically change an image in the navigation bar based on the user's scroll position? For example, I want pic1 to be displayed when the page content is at the top, then switch to pic2 once the user reaches the footer, and then back ...

updating numerous div elements using the jQuery load function

My SQL database contains various data, and on my webpage, I have numerous divs (around 30) showcasing this information. Each div corresponds to a different value in the database. My goal is to dynamically refresh these divs using the jQuery item.load() f ...

ways to validate the calling function in jquery

One of the challenges I'm facing is identifying which function is calling a specific error function that is used in multiple places within my code. Is there a method or technique to help determine this? ...

The occurrence of events for a basic model in Backbone is inexplicably non

I attempted to save some model data on localStorage (and even tried to catch this event and log some text to the console), but it didn't work - no errors and no events either. Here is my JavaScript code: var app = { debug: true, log: func ...

Using CSS and JavaScript to hide a div element

In my one-page website, I have a fixed side navigation bar within a div that is initially hidden using the display:none property. Is there a way to make this side nav appear when the user scrolls to a specific section of the page, like when reaching the # ...

Tips on obtaining the screen resolution and storing it in a PHP variable

Hey there! I've run into a bit of a roadblock that I'm struggling to overcome. I know that I need to incorporate some JavaScript to solve this issue, but I'm having trouble grasping how to do so. Here's the script I'm working with: ...