SitePoint Sponsor

User Tag List

Results 1 to 2 of 2
  1. #1
    SitePoint Enthusiast
    Join Date
    Jun 2014
    Posts
    70
    Mentioned
    1 Post(s)
    Tagged
    0 Thread(s)

    Modify JQuery script to allow for multiple on a page

    JSFiddle: http://jsfiddle.net/C8VmC/

    The first row of my fiddle works, however I need to have it modified so that it works for multiple on a page with the id's being Pixels_X and Percentage_X.

    Thank you for any help,

    Best Regards,
    Tim

  2. #2
    Unobtrusively zen silver trophybronze trophy
    paul_wilkins's Avatar
    Join Date
    Jan 2007
    Location
    Christchurch, New Zealand
    Posts
    14,729
    Mentioned
    104 Post(s)
    Tagged
    4 Thread(s)
    Quote Originally Posted by MrTIMarshall View Post
    JSFiddle: http://jsfiddle.net/C8VmC/

    The first row of my fiddle works, however I need to have it modified so that it works for multiple on a page with the id's being Pixels_X and Percentage_X.
    It sounds like you want to use a for loop:

    Code javascript:
    var pixel, percentage, i;
    for (i = 0; i < 100; i += 1) {
        pixel = document.getElementById('Pixels_' + i);
        percentage = document.getElementById('Percentage_' + i);
        ...
    }

    A better solution though is to not use sequentially named unique identifiers, and to use a class name instead.

    HTML Code:
    <input type="number" name="pixels[]" class="pixels"> 
    ...
    <input type="number" name="percentage[]" class="percentage">
    Code javascript:
    function addPixelPercentageHandler(pixels, percentage) {
        // add event to pixels and percentage field
    }
     
    var pixels = document.querySelectorAll('.pixels'),
        percentage = document.querySelectorAll('.percentage'),
        i;
    for (i = 0; i < pixels.length; i += 1) {
        addPixelPercentageHandler(pixels[i], percentage[i]);
    }
    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
  •