koders
koders

Reputation: 5794

Reference to the caller element in JavaScript

I want to access to the caller element within a function, with something like:

// Script
<script type="text/javascript">

window.onload = function() {
   var field = document.getElementById("myfield");
   field.onkeyup = change(field);
   function change(x) {
      if (x.value == "") {
          x.value = "No value";
      }
   }
}

</script>


// Body
<input id="myfield" type="text">

This doesn't work. And I don't want to give onkeyup methods to every single element, I want to register them programmatically. Any solutions ?

Upvotes: 0

Views: 209

Answers (3)

Shomz
Shomz

Reputation: 37701

The problem is that you're assigning a function return value to field.onkeyup, while instead it needs to be a function:

field.onkeyup = function(){
    change(field);
}

var field = document.getElementById("myfield");
field.onkeyup = function(){
  change(field);
}
function change(x) {
  if (x.value == "") {
    x.value = "No value";
  }
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<input id="myfield" type="text">

However, for that same functionality (though I know you want to learn how to bind events in JS), I recommend simply using the placeholder attribute like this:

<input id="myfield" type="text" placeholder="No value" />    

<input id="myfield" type="text" placeholder="No value" />

That's it, no JS needed and it behaves much better.

Upvotes: 1

alessandrio
alessandrio

Reputation: 4370

value is only to input.

var diva = document.getElementById("mydiva");
diva.onkeyup = change(diva);
function change(x) {
   if (x.value === "") {
       x.value = "No value";
   }
}

//different
var element = document.getElementById('element');
element.onkeyup = function(){
  if(element.value==="") element.value='sfdfgfd';
};

var divb = document.getElementById("mydivb");
if(divb.innerHTML===''){
    divb.innerHTML='No content';
}

var divc = document.getElementById("mydivc");
divc.onkeyup = dchange(divc);
function dchange(y) {
  if(y.innerHTML===''){
    y.innerHTML='No contenible';
  }
}
<input id="element" type="text"><hr>
<input id="mydiva" type="text">
<div id="mydivb"></div>
<div id="mydivc" contentEditable="true"></div>

Upvotes: 0

rosscosack
rosscosack

Reputation: 67

To access the element that triggered the event you can do this

element.onkeyup = function(e){
  var targetElement = e.target;
} 

Upvotes: 0

Related Questions