Get value from array based on user input in jQuery

Related searches

I have an array with the alphabet, each letter has a URL attached with it. I also have a list of buttons, each corresponding to a letter of the alphabet.

I want to retrieve the value from the array (url) based on which button the user clicks, the user may click multiple buttons.

So if the user click the button "C", I want to get to retrieve the URL associated with the letter "C" from the array.

I was able to loop through the #letters element's children and get the id of each button. I thought about comparing it against the array somehow but I got lost along the way.

I really have no solution in sight.

HTML

<div class="col-md-12" id="letters">
   <a href="#" class="btn btn-primary" id="A">A</a>
   <a href="#" class="btn btn-primary" id="B">B</a>
   <a href="#" class="btn btn-primary" id="C">C</a>
</div>

Javascript

$(function() {
    let array = {
        'A' : 'http://example.com/A.png',
        'B' : 'http://example.com/B.png',
        'C' : 'http://example.com/C.png',
    };

    $.each(array, function(key, value) {
        console.log('Initializing...', key + ' => ' + value);
    });

    let letters = $('#letters');
    $.each(letters.children(), function(i) {
        console.log(letters.children()[i].id); // get value of id tag
    });
});

Use data-* attribute and add event listener to your letters, on click get the clicked item and get the letter using .data().

$(function() {
    let array = {
        'A' : 'https://images.pexels.com/photos/67636/rose-blue-flower-rose-blooms-67636.jpeg?cs=srgb&dl=beauty-bloom-blue-67636.jpg&fm=jpg',
        'B' : 'https://images.pexels.com/photos/1308881/pexels-photo-1308881.jpeg?cs=srgb&dl=ao-dai-beautiful-beauty-1308881.jpg&fm=jpg',
        'C' : 'https://images.pexels.com/photos/237018/pexels-photo-237018.jpeg?cs=srgb&dl=asphalt-beauty-colorful-237018.jpg&fm=jpg',
    };
  
  $('.btn-primary').on('click', function() {
    
    const letter = $(this).data('letter');

    $('#demo').attr('src', array[letter]);
  });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
  <div class="col-md-12" id="letters">
   <a href="#" data-letter="A" class="btn btn-primary" id="A">A</a>
   <a href="#" data-letter="B" class="btn btn-primary" id="B">B</a>
   <a href="#" data-letter="C" class="btn btn-primary" id="C">C</a>
</div>
  <img width="300" id="demo" src="" />

Get value from array based on user input in jQuery, Use data-* attribute and add event listener to your letters, on click get the clicked item and get the letter using .data() . $(function() { let array� Jquery get input array field. use map method we can get input values that stored in array. Add a number of input fields based on a dynamic value in PHP. 0.

Here is a snippet that I get all the links and attach a click event on then, that simply logs the value which the key corresponds to the clicked button id

(function(){
    let array = {
        'A' : 'http://example.com/A.png',
        'B' : 'http://example.com/B.png',
        'C' : 'http://example.com/C.png',
    };
    
    const buttons = document.querySelectorAll('#letters a');
    buttons.forEach(button => {
      button.addEventListener('click', (e) => console.log(array[e.target.id]));
    });
})();
<div class="col-md-12" id="letters">
   <a href="#" class="btn btn-primary" id="A">A</a>
   <a href="#" class="btn btn-primary" id="B">B</a>
   <a href="#" class="btn btn-primary" id="C">C</a>
</div>

.map(), As the return value is a jQuery object, which contains an array, it's very common to call .get() on <input type="text" name="url" value="https://johnresig.com/">. Hello, everybody. I am newbie as my question shows. I will paste here a code that I combined from around the web and managed to work. But there is something

There's no point in writing links in HTML if you plan on having more in the future. Save yourself some time and generate them dynamically. Provided below is a reusable function listLnx() that will generate <a> in HTML from a given list of nearly an unlimited amount of urls. Full details are commented in demo.

// An Array of Arrays each sub-array has a key/value pair
let urls = [
  ['A', 'https://example.com/'],
  ['B', 'https://stackoverflow.com'],
  ['D', 'https://stackoverflow.com/users/2813224/zer00ne'],
  ['C', 'https://css-tricks.com'],
];

/*** listLnx()
1st Param: [Array] (see above)
2nd Param: [String] (optional--default: "body") the tag in which the links 
           will be nested within
*/
/*
*A - Reference the parent tag
*B - Instantiate  Map Object from the array. Array is 
     reversed because the links are prepended to parent
*C - Iterate through map with a for...of loop. The       
     entries() method returns an array of key/value pairs
     which is destructured for easy access
*D - An <a> is created with .createElement() method. The 
     remaining statements assemble each link with the
     following: 
     1. an #id
     2. a [href]
     3. text of #id and hostname
     4. block level style
     5. then prepended to parent tag
*/
const listLnx = (array, selector = `body`) => {
  let node = document.querySelector(selector); //A
  let map = new Map(array.reverse()); //B

  for (const [key, url] of map.entries()) { //C
    const a = document.createElement('a'); //D 
    a.id = key; //1
    a.href = url; //2
    a.textContent = `${key} - ${a.hostname}`; //3
    a.style.display = 'block'; //4
    node.prepend(a); //5
  }
}

listLnx(urls);

.val(), "input[type=checkbox][name=bar]:checked" ).val(); Get the single value from a single select and an array of values from a multiple select and display their� Answer: Use the jQuery val () Method. You can simply use the jQuery val () method to get the value in an input text box. Try out the following example by entering something in the text input box and then click the "Show Value" button, it will display the result in an alert dialog box.

How to get values from inputs ( array ), Re: How to get values from inputs ( array ) <script type="text/javascript"> $(function(){ $('#AllParts').submit(function(e){ var errors=false. $('tr:has(.Part)').each(function(){ var part=$('.Part',this).val(), price=$('.Price',this).val().replace(/,/g,"."), validPrice=price!="" && ! isNaN(price); There is a Input Element, the task is to set its value using JQuery. Here are a few examples discussed. To understand example first few methods to know. JQuery val() method: This method return/set the value attribute of selected elements. If we use this method to return value, it will return the value of the FIRST selected element.

.serializeArray(), Description: Encode a set of form elements as an array of names and values. < input type="submit" name="g" value="Submit" id="g">. </div>. </form> Get the values from a form, iterate through them, and append them to a results display. HTML Forms contains various elements like input fields, options, textarea etc. and for further processing, we need to get value of each field using jQuery. This tutorial, Explains about, how to get input values of different HTML form elements using jQuery as follows:

The .val () method is primarily used to get the values of form elements such as input, select and textarea. When called on an empty collection, it returns undefined. When the first element in the collection is a select-multiple (i.e., a select element with the multiple attribute set), .val () returns an array containing the value of each selected option.