jquery.validate: multiple fields add up to value [duplicate] - javascript

This question already has an answer here:
JQuery Validate: How do I add validation which checks the sum of multiple fields?
(1 answer)
Closed 8 years ago.
I'm working on a form where the user enters a total, then enters more values into other fields that represent a dividing up of that total. For example:
<input type="text" name="total" />
<input type="text" name="portion[1]" />
<input type="text" name="portion[2]" />
<!-- and so on -->
<input type="text" name="portion[n]" />
If the user enters 123.45 into total, then they need to fill out the portions 1 - n such that their values add up to 123.45. Each portion field is required to be a positive number or 0 but those are the only other restrictions on them.
The jquery.validate plugin has an equalTo validation method, but this can only seem to cope with a single field, rather than a set.
Is there a way to
Define a validation rule that will validate the total of the group of fields against the total field
Get a single message to display for the group of fields if they don't add up

Try this function with a jquery event
function Mvalidate()
{
var total=$('[name=total]').val();
var n=10; // no of portions
var partialsum=0;
for(var i=0;i<n; i++)
{
var t=$("[name=portion["+i+"]]").val();
partialsum+=parseFloat(t);
}
if(partialsum<total)
alert("Portions add up not complete!");
}
$("#checkbutton").click(function()
{
Mvalidate();
});

#Krishnan:
according Jquery Doc the
$('.total').
is a class selector, isn't it? If you want to look for an element with a name attribute, you have to write it as follow:
$("[name='total']").val();
$("[name='portion["+i+"]']").val();
If you know there is only an input field with that name, you can use
$("input[name='total']").val();

This question looks like it has some answers that could be useful in solving this problem.

Related

Disallow input if it matches predefined values

I would like to disallow certain input into an html input field.
Manually type in a value in a "Select" / Drop-down HTML list? this question covers how to recommend values while letting the user type.
I would like to let the user type and 'blacklist' certain values if they matches one of my predefined values and show a warning.
What is the easiest way to achieve this?
function myFunction(e) {
const val = e.value;
const blacklist = ["12345678", "qwerty"];
if (blacklist.indexOf(val) >= 0) alert("Blacklist");
}
<p>A function is triggered when the user releases a key in the input field.</p>
Enter your name: <input type="text" id="fname" onkeyup="myFunction(this)">
You need to play with keyup event and provide a blacklist. You can do whatever you want with val, you could check if it's one of blacklist values(example above) or if it matches a RegExp pattern.
You can also use a regular expression. It's only possible to submit the form if the text does not contain foo.
<form action="#">
<input type="text" name="xx" pattern="^((?!foo).)*$"><br />
<input type="submit">
</form>

How to edit dynamic form fields to create a single hidden field comprised of the value of two fields

I need to send a form off to where a single hidden field is comprised of two of the other fields that will be dynamically populated by a user (post/zip code and first line of address) where after regular expression only the numbers remain "123|456".
I have attempted to start, using the code below, where I monitor the output in the console. I have managed to dynamically edit a textfield so that all that is shown are the numbers but this is not suitable for a user. So I was trying to store the edited textfield data into the hidden field whilst leaving the complete line of address but I could not see how this can be done.
Also, can someone explain why if I remove the commented line the variable is not stripped of any letters albeit just 1?
$(document).ready(function() {
$("#testMe").on('propertychange change click keyup input paste', function() //attaching multiple handlers
{
var removedText = $("#testMe").val().replace(/\D/, '');
$("#testMe").val(removedText); //only removes once if removed
console.log(removedText);
}
);
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<input type="hidden" id="hide" value="">
<input type="text" id="testMe" value="">
<span id="test2"></span>
The question was kind of unclear to me, but I did my best to answer.
https://jsfiddle.net/ccu6j6xu/
<input type="hidden" id="hide" value="">
<input type="text" id="zip" value="">
<input type="text" id="address" value="">
<span id="test2"></span>
In the HTML, all I did was add another input, because I think that's what you wanted to do?
$(document).ready(function() {
$("#zip, #address").on('propertychange change click keyup input paste', function() {
var concatText = $("#zip").val().replace(/\D/g, '') + "|" + $("#address").val().replace(/\D/g, '');
$("#test2").text(concatText);
$("#hide").val(concatText);
});
});
Then in the JavaScript, I changed the selector to match the new inputs, and then I changed the function.
The first line of this function defines a variable concatText to hold the values of each input concatenated with a | character between. Each one has regex applied to remove the letters for the final value. Then the next line changes the value of the span to display, and the final line applies this value to the hidden input.
Again, the question was kind of confusing to me, but feel free to comment and I can help some more :)
EDIT: reread the question, I think this better answers

How to put a string from an input field and put it into a function [duplicate]

This question already has answers here:
Get the value in an input text box
(13 answers)
Closed 8 years ago.
I am very new to programing so sorry if this question is to vague.
I have a simple html input field:
input class="draft" type="text"
and I have a javascript function (the function only accepts strings):
Message.send()
Using javascript/jQuery how do I take the string the user typed into the input field and place it into the Message.send() function (in string form)?
Thanks in advance for any help
jQuery:
Message.send($("input.draft").val());
javascript:
Message.send(document.querySelector("input.draft").value);
No jQuery needed. I'm not sure what you mean by place it into the Message.send() function (in string form), so I assume you get the value in the text input and use it as an argument in the Message.send() function.
Try this:
Message.send(document.getElementsByClassName("draft")[0].value);
Assuming your input field is something like this:
<input type="text" id="someInputField" name="someInputField" class="inputFields" />
You could do this
<script type="text/javascript">
//We use the field's id to refer to it and get to its value (the text in it):
var message = $('#someInputField').val();
//And then you might call the function like:
nameOfTheFuntion(message);
</script>
You would need to have jQuery libraries to make it work though, but you could do without them by replacing:
$('#someInputField').val();
with
document.getElementById('someInputField').val();
Give your <input> box an id for example
<input type="text" id="blah" />
In your javascript you are able to reference the <input> like so:
var strBlah = document.getElementById("blah").value;
Now you have the value typed into the <input> box so you would do the following:
Message.send(strBlah)

Form validation with Jquery or other without id name or class

I have no idea how to solve the Problem maybe some one can help.
I have a dynamic form that duplicate pices of the form depending on the user input.
So i cant use ids because the will be not uniq (Jquery Val. plugin).
I cant use classes because the are used for layout things ...
I cant use names because the are used to post in an array ...
So where to hook up the validation ?
Some one have tips for me ?
Thank you !!!
I am assuming that you have same validation type for each input group, and I am sure that you generate a new name for the new input right?
When you duplicate the input with name="field" .. make the duplicated name="field-2"
In jQuery use start with selector to validate these fields
$( "input[name^='field']" ) // This will match field and field-2
More Advanced Method:
If you need to access these dynamic fields. You will need to generate your own data-Anything
When you have an input such as
<input type="text" name="field" data-order="0" data-type="mytype" data-duplicated="FALSE">
The duplicated can be like this
<input type="text" name="field2" data-order="1" data-type="mytype" data-duplicated="TRUE">
Then access the second one like this in jQuery
$("input").each(function(index){
if($(this).data("type") == "mytype" && $(this).data("order") == 0){
// validate
}
});
To access all duplicated using order or duplicated field. you can use what you want.
$("input").each(function(index){
if($(this).data("type") == "mytype" && $(this).data("order") > 0){
// validate
}
});
So, basically you can define your data-attributes as the way you want dynamically, and access them by looping through the current inputs in the HTML page. When you find the input apply the validation function immediately.

Javascript to prevent invalid user input

I have written a set of javascript functions that allow me to validate user input on a form. I only want to accept valid input, and impose the following behaviour:
When a user enters an invalid form, I display an alert and inform them that the value entered is incorrect. Crucially, the original (valid) value in the form is not changed.
The value is only changed when the value has been validated.
For example, suppose I want to accept only positive integers in a field.
This is the sequence of events that describes the desired behaviour.
Scenario 1 (valid input)
Form loads with valid default in the input field
User types in valid number
Input field value is updated (as per normal form behaviour)
Scenario 2 (INvalid input)
Form loads with valid default in the input field
User types in INvalid number
Alert box is shown alert('Invalid value')
Input field value is NOT CHANGED (i.e. the value is the same as BEFORE the user typed in the invalid number)
[Edit]
The only problem I am facing at the moment (i.e. what this question is seeking an answer for), is Scenario 2, action point 4. More specifically put, the question degenerates to the following question:
How do I stop the value of a field from changing, if I (somehow) determine that the value being entered by the user is invalid. This is really, all I'm trying to answer.
I am also doing server side checks, this question is just about the front end - i.e. refusing to change a field (form text input) value if I determine that the value is incorrect.
BTW, I am using jQuery, and would like to implement this in a manner that separates behaviour from display (I think this is what is meant by the term 'unobtrusive' ?)
Any suggestions on how to implement this behaviour as described above, would be very much appreciated.
PS: I dont want to use yet another jQuery plugin for this. I should be able to use jQuery + the simple javascript validation functions I have already written.
When loading the page, couldn't you create a hidden form value or js variable in which you store the initial/default value for the field? When they change the form field, validate it, and if it passes, update the hidden field or js variable to match that in the field they updated.
When the input given by the user fails validation, show the invalid entry along with the error message and then update the form field back to the value you have saved which would be either the
default value or the last valid value that they entered.
EDIT:
Note that this is only a quick and (very) dirty example of doing what I explained in my answer above. If you have a lot of inputs, you will probably want to store the values in an associative array instead of in hidden form values, but this should give you a good handle on what I am suggesting. I would also strongly encourage you to NOT use alert boxes for notification of invalid answers.
<html>
<head>
<script type="text/javascript">
function validate()
{
var field1 = document.getElementById("field1");
var saved = document.getElementById("field1_save");
if (field1.value < 0 || field1.value > 10)
{
alert("Field1 value of " + field1.value + " is invalid");
// Change the value back to the previous valid answer
field1.value = saved.value;
return false;
}
// Save the valid input
saved.value = field1.value;
return true;
}
</script>
</head>
<body>
Test User Input
<form name="form1" id="form1" method="post">
<input name="field1" id="field1" type="text" value="2" onblur="validate();"/>
<input name="field1_save" id="field1_save" type="hidden" value="2" />
<input name="btnSubmit" type="submit" value="Submit" />
</form>
</body>
</html>

Categories