SitePoint Sponsor

User Tag List

Results 1 to 2 of 2

Thread: Events

  1. #1
    SitePoint Addict
    Join Date
    Sep 2008
    Posts
    341
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    Events

    This is what I have:
    http://page-test.co.uk/js-test.html

    ..and it works exactly how I want it to, but I need it to work by doing these two things:

    (a) If you see in the change_button function, I have hard coded the 'name_can_vary' name element. I need to do it so this isn't hard coded (so it can work on any page/form).

    (b) I don't want to change any of the HTML, and I only want to change the code used in the change_button function (otherwise I will need to change many pages).

    Thanks in advance.

  2. #2
    Unobtrusively zen silver trophybronze trophy
    paul_wilkins's Avatar
    Join Date
    Jan 2007
    Location
    Christchurch, New Zealand
    Posts
    14,719
    Mentioned
    103 Post(s)
    Tagged
    4 Thread(s)
    Let's look at the form:

    HTML Code:
    <form autocomplete="off" method="POST" class='form-name'>
        <button type="submit" name="name_can_vary">Text Can Vary</button>
    </form>
    and the relevant scripting code is:

    Code javascript:
    function change_button(evt) {
        evt = evt || window.event;
        var targ = evt.target || evt.srcElement;
        targ.name_can_vary.innerHTML = "CHANGED - OK";
        ...
    }

    You have associated a function with the form onsubmit event, which means that you cannot easily gain access to the button that was used to trigger the event.

    Currently your code is retrieving the target that the event takes place on. Since the onsubmit event cannot take place on a button, but only with the form, it is the form that is the target of your onsubmit event.

    What this means is, is that the targ variable of your code is just the same as the this keyword, both being the form itself. So you could instead use this to get the element with a submit type:

    Code javascript:
    this.querySelector('[type="submit"]).innerHTML = "CHANGED - OK";
    Programming Group Advisor
    Reference: JavaScript, Quirksmode Validate: HTML Validation, JSLint
    Car is to Carpet as Java is to JavaScript


Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •