views:

102

answers:

4

How can I check if the number entered in the input-field is higher of even as th value in my 'min' field?

            <tr>
                <td>Steeeeaak</td>
                <td><input type="hidden" name="amount_5_min" value="10"/>
                <input type="text" name="amount_5" size="4" value="10"/></td>
                <td>-</td>
                <td><a href="/item/delete/eventId/2/hash/a8b5dzp9rks7164wh30j2anqh13w/itemId/5">Verwijder</a> </td>
            </tr>

As you can see the first part of the name of both fields are the same ... Any possibilities here? I do a submit at the end of the form, so I guess I have to do something on submit?

Thx!

+2  A: 
var fieldname = "amount_5";
var val1 = parseInt($("input[name="+field_name+"_min]").val(),10);
var val2 = parseInt($("input[name="+field_name+"]").val(),10);
// Compare the values

And to bind onto the submit action of the form

$("form#your_form_id_here").submit(funtion() {
    // Use above code
});

EDIT Kevin makes a good point

EDIT 2 Updated for any input name

Jamie Wong
It should probably be parseInt($..., 10) as someone could be 010 in the value, and that would convert it to octal and make 010 not equal to 10, even though they probably should be considered equal.
Kevin
The problem is: There are many rows of this ... so I can't hardcode the names.
koko
@kok See edit. Unless you meant you need to dynamically obtain the actual name of the field as well. Which is possible.
Jamie Wong
@jamie THx! I indeed need to get the names dynamically.
koko
+2  A: 

I'm guessing by the markup you posted that there are many rows, shopping cart style. In that case here's a way to loop though all rows checking the amounts on submit, just give your form/table IDs to match your selector:

$("#myForm").submit(function() {
  var valid = true;
  $("#myTable tr td input[name^='amount_']:last-child").each(function() {
    var val = parseInt(this.value, 10); //this value
    var min_val = parseInt($(this).siblings().val(), 10); //min_value
    if(val < min_val) {
      valid = false;
      alert($(this).closest('tr').children(':first').text() + //"Steeeeaak"
            " doesn't meet the minimum required value: " + min_val);
    }
  });
  return valid; //submit aborts if any didn't meet min value
});

This function makes use of the <input> elements being siblings, in a certain order and inside the same <td>, just using the known HTML structure to your advantage here.

Nick Craver
@Nick Thanks! There are also a few different tables with different names... How to make that dynamically too?
koko
You can leave the table ID off, or give them all the same class, e.g. `class="amountTable"` and use `.amountTable` instead of `#myTable` in the selector.
Nick Craver
+1  A: 

I'll throw this one out there just for fun (and partly because I just learned about ~~ today).

Try it out: http://jsfiddle.net/694dB/

It assumes the inputs are the only two (or at least the first two) in the row.

$('#myform').submit(function() {
    var $inputs = $(this).find('input[name^=amount]');

    var values = $inputs.map(function() {
        return this.value;
    }).get();

       // If it is less than the minimum, add a class,
       //    and return false to stop the submit
    if(~~values[1] < ~~values[0]) {
        $inputs.closest('tr').addClass("someNewClassName");
        return false;
    }
});

Updated based on your comment. Please note, that this is effective for one row. To do the same operation on several rows, you'll need to use a loop like @Nick provided in his answer.

Article on the double bitwise operator:

http://james.padolsey.com/javascript/double-bitwise-not/

patrick dw
Thx patrick! Your assumption is right, there are only 2 inpu-fields in a row. I tried the demo-code. It seems to be exactly what I need! Will try this after some sleep ;-)
koko
@koko - Sounds good. Let me know how it turns out for you. :o)
patrick dw
@patrick When I put a value higher then min, I als get the alert 'meets the minimum'. Is it possible to add a class to the row with the error? If there is an error, it still submits at the moment. How can I tackle that? As you can seet, I'm pretty new to JQuery :$
koko
@koko - I updated my answer to add a class and prevent the submit when there is an error. Let me know how it looks. :o)
patrick dw
A: 

In that case, use something like:

var elms = document.getElementsByTagName("input"); //get all input tags
var texts;
var minlengths;
for (input in elms) {
    var value = input.value; //'with' statement is evil
    if (input.type == "text") {
        texts.push(value);
    } else if (input.type == "hidden") {
        minlengths[value.substring(0, value.lastIndexOf("_"))] = value; //set what the field 'checks' = the minimum length
    }
}
for (text in texts) { //go back through the texts because the inputs might not be right after the texts
    var minlength = minlengths[text];
    var textnum = parseInt(text.value, 10);
    if (textnum === NaN || textnum > minlength) {
        alert("One of the fields is greater than the minimum length.");
    }
}

Note: This code is untested, and may not work. There is probably an "off by one" error somewhere in there.

Edit: In any case, you have to do this server-side too, because the user may tamper with the request. (Never trust the user) Is there any specific reason why you can't just use the minlength attribute on the text input fields?

Hello71
Hello71 - Is there such a thing? There's a maxlength, but I don't think there's a minlength. http://www.w3schools.com/tags/tag_input.asp Anyway, the OP appears to want to compare numeric values, as in greater than / less than. Not the number of characters.
patrick dw
Oops. Thought I had misread the question. Oh well.
Hello71
Why is `input.value` evil, as you state in your comment?
patrick dw
Sorry I wasn't clear, it's the 'with' statement that's evil. I used `value = input.value` instead of `with input`.
Hello71