0

I am attempting to have a button with a search value for our most common searches. What I was trying to do is user clicks button and inserts the text WITH the quotes "Some Text".

Right now this is what I am using for a single button. How would I make this so I can use one script with multiple buttons?

  <button onclick="searchText()" data-product-name="iPhone 12 Pro">iPhone 12 Pro Max</button> <----Current Button

<button onclick="searchText()" data-product-name="Pixel 5">Pixel</button> <---- Added for what Id like
<button onclick="searchText()" data-product-name="LG">LG</button><---- Added for what Id like
<button onclick="searchText()" data-product-name="Samsung S20 Plus">Samsung S20 Plus</button><---- Added for what Id like

  <script>
  var i = 0;
  var txt = '"iPhone 12 Pro Max"';
  var speed = 50;

  function searchText() {
    if (i < txt.length) {
      document.getElementById("search-query").value += txt.charAt(i);
      i++;
      setTimeout(typeWriter, speed);
    }
  }
  </script>

I tried adding the following but did not work.

var txt = element.getAttribute('data-product-name');

2 Answers 2

1

var i = 0;
var txt = '"iPhone 12 Pro Max"';
var speed = 50;
var elements = document.querySelectorAll('button')
for (let i = 0; i < elements.length; i++) {
  elements[i].addEventListener('click', function() {
    var txt = this.getAttribute('data-product-name');
    console.log(txt);
  });
}
<button data-product-name="iPhone 12 Pro">iPhone 12 Pro Max</button>
<button data-product-name="Pixel 5">Pixel</button>
<button data-product-name="LG">LG</button>
<button data-product-name="Samsung S20 Plus">Samsung S20 Plus</button>

Sign up to request clarification or add additional context in comments.

Comments

0

You can pass the id of the button to the searchText. and read the text using jquery or plain js

   <!--html --->
   <button onclick="searchText('buttonOne')" id= "buttonOne" data-product-name="Samsung S20 Plus">Samsung S20 Plus</button><---- Added for what Id like

   // javascript
   function(buttonId){
        var text = document.getElementById(buttonId).innerHTML
        // process the text with your business logic here
   }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.