开发者

How to migrate a .change function from jQuery to plain Javascript

开发者 https://www.devze.com 2023-03-05 14:40 出处:网络
I\'m not a JS expert but i think what i\'m trying to do is pretty simple (at least in jQuery) I\'ve got 3 select

I'm not a JS expert but i think what i'm trying to do is pretty simple (at least in jQuery)

I've got 3 select

  <select id="faq" class="onchance_fill">...</select>
  <select id="pages" class="onchance_fill">...</select>
  <select id="faq" class="onchance_fill">...</select>

and an input (it's a tinyMCE one in advlink plugin)

<input type="text" onchange="selectByValue(this.form,'linklisthref',this.value);" value="" class="mceFocus" name="href" id="href" style="width: 260px;">

I want 开发者_如何学运维that each time i change a value in one of the 3 select, that this value of the option, will be placed in the input.

In Jquery, it would be something like :

$('.ajax_onchance_fill').change(function() {
        data = $('.ajax_onchance_fill').val();
        $('#href').text(data);
    });

But i can't use it. So what is the equivalent in plain Javascript ?

Thanks


I would advice you keep using Jquery as it speeds up this kind of thing but in pure JavaScript i think what you want looks something like this...

 <script type="text/javascript">
  function load() {
  var elements = document.getElementsByClassName('onchance_fill');
  for(e in elements){
      elements[e].onchange = function(){
          document.getElementById('href').value = this.value;
     }       
  }
  }
</script>


document.getElementsByClassName("ajax_onchance_fill").onchange = function() { 
   getElementById('href').value = this.options[this.selectedIndex].text;
};

Though I am not sure exactly if it'll work since getElementsByClassName returns more than 1 element.


Try this:

$('.ajax_onchance_fill').change(function() {
        var data = $(this).val();
        $('#mytextboxid').val(data);
    });


Okay, so I realize this thread is well over 8 years old, so this answer isn't so much for the OP (who probably figured it out long ago) as it is for someone else who might be curious about this particular topic.

All that said, here's a relatively simple and reliable way you could pull it off in vanilla JS:

/**
 * Since we need to listen to all three ajax_onchance_fill elements,
 * we'll use event delegation.
 * 
 */

const targetLink = document.getElementById('href'); 

    document.addEventListener('change', function(e) {

        if (!!Element.prototype.matches) { // Let's make sure that matches method is supported...

            if (e.target.matches('.ajax_onchance_fill')) {

                targetLink.textContent = e.target.value;

            }

        } else { // and if not, we'll just use classList.contains...

            if (e.target.classList.contains('ajax_onchance_fill')) {

                targetLink.textContent = e.target.value;

            }
        
        }   

    });
0

精彩评论

暂无评论...
验证码 换一张
取 消