Top technique for extracting the value of a button using JavaScript

I am looking to extract the value of the value attribute from the button element and input it into a different modal.

Within my PHP loop, I generate the following HTML:

<button data-toggle="modal" data-target="#mod-error" type="button" class="myclasses btn" value="1">Confirm</button>
<button data-toggle="modal" data-target="#mod-error" type="button" class="myclasses btn" value="2">Confirm</button>
<button data-toggle="modal" data-target="#mod-error" type="button" class="myclasses btn" value="3">Confirm</button>

Upon clicking a button, a modal appears with two options: continue or cancel. My goal is to save the value attribute of the first button in the href attribute of the "continue" button within the second modal.

The structure of my modal looks like this:

<div class="modal-body">
    <div class="text-center">
        <div class="i-circle danger"><i class="fa fa-times"></i></div>
        <h4>Are you sure?!</h4>
        <p>If yes click on Continue!</p>
        <div class="modal-footer">
            <button type="button" class="btn btn-default" data-dismiss="modal">Cancel</button>
            <a href="IWANTGETIDHERE">
                <button type="button" class="btn btn-danger" data-dismiss="modal">Continue</button>
            </a>
        </div>
    </div>
</div>

You can view a demo of my modal here.

Answer №1

Utilizing jQuery for Event Handling:

$(document).ready(function() {
    $('.button').click(function() {
        alert($(this).attr("value"));
    });
});

To update instead of using an alert, you can do the following:

$('.footer-links a').attr("href", $(this).attr("value"));

View the JSFiddle demonstration

Using Vanilla JavaScript for Event Handling:

document.getElementById('button').onclick = function() {
    document.getElementById('link').setAttribute('href', this.value);
}

Check out the JSFiddle example

Answer №2

var btn = document.querySelector("#buttonID");
btn.addEventListener("click", function(){
document.querySelectorAll(".class")[0].href =  document.getElementById("buttonID").value;
});

In case you prefer no external dependencies.

Answer №3

One approach you can take is to include a unique data-customId attribute and eliminate the value from each of your buttons:

<button data-customId="4" data-toggle="modal"  data-target="#mod-error" type="button" class="custom-button btn">Submit</button>
<button data-customId="5" data-toggle="modal"  data-target="#mod-error" type="button" class="custom-button btn">Submit</button>
<button data-customId="6" data-toggle="modal"  data-target="#mod-error" type="button" class="custom-button btn" >Submit</button>

Additionally, assign an id to your modal div such as:

<div id='confirmAction' class="modal-dialog">
    <!-- Content -->
</div>

Subsequently, set up an event handler for the bootstrap show event:

$('#confirmAction').on('show.bs.modal', function (event) {
    $id = $(event.relatedTarget).attr('data-customId'); // Retrieve the customId
    $(this).find('span:first').attr('href', $id);
});

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

Creating a multi-dimensional array by combining two arrays based on their matching unique values

I am embarking on a journey to develop my very first API using Node.js (a completely new endeavor for me). Within this project, I have two arrays named "rooms" and "room_availability." The primary goal is to merge all entries from the "room_availability" a ...

Is there a way to include space at the beginning of a form label with react-bootstrap?

I am currently working on incorporating a form that is perfectly centered on the page, featuring standard login fields for both email and password inputs. Strangely enough, the label for the email input appears to be getting prefixed with an additional spa ...

What is the rationale behind not passing $scope to a service in AngularJS, and is it considered bad practice?

Is it advisable not to pass $scope to a service for certain reasons? I understand that services are intended to be reusable singletons, and passing a (potentially) large object to the service could lead to maintenance issues. However, assuming there is so ...

Angular2 Error: Issue with the "match" function in JavaScript

Why am I receiving a typeerror that says "cannot read property of 'match' undefined"? var numInput = document.getElementById('input'); // Listen for input event on numInput. numInput.addEventListener('input', function(){ ...

Is it dangerous to assign innerHTML to a div using ReactJS?

I want to display a status message based on the response received from an axios POST request. Here is my code: import React from 'react'; import axios from 'axios'; const handleSubmit = (email, pass) => { const data = { ...

Ways to determine if a web browser is executing javascript code (without altering the javascript on the webpage)

Working on creating a custom PHP client for Selenium, I've encountered an issue with implementing the waitForPageToLoad() function: The problem lies in just checking the document.readyState, as there could be JavaScript scripts running on the page (l ...

trigger form submission and refresh on React JSON Schema Form

I'm currently utilizing react-jsonschema-form to create a form, but I'm facing an issue where the function linked to the onSubmit button isn't executing. It's puzzling why clicking the button causes the page to reload without running th ...

What is the best way to determine the midpoint index of an array?

As a newcomer, I have a question regarding a recent assignment. The task involves creating a global array where objects are imported as they are entered into an input field on the HTML document. The challenge is to update the current list on the document ...

I'm experiencing trouble with Shopify as it appears to be failing to execute

I have been attempting to incorporate a tracking pixel into my project. Thus far, I have tested the code in various environments, both with and without wrapping it in a function and deploying it using window.onload. If you would like to see the implementa ...

What is the best way to create query strings for AJAX URL using jQuery or JavaScript?

At the moment, I am implementing ajax and jquery to dynamically update search results based on different filtering categories within a form. My challenge lies in the fact that I aim to pass varying variables to the URL used for ajax, derived from checkbox ...

The main React component fails to fully load the index.html file

I am a beginner in the world of reactjs and I have encountered a problem with loading CSS in the head and JS libraries and plugins at the end of the body in my template. Here is how my index.html looks: <!DOCTYPE html> <html lang="en"> <hea ...

Incorporate checkboxes within a dropdown menu using JavaScript

Is there a way to achieve something similar in pure JavaScript, without relying on jQuery? ...

My initial reaction to the code

I recently completed my first React code, which is the classic "Hello World" example. Unfortunately, I'm encountering some issues with it and despite trying various solutions, nothing seems to work. Below is the code snippet: <html> <h ...

How can I transform my jQuery code into a React Component?

When it comes to updating the CSS of an element in React, I initially turned to jQuery but later discovered that is not recommended. So now I am seeking guidance on how to achieve this task properly without using jQuery. If necessary, I can provide additi ...

Incorporating Bootstrap Extensions into Angular 8

Recently delving into Angular, I've been attempting to incorporate a Bootstrap Plugin called Bootstrap Toggle into Angular 8. Below are the steps I've taken: First, I installed bootstrap, jquery, popper.js, and bootstrap-toggle. In the angular. ...

Calculating different percentages from a reduced map containing JSON data

Forgive me in advance if there's a similar question out there, but after a day of searching, I couldn't find what I need. I'm calling an API that responds with data, and I've extracted the necessary details to create a JSON file with t ...

Is it possible to delay the execution of a JavaScript export statement in any way?

My current project involves developing a tool using React and Redux. To fetch data from the server, I am utilizing whatwg-fetch. The reducer in my code is responsible for creating its store within a callback function after the data has been successfully fe ...

The 'async' keyword is not permitted in this context within a TypeScript React application

An issue has arisen with the aync, indicating that the async modifier is not permitted in this context: private async getValue= (acc: Access): void => { await this.service.getForm(''); } It appears that there might be an ...

What are the different kinds of properties that can be used in Vue.js

When working with Javascript, I can create arrays that hold different types of data elements like: var ex = ['name', 12, true]; console.log(ex); In Vue JS, when defining props for a component within a single file template, I have the option to ...

When should the preloader be placed within the DOMContentLoaded or load event?

I'm looking to implement a preloader on my website to ensure everything is fully loaded - images, JavaScript, fonts, etc. However, I'm unsure whether to use the following: window.addEventListener('DOMContentLoaded', () => { // code ...