Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Find Parent Sibling First Child's First Child using Jquery

I’m trying to Use a combination of JS and Jquery here to select the input text (a few elements previous), when the button is clicked.

I know how to do this just using JS but i want to understand how to do this using jQuery. I get the error message in console: TypeError: ele.setSelectionRange is not a function. Which I take it means that it is not defining the Input Value the way I need it to.

I’m not using ID or Class here to identify the input.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Can someone help me here? Thanks

JS

$(document).ready(function () {
  $('.jimmy').click(function(e){
  e.preventDefault;
  jimsFunction(this);
  });
});

function jimsFunction(input) {
  let ele = $(input).parent().siblings(':first-child').children();
  ele.select();
  ele.setSelectionRange(0, 99999);
  navigator.clipboard.writeText(ele.value);
  alert("Copied: " + ele.value);
}

HTML

      <div class="colbody">
        <div>
          <input type="text" value="www.brave.com" readonly>
        </div>
        <div>
          <a href="www.google.com" target="_blank">View</a>                                
        </div>
        <div>
          <button type="button" class="jimmy">Copy URL</button>
        </div>
      </div>  

>Solution :

setSelectionRange(0, 99999) is not a method on jQuery object. Use it on DOM element.

So try: [0]

Example:

$('.jimmy').click(function(e) {
  e.preventDefault;
  jimsFunction(this);
});


function jimsFunction(input) {
  let ele = $(input).parent().siblings(':first-child').children();
  ele[0].select();
  ele[0].setSelectionRange(0, 99999);
  navigator.clipboard.writeText(ele[0].value);
  alert("Copied: " + ele[0].value);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="colbody">
  <div>
    <input type="text" value="www.brave.com" readonly>
  </div>
  <div>
    <a href="www.google.com" target="_blank">View</a>
  </div>
  <div>
    <button type="button" class="jimmy">Copy URL</button>
  </div>
</div>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading