Reputation: 9121
Im wanting to bind input
and select
changes without jQuery
.
Currently i have the following in jQuery
$(':input').each(function(){
$(this).attr('value', this.value);
});
$('select').each(function(){
var Selected = $(this).children('option:selected');
$(this).children('option').removeAttr('selected', false);
Selected.attr('selected', true);
$(this).replaceWith($(this)[0].outerHTML);
});
$(':input').bind('keyup', function() {
$(this).attr('value', this.value);
});
$('select').change(function(){
var Selected = $(this).children('option:selected');
$(this).children('option').removeAttr('selected', false);
Selected.attr('selected', true);
$(this).replaceWith($(this)[0].outerHTML);
$('select').unbind('change');
$('select').change(function(){
var Selected = $(this).children('option:selected');
$(this).children('option').removeAttr('selected', false);
Selected.attr('selected', true);
$(this).replaceWith($(this)[0].outerHTML);
$('select').unbind('change');
});
});
How could this be done withou jQuery
?
Upvotes: 1
Views: 1689
Reputation: 34556
It's a question of knowing the native equivalents to jQuery shortcuts. So:
$(':input') //jQuery
document.querySelectorAll('input, select, textarea, button'); //native
And for jQuery's .bind()
, .change()
, .on()
or any other of its various event binding methods, there's .addEventListener()
in native.
So you just have to put them together. Grab all the elements, loop over them and bind to each of them:
var els = document.querySelectorAll('input, select, textarea, button');
[].forEach.call(els, function(el) {
this.addEventListener('keyup', function() {
//do something on key up
}, false);
if (el.tagName == 'SELECT') this.addEventListener('change', function() {
//also do something on change for dropdowns
}, false);
});
Upvotes: 2