Using .each() method to validate form fields in jquery - javascript

I'm trying to build a function using the .each() method in jQuery that scans for empty input fields, highlights them in red, and then provides an alert message to let the user know what needs to change.
Here's my sample html:
<tr>
<td><input type="number" class="amount required" name="amount" ></td>
<td><input type="number" class="carrier required" name="carrier" ></td>
<td><input type="number" class="kilo required" name="kilo" ></td>
</tr>
<button type="submit" class="analyze">Analyze</button>
Here's the function to loop through the table data and add the CSS:
$(".analyze").click(function() {
$(".required").each(function() {
if ($(this).val() === "") {
$(this).parents("td").addClass("redClass");
alert("Looks like some of the fields aren't filled out correctly. They're highlighted in red.");
}
});
});
The issue is that the code goes through the array one-by-one and creates an alert message for every single empty cell. Ideally it'd add .redClass to the empty fields all at once and just present one alert message at the end if any are empty.

Per my comment:
$(".analyze").click(function() {
var counter = 0;
$(".required").each(function() {
if ($(this).val() === "") {
$(this).parents("td").addClass("redClass");
counter++;
}
});
if(counter > 0){
alert("Looks like some of the fields aren't filled out correctly. They're highlighted in red.");
}
});

Try this:
$(".analyze").click(function () {
var req = $(".required");
req.each(function (i) {
if ($(this).val() === "") {
$(this).parent("td").addClass("redClass");
req.error = true;
}
});
if (req.error) {
alert("Looks like some of the fields aren't filled out correctly. They're highlighted in red."); }
});
.redClass {
background: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<tr>
<td>
<input type="number" class="amount required" name="amount">
</td>
<td>
<input type="number" class="carrier required" name="carrier">
</td>
<td>
<input type="number" class="kilo required" name="kilo">
</td>
</tr>
</table>
<button type="submit" class="analyze">Analyze</button>

Here's a fiddle http://jsfiddle.net/cga65pLh/1/
$(".analyze").click(function() {
//on click of element with class "analyze"
$(".required").removeClass("redClass"); //remove redClass from all elements
//remove redClass from all elements with class required
x=true;
//turn x to true so that we know a pop up hasn't occurred yet
$(".required").each(function() {
// loop through each element with the class required
if ($(this).val() === "") {
// if the value is empty
$(this).addClass("redClass");
//add redClass to the element, turning the background of the element red.
(x) ?
//check if x is true (this is a ternary statement)
// if x is true do the following:
(alert("Looks like some of the fields aren't filled out correctly. They're highlighted in red."),
x=false)
:
// if x is false simply return false and don't do anything
false;
}
});
});
What this does is, on click, it removes redClass from any element with class "required" this is so that it starts fresh each time the button is pressed. It then turns the value x to true. This way we can keep track of if there's an alert message or not. a.e if it's true there's been no alert.
For each element with class "required" we check if value is "". If it is, we apply the class "redClass" which turns the current box red and we check if x is true. If x is true we display an alert and turn x to false so that no other pop ups occur.

Related

Input text validation using jQuery

I have a situation where i want to validate the text entered into a input text field. This is the HTML code:
<div id="err_title" style="display:none;">Please enter a valid Number.</div>
<input type="radio" id="txt_a-radio" value="valueA" checked="checked">
<input type="text" id="txt_a">
<input type="radio" id="txt_b-radio" value="valueB">
<input type="text" id="txt_b" disabled>
By default #txt_b field will be disabled, when user clicks on #txt_b-radio button #txt_b will be enabled and #txt_a will be disabled.
The condition for validation is:
#txt_a can contain only 12 digit number
#txt_b can contain only 20 digit number
Validation should happen once user enters value in enabled field then clicks anywhere outside. If value entered by user is not valid error message #err_title should display.
Suppose if user enters value for #txt_a and then clicks on #txt_b-radio button then validation shouldn't happen since user has switched the input field.In this case #txt_a should be disabled and txt_b enabled.
I have tried with the following code:
$('#txt_a').change(function() {
custNumber = $('#txt_a').val(); expression = /^[0-9]{12}$/;
if(custNumber === '') {
$("#err_title").css('display', 'none');
} else if ((!custNumber.match(regexp))) {
$("#err_title").css('display', 'block');
} else {
$("#err_title").css('display', 'none');
}
});
$input1 = $('input[name="input1"]');
$input2 = $('input[name="input2"]');
$checkbox = $('input[name="checkbox"]');
$input1.on('change', function(e) {
var isValid = this.value.length >= 12;
this.classList.toggle('notValid', !isValid);
})
$checkbox.on('change', function(e) {
$input2.prop('disabled', !this.checked);
})
input.notValid {
border: 1px solid red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" name="input1" />
<input type="text" name="input2" disabled />
<input type="checkbox" name="checkbox" />
NOTE:
In example above, I'm mixing vanillia JS, with jQuery. I would recommend avoiding it - I did that to show You how easy (well not always...) it is to do such a simple thing without jQuery.
Basically, if You want to do simple stuff like that, I would recommend to give up on jQuery.
ANSWER:
You are looking for jQuery change event. It triggers once input loose focus.
$(your_input).on('change', function(e) {...} )
You can validate input length like (function inside listener) :
var isValid = this.value.length === 12
Same goes with disabled/enabled input.
You have to attach event listener to checkbox
$(your_checkbox).on('change', function(e) {...} )
then You can get state of checkbox :
var isChecked = this.checked
and disable/enable Your input
$(your_input).attr('disabled', !isChecked)

Get elements from Parent Row of checked checkboxes

I have the following row in a table.
<tr class="data_rows" ng-repeat='d in t2'>
<td class="tds"> <input class='checkBoxInput' type='checkbox' onchange='keepCount(this)'></td>
<td class="tds"><a href='perf?id={{d.ID}}'>{{d.ID}}</a></td>
<td class="tds">{{d.HostOS}}</td>
<td class="tds">{{d.BuildID}}</td>
<td class="tds">{{d.Description}}</td>
<td class="tds">{{d.User}}</td>
<td class="tds">{{d.StartTime}}</td>
<td class="tds">{{d.UniqueMeasure}}</td>
<td class="tds">{{d.TotalMeasure}}</td>
</tr>
Here's the HTML for button that will invoke the function to collect the ids from checked check boxes and store them.
<div id='compButtonDiv' align='center' style="display: none;">
<input id='cButton' type='button' value='compare selections' onclick='submitSelection()' style= "margin :0 auto" disabled>
</div>
The data is in t2 which consists of an array of length 15-20.
What i want to do is get the value of ID i.e, {{d.ID}} of the 2 checked check boxes so that i can store them in a variable and pass them as query parameters to URL using `location.href = url?param1&param2'
Here's the javascript:
function keepCount(obj){
debugger;
//var count=0;
if(obj.checked){
obj.classList.add("checked");
}else{
obj.classList.remove("checked");
}
var count = document.getElementsByClassName("checked").length;
var cBtn = document.getElementById('cButton');
//alert(count);
if(count == 2){
cBtn.disabled = false;
}
else if(count < 2){
cBtn.disabled= true;
}
else{
cBtn.disabled= true;
alert("Please Select two sets for comparison. You have selected: " + count);
}
}
function submitSelection(){
// what should be the code here??
location.href= "existingURL?a&b";
}
Now can someone please tell me how to get the id's?? I need to extract ID from the checkboxes that are checked(on the click of button whose code i've mentioned above'.
Thanks.
-Ely
Firstly when we use angularjs we tend to depend less and less on DOM manipulation.
For this reason, what you can do is to attach ngModel to the checkbox.
Like:
<input class='checkBoxInput' ng-model='d.isChecked' type='checkbox' onchange='keepCount(this)'>
What this does is, it attaches the variable (in your case the property of item in the list) to the check box. If it is checked it is true, if unchecked, initially it will be undefined, later on checking and then unchecking it will be false.
Now, when you submit, just loop over the original list in the function and check the values of d.isChecked (true/falsy values). Then you can add the necessary items in a separate list for submission.
The only concern is when checking the list on submission , check if(d.isChecked), so that it ignores the falsy values(false/undefined).

check if all input field has value jQuery condition

i have several input fields with a class name of required.
i have a code below to check if all my <input> fields have a value, if not empty or null, it will show/unhide a specific div.
but it doest seem to work on me.
also, by default, #print is displayed as none via CSS.
<!-- index.php -->
<input type="text" id="getID" class="required form-control" placeholder="id">
<input type="text" id="getName" class="required form-control" placeholder="name">
<!-- script.js -->
$(document).ready(function() {
$('input.required').each(function() {
if($(this).val() != "") {
$("#print").show();
}
else {
$("#print").hide();
}
});
});
I'd suggest:
$('#print').toggle(!($('input.required').length == $('input.required').filter(function () {
return this.value;
}).length));
Simplified JS Fiddle demo.
Obviously this should be run on submit, assuming you want to only show the #print element as a validation prior to submission.
References:
filter().
toggle().
As I stated in my comment above, you're checking the values when the page loads, before the user has any chance to enter anything. If you have a button on your page, bind the event to that which will fire the function at the right time.
Something a little like this jFiddle
index.php
<input type="text" id="getID" class="required form-control" placeholder="id">
<input type="text" id="getName" class="required form-control" placeholder="name">
<div id="button">Submit</div>
<div id="print">You're missing something D:!</div>
script.js
$('#button').on('click', function() {
$('#print').hide();
var error=false;
$('input.required').each(function() {
if($(this).val() == "") {
error=true;
}
});
if(error) {
$('#print').show();
}
});
Try
$(document).ready(function () {
//the default state
var valid = true;
$('input.required').each(function () {
//if the value of the current input is blank then the set is invalid and we can stop the iteration now
if ($.trim(this.value) == '') {
valid = false;
return false;
}
});
//set the visibility of the element based on the value of valid state
$("#print").toggle(!valid);
});

Why this javascript not enabling text boxes using check box?

Again in problem
Actually I have following jsp code in which I have few text boxes which I have made disabled by using property disabled="disabled".
Now problem is each record that I will get from database in each text box using iterator which iterates values added from databse in arraylist.If database return more than one record then using that check box I can enable textboxes but if databse resultset return only one record then I am unable to enable textboxes and throws following ERROR:
Message: 'document.f1.chk' is null or not an object
Line: 26
Char: 10
Code: 0
<script type="text/javascript">
function enable()
{
for(i=0;i<document.preapp.chk.length;i++)
{
if(document.preapp.chk[i].checked==true)
{
document.preapp.id[i].disabled=false;
document.preapp.vname[i].disabled=false;
document.preapp.comp[i].disabled=false;
document.preapp.cont[i].disabled=false;
document.preapp.wtm[i].disabled=false;
document.preapp.intime[i].disabled=false;
}
else
if(document.preapp.chk[i].checked==false)
{
document.preapp.id[i].disabled=true;
document.preapp.vname[i].disabled=true;
document.preapp.comp[i].disabled=true;
document.preapp.cont[i].disabled=true;
document.preapp.wtm[i].disabled=true;
document.preapp.intime[i].disabled=true;
}
}
}
</script>
<CENTER>Back to Search</CENTER>
<form method="post" action="" name="preapp">
<table border="1" align="center" width="100%">
<%
Iterator itr;
try
{
ArrayList al=(ArrayList)request.getAttribute("sq");
int i=0;
for(itr=al.iterator();itr.hasNext();)
{
i=i+1;
%>
<tr>
<td></td><td><input type="checkbox" name="chk" onclick="enable(this)" ></td></tr></tr>
<tr><td>Id</td><td><input type="text" name="id" value="<%=itr.next()%>" disabled="disabled" size="100%"></td></tr>
<tr><td>Visitor Name</td><td><input type="text" name="vname" value="<%=itr.next()%>" disabled="disabled" size="100%"></td></tr>
<tr><td>Comapny</td><td><input type="text" name="comp" value="<%=itr.next()%>" disabled="disabled" size="100%"></td></tr>
<tr><td>Contact</td><td><input type="text" name="cont" value="<%=itr.next()%>" disabled="disabled" size="100%"></td></tr>
<tr><td>Meeting Scheduled With</td><td><input type="text" name="wtm" value="<%=itr.next()%>" disabled="disabled" size="100%"></td></tr>
<tr><td>Entry Made On</td><td><input type="text" name="intime" value="<%=itr.next()%>" disabled="disabled" size="100%"></td></tr>
<tr><td></td>
</tr>
<tr>
</tr>
<%
}
}
catch(Exception e)
{
e.printStackTrace();
System.out.println(e.getMessage());
}
%>
How Do solve this problem? please help me out!
It works like charm, except in the case you have only one TR block.
In that case, the .chk has no "length" attribute!
You should consider that case separately:
function enable()
{
if(document.preapp.chk.length == null)
{
disabledState = !document.preapp.chk.checked
document.preapp.id.disabled=disabledState;
document.preapp.vname.disabled=disabledState;
document.preapp.comp.disabled=disabledState;
document.preapp.cont.disabled=disabledState;
document.preapp.wtm.disabled=disabledState;
document.preapp.intime.disabled=disabledState;
} else {
for(i=0;i<document.preapp.chk.length;i++)
{
disabledState = !document.preapp.chk[i].checked
document.preapp.id[i].disabled=disabledState;
document.preapp.vname[i].disabled=disabledState;
document.preapp.comp[i].disabled=disabledState;
document.preapp.cont[i].disabled=disabledState;
document.preapp.wtm[i].disabled=disabledState;
document.preapp.intime[i].disabled=disabledState;
}
}
}
a couple of suggesions: instead of setting the properties of elements to true or false, try using the setAttribute and removeAttribute methods:
document.preapp.id[i].disabled=true;
//replace with:
document.preapp.id[i].setAttribute('disabled','disabled');
//to enable:
document.preapp.id[i].removeAttribute('disabled');
The way you're doing things works fine 99.9% of the time. I haven't seen the above code fail, though (I have had issues with the true/false approach).
Next: the error message you post, contains very useful information: check line 26 of your original code. 'document.f1.chk' is nowhere to be found in your snippet, so I can't check for typo's or other possible problems in your code there.
You're passing the element to the enable function, too. Why then, are you looping through all elements, checking all elems on the page?
function enable(elem)
{
var i = document.preapp.indexOf(elem);//
if (elem.checked === true)
{
document.preapp.id[i].removeAttribute('disabled');
//...
}
//functions have properties, exploit them:
if (typeof enable.previous === 'undefined' || enable.previous === i)
{
enable.previous = i;
return true;
}
document.preapp.id[enable.previous].setAttribute('disabled','disabled');
//...
enable.previous = i;
}
The last section of the enable function stores the index of the checkbox that was just clicked, so that when the enable function has been clicked before, there's no need to loop through all elements again: enable.previous holds the index of the checkbox that was clicked last time.
Lastly: there are no opening or closing bracket for the else block, and there is an extra line of whitespace. Else works fine without brackets, but only branches one line. In your code, this line is blank: either remove the else, or add brackets.
PS: Perhaps a fiddle would help to get a clear view of the situation?
As Teejay pointed out, in case of unique names, the elements are referenced directly, instead of a nodesList being passed.

How to check a checkbox onkeypress?

I have the following code to check a checkbox as soon as the user types something in the textbox. This works fine for a single text box.
function activateCheckbox() {
if (document.myForm.box1.checked == false) {
document.myForm.box1.checked = true;
}
}
<tr>
<td><input type="text" id="mySearch1" name="mySearch1" size="40" onkeypress="activateCheckbox()"/></td>
<td><input type="checkBox" id="box1" name="box1"/></td>
</tr>
However suppose there are more than one text boxes with a checkbox against each one and I want that only the corresponding checkbox should be checked. I modified the above code as shown below by passing a parameter to the function but it's not working, because "document.myForm.id.checked" doesn't work as it accepts the checkbox name instead of "id". Please suggest if there are better alternatives or how do I modify my code to make it working?
function activateCheckbox(id) {
if (document.myForm.id.checked == false) {
document.myForm.id.checked = true;
}
}
<tr>
<td><input type="text" id="mySearch1" name="mySearch1" size="40" onkeypress="activateCheckbox('box1')"/></td>
<td><input type="checkBox" id="box1" name="box1"/></td>
</tr>
<tr>
<td><input type="text" id="mySearch2" name="mySearch2" size="40" onkeypress="activateCheckbox('box2')"/></td>
<td><input type="checkBox" id="box2" name="box2"/></td>
</tr>
<tr>
<td><input type="text" id="mySearch3" name="mySearch3" size="40" onkeypress="activateCheckbox('box3')"/></td>
<td><input type="checkBox" id="box3" name="box3"/></td>
</tr>
You have a couple of options. You can do:
function activateCheckbox(id) {
if (document.myForm[id].checked == false) {
document.myForm[id].checked = true;
}
}
...or personally, I think this is a bit more clear:
function activateCheckbox(id) {
var checkbox = document.getElementById(id);
if (! checkbox.checked) {
checkbox.checked = true;
}
}
The first approach works because in JavaScript obj.someProperty means the same semantically as obj["someProperty"]. So if you have a variable that stores the name of the property you want to access, you can always do obj[name] to access the property.
The second approach is just finding the checkbox in the DOM by its id. It seems cleaner to me, since you are setting the id of each checkbox anyways and since you called your variable "id".
Also note that your if statement is superfluous. The checked attribute will only ever be true or false (you can subvert this by storing other things there, but that's a completely separate topic). So setting it to true whenever it is false is logically equivalent to always setting it to true, and you can implement your handler function with a single line, like:
function activateCheckbox(id) {
document.getElementById(id).checked = true;
}
.id means literally the id property. In case you want to have it set dynamically, use the [] notation:
function activateCheckbox(id) {
if (document.myForm[id].checked == false) {
document.myForm[id].checked = true;
}
}
['test'] means .test, ['abc'] means .abc. So [id] means: access the property that id has as its value.
I advise you to use a JQuery (www.jquery.com). By adding one code line
<script src="http://code.jquery.com/jquery-1.6.2.min.js" type="text/javascript"></script>
you can solve your problem problem by write just one code line:
$('#checkboxId').attr('checked','checked');
or you can check
$('input[type="checkbox"]').attr('checked','checked');
or unckeck
$('input[type="checkbox"]').attr('checked','');
all checkboxes in you document

Categories