Jump to content

Recommended Posts

I am trying to call a javascript function in the onclick event property of an html element. Problem is that it is going to apply to a different element of the form so I can't call it by saying like function(this.value) So what do I do to use a different one? Do I gotta do function(id.value)?

I am trying to call a javascript function in the onclick event property of an html element. Problem is that it is going to apply to a different element of the form so I can't call it by saying like function(this.value) So what do I do to use a different one? Do I gotta do function(id.value)?

 

I'm not sure if I'm understanding what you want to do - are you trying to have the click event of one form element affect the behavior/look/value/whatever of another element?  If so, it's not difficult.  There are two ways to go about it:

 

Inline:

<form ... >
   <input onclick="functionToRun('otherElementId');" ... />
   <input id="otherElementId" ... />
</form>

<!-- JavaScript snippet below should be where ever you put the rest of your script's code -->

function functionToRun(id) {
   var elementToModify = document.getElementById(id);

   // do things to elementToModify
}

 

Unobtrusive (my preference):

<!DOCTYPE html>
<html>
   <head></head>

   <body>
      <form ... >
         <input id="elementWithClick" ... />
         <input id="otherElementId" ... />
      </form>
   </body>

   <script type="text/javascript">
      var toggle = document.getElementById("elementWithClick");
      var target = document.getElementById("otherElementId");

      toggle.onclick = function() {
         // do things to the target element
      }
   </script>

</html>

 

Note that '...' denotes attributes and other things not important to the basic structure of the solution, but should still be present when you do it for real.  Also, since you weren't very specific in describing what you hope to do, this was a shot in the dark.  It may not be relevant to your actual problem.

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.