www.webdeveloper.com
Results 1 to 2 of 2

Thread: Javascript Filter on Variable Set

  1. #1
    Join Date
    Dec 2013
    Posts
    1

    Javascript Filter on Variable Set

    I have the following code on my page that I need to apply some filters to:

    Code:
    <script type="text/javascript">
        function check() {
            var elements = document.getElementsByName("quantity");
            var qtycheck = document.getElementById("qtycheck").value;
    
            for (var i=0; i<elements.length; i++) {
                var nmbr = elements[i].value;
                if (nmbr > <?php echo $maxqtyorder; ?>){
                    alert("You've selected more treats than your package allows.");
                    return false;
                }
                else if (nmbr > qtycheck){
                    alert("You've selected more treats than your package allows.");
                    return false;
                }
            }
            return true;
        }
    </script>
    The 2nd line:
    Code:
    var elements = document.getElementsByName("quantity");
    I want to get all the elements by name of quantity but exclude the ones that have an ID of quantity2442 and quantity2443.

    Is there a way to do this when setting the variable?

  2. #2
    Join Date
    Dec 2011
    Location
    Centurion, South Africa
    Posts
    795
    Only way I can think of is doing a manual filter during a loop:

    Code:
    <script type="text/javascript">
    
    	var
    		i, j, elements = [];
    
    	for (i = 0, j = document.getElementsByName('quantity'); i < j.length; ++i) {
    		if (
    			('quantity2442' !== j[i].id) &&
    			('quantity2443' !== j[i].id)
    		) {
    			elements.push(j[i]);
    		}
    	}
    
    	console.log(elements); // shows 8 of 10 elements
    
    </script>
    The html I tested with

    HTML Code:
    <input name="quantity" />
    <input name="quantity" />
    <input name="quantity" />
    <input id="quantity2442" name="quantity" />
    <input name="quantity" />
    <input name="quantity" />
    <input name="quantity" />
    <input id="quantity2443" name="quantity" />
    <input name="quantity" />
    <input name="quantity" />
    Last edited by bionoid; 12-07-2013 at 03:14 AM.
    JavaScript: Learn | Validate | Compact | bionoid

Thread Information

Users Browsing this Thread

There are currently 1 users browsing this thread. (0 members and 1 guests)

Posting Permissions

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



Recent Articles