Home > Software design >  Find Parent Sibling First Child's First Child using Jquery
Find Parent Sibling First Child's First Child using Jquery

Time:06-03

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.

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 >
        <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" >Copy URL</button>
        </div>
      </div>  

CodePudding user response:

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 >
  <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" >Copy URL</button>
  </div>
</div>

  • Related