Validating input field contained in table row - javascript

<tr>
<td>.....</td>
<td>
<div class="...">
<div class="..." id="..." style="display:block;">
<ul id="..." class="..." style="position:relative;">
<%
for(int i = 0;i < len;i++)
{
//get a json object
if(jsonobj != null)
{
//Get style...id..and some other values....
%>
<li class="..." style="display:block;" id="...">
<div style="<%=style%>">
<input type="checkbox" id="<%=Id%>" class="..." value="true" <%if(enabled){%> checked="checked" <%}%> onClick="..."/>
<input id="inp_<%=Id%>" type="text" class="..." style="border:none;padding-left:5px;" value="<%=text%>" title="<%=title%>">
</div>
</li>
<% }
}
%>
</ul>
</div>
</div>
</td>
</tr>
I have a table row like the above code. As you can see, there are two inputs, a checkbox and a text field. While submiting the form I want to validate the text field and show an error message with a small error icon at the right side. But since the input is in a table row I'm unable to to this.
I have a function which shows a tool tip. I just have to pass the id of the element and the message to that function. I want to validate the input field, show a small error image and call the tool tip function so that the tool tip is shown on the error image.
I want the error image to appear next to the required input field i.e., if the 3rd input field is vaidated to false, then the error should be displayed next to the 3rd containing the input field.
How do I do it?

It's a simple task for jQuery. See the example below:
$(document).ready(function(){
$("#btnSave").click(function(){
$(".txtvalidatorMessage").remove() // remove all messages
var inputs = $(".txtvalidator");
function ShowMessage(message, input){
var messageContainer = $("<div class='txtvalidatorMessage'>"+message+"</div>");
messageContainer.insertAfter(input)// show the message beside the input
}
inputs.each(function(){
var validationType = $(this).attr("validationType");
var require = eval($(this).attr("require"));
switch(validationType)
{
case "NotEmpty":
if ($(this).val() == "" && require == true)
ShowMessage("cant be empty",$(this))
break;
case "Number":
var isnum = /^\d+$/.test($(this).val());
if (!isnum && require == true)
ShowMessage("only number",$(this))
break;
}
});
});
});
.txtvalidatorMessage{
color:red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<tr>
<td>
<input type='text' value="" placeholder='Cant be empty' class='txtvalidator' validationType='NotEmpty' require='true' />
</td>
</tr>
<tr>
<td>
<input type='text' value="" placeholder='only Number' class='txtvalidator' validationType='Number' require='true' />
</td>
<tr>
<td>
<input type='button' value="Validate" id='btnSave' />
</td>
</tr>
</table>

Related

JavaScript - Getting Value of Div Content - Content Getting Replaced by Wrong String

Link to jsFiddle.
If the textarea is blank, the content should say "you have to tell me a joke!" with Javascript.
Instead, even when the textarea is blank, the content is still getting changed to "was your joke funny?"
Relavant code:
HTML
<div class="row"><!--third row -->
<div class="col-2 joker">
<img src="/joker.png"/>
<p id="jokerDialogue">Tell me a joke</p>
</div>
<div class="col-2">
<table>
<tr>
<td>Joke:</td>
</tr>
<tr>
<td>
<textarea id="jokeQuestion" type="string" min="1" max="24" size="24">
</textarea>
</td>
</tr>
<tr>
<td>
<input id="submit-joke" type="button" value="submit" class="js-button"
onclick="joker()">
</td>
</tr>
</table>
</form>
</div>
<div class="col-8">
</div>
</div>
Javascript
function joker() {
let content = document.getElementById("jokeQuestion");
if (content != "") {
document.getElementById("jokerDialogue").innerHTML = "Was your joke funny?";
}
else if (content == "") {
document.getElementById("jokerDialogue").innerHTML = "You must tell me a joke!";
}
}
As you can see, I'm trying to create a variable content and say that it's whatever the user enters in the textarea with the id jokeQuestion.
But even when content is blank, the <p> with the id "jokerDialogue" is still getting changed to "Was your joke funny?"
I thought that if (content != "") meant "if the content is not blank" - so then why is the function returning "Was your joke funny?" even when it's blank?
You need to get the value of content:
let content = document.getElementById("jokeQuestion").value;
Now your code will work as expected.

Iterate through inputs in ASP.Net table

I have a table I create programmatically through ASP.Net code which, in each row, has a checkbox and a textfield.
What I can't seem to achieve (via jQuery at least) is to iterate all the rows to check if all rows which checkbox has been checked have text in the textfield. Confusing? Let me simplify...
I have a table. That table has 3 rows. Each row has a checkbox, some plain text and a textfield. I need to check, in jQuery, if all rows whose checkboxes have been checked by the user also have text in the respective textfields.
I tried to create a simple example based off some answers in here but this doesn't seem to be working; it displays the modal regardless of whether there is text on the input or not.
$('#myButton').on('click', function() {
checkInputs();
});
function checkInputs() {
var hasEmpty = 0;
$('#myTable tr').each(function(i, row) {
var row = $(row);
var checkbox = row.find('input[type*="checkbox"]');
var textbox = row.find('input[type*="text"]');
if (checkbox.is(':checked')) {
if (textbox.val() == "") {
hasEmpty = 1;
};
}
});
if (hasEmpty = 1) {
$(function() {
$("#dialog").dialog();
});
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://code.jquery.com/ui/1.12.0/jquery-ui.min.js"></script>
<link rel="stylesheet" href="https://code.jquery.com/ui/1.12.0/themes/smoothness/jquery-ui.css" />
<table id="myTable">
<tr>
<td>
<input type="checkbox" />
</td>
<td>
<input type="text" />
</td>
</tr>
<tr>
<td>
<input type="checkbox" />
</td>
<td>
<input type="text" />
</td>
</tr>
</table>
<button id="myButton">Button</button>
<div id="dialog" title="Basic dialog" style="display:none;">
<p>This is the default dialog which is useful for displaying information. The dialog window can be moved, resized and closed with the 'x' icon.</p>
</div>
The "dialog" part is a jQueryUI modal which I want to display when there's checkboxes that have been checked but the respective inputs don't have a value. I copy-pasted the jQueryUI example code here for the sake of simplification.
Reminder that the actual table is an ASP.Net table which is created programmatically.
Your main issue is that you're using = in the if statement, which sets a value, instead of == or === to compare values. You also don't need the additional document.ready handler around the dialog call.
With that said you can improve the logic slightly by ending the loop as soon as an invalid row is found, like this:
$('#myButton').on('click', function() {
if (!validateInputs())
$("#dialog").dialog();
});
function validateInputs() {
var valid = true;
$('#myTable tr').each(function() {
var $row = $(this);
var $checkbox = $row.find(':checkbox');
var $textbox = $row.find(':text');
if ($checkbox.is(':checked') && $textbox.val().trim() === "") {
valid = false;
return false; // break loop
}
});
return valid;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://code.jquery.com/ui/1.12.0/jquery-ui.min.js"></script>
<link rel="stylesheet" href="https://code.jquery.com/ui/1.12.0/themes/smoothness/jquery-ui.css" />
<table id="myTable">
<tr>
<td>
<input type="checkbox" />
</td>
<td>
<input type="text" />
</td>
</tr>
<tr>
<td>
<input type="checkbox" />
</td>
<td>
<input type="text" />
</td>
</tr>
</table>
<button id="myButton">Button</button>
<div id="dialog" title="Invalid" style="display: none;">
<p>Not all checked boxes had text entries</p>
</div>
Your if (hasEmpty = 1) has single =. Update it as below.
if (hasEmpty == 1)
Complete code is as below.
$('#myButton').on('click', function() {
checkInputs();
});
function checkInputs() {
var hasEmpty = 0;
$('#myTable tr').each(function(i, row) {
var row = $(row);
var checkbox = row.find('input[type*="checkbox"]');
var textbox = row.find('input[type*="text"]');
if (checkbox.is(':checked')) {
if (textbox.val() == "") {
hasEmpty = 1;
};
}
});
if (hasEmpty == 1) {
$(function() {
$("#dialog").dialog();
});
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://code.jquery.com/ui/1.12.0/jquery-ui.min.js"></script>
<link rel="stylesheet" href="https://code.jquery.com/ui/1.12.0/themes/smoothness/jquery-ui.css" />
<table id="myTable">
<tr>
<td>
<input type="checkbox" />
</td>
<td>
<input type="text" />
</td>
</tr>
<tr>
<td>
<input type="checkbox" />
</td>
<td>
<input type="text" />
</td>
</tr>
</table>
<button id="myButton">Button</button>
<div id="dialog" title="Basic dialog" style="display:none;">
<p>This is the default dialog which is useful for displaying information. The dialog window can be moved, resized and closed with the 'x' icon.</p>
</div>

Checking that at least one textarea is filled

I need help with adding a controll that checks that atleast one on the textareas is filled so that people wouldnt save blank forms. so it should controll that at least on element is checked and filled, otherwise it should give an error and wouldnt save. If anyone would have an idea how to do so, I would greatly appreciate it. The code that Im working with is down below (actually have more textareas but they are the same only with another names).
<tr>
<td valign="top" style='width: 300px;'>Family members help</td>
<%
elemText = xml.getElementFromXPath("//nursing_care/family_help/tekst");
%>
<td valign="top"><input <%=(elemText==null?"checked=\"checked\"":"") %> value="0" onclick="javascript:showText(this);" name="//nursing_care/family_help" type="radio" checked="checked">Valimata
<input <%=(elemText!=null?"checked=\"checked\"":"") %> value="1" onclick="javascript:showText(this);" name="//nursing_care/family_help" type="radio">Määratud</td>
<td>
<textarea style='width: 350px' style="display:<%=(elemText==null?"none":"block") %>" id="//nursing_care/family_help/tekst" name="//nursing_care/family_help/tekst"><%=(elemText!=null?elemText.getText():"") %></textarea>
</td>
<td><input style="display:<%=(elemText==null?"none":"block") %>" type="text" class="txt_left" id="//nursing_care/family_help/date" name="//nursing_care/family_help/date" value="<%=xml.getText("//nursing_care/family_help/date")%>" maxlength="10" size="10"
onchange="gnlDateValid(this,event); if(event.returnValue != false);" onfocus="gnlGotFocus(getCurrentDate(),this); inputChanged(this);" onkeydown="gnlKeyDown('00.00.0000',this,event);" /></td>
</tr>
</tbody>
<tfoot>
<tr>
<td colspan="3"><input type="submit" class="button_save button" value="Salvesta" />
<input type="button" class="button" value="Sulge" onclick="window.close()" /></td>
</tr>
</tfoot>
And here is the function that shows/hides the textareas (just in case)
function showText(obj){
var elements = document.getElementsByName(obj.name);
var element = getNode(obj.name + "/tekst");
if (elements[0].checked)
element.style.display="none";
else
element.style.display="block";
var element = getNode(obj.name + "/date");
if (elements[0].checked)
element.style.display="none";
else
element.style.display="block";
}
Something like this should work.
Extend the submit button like this.
<input type="submit" class="button_save button" value="Salvesta" onclick="return submitCheck()"/>
and implement this function in your javascript file.
function submitCheck(){
var form = document.forms[0];
var textareas = form.getElementsByTagName("textarea");
for(var textarea in textareas){
if(textarea.value !== ""){
return true;
}
}
return false;
}
BTW i would recommend you to use jQuery when working with the HTML DOM ;-)

Row Validation with Jquery Validation plugin

I have a series of forms that correspond to likert questions:
<form class="indicator-form" request="post">
<fieldset>
<label class="top-label">
Enter the number of <strong>category 1</strong> staff that answered each level of importance on a 5-point likert-field scale for the question:<br/>
<em>Question 1?</em>
</label>
<table>
<tr class="likert">
<td>
<label for="cat1_a">Very Unimportant</label>
<input id="cat1_a" name="cat1_a" class="likert-field" type="text" />
</td>
<td>
<label for="cat1_b">Unimportant</label>
<input id="cat1_b" name="cat1_b" class="likert-field" type="text" />
</td>
<td>
<label for="cat1_c">Neutral</label>
<input id="cat1_c" name="cat1_c" class="likert-field" type="text" />
</td>
<td>
<label for="cat1_d">Important</label>
<input id="cat1_d" name="cat1_d" class="likert-field" type="text" />
</td>
<td>
<label for="cat1_e">Very Important</label>
<input id="cat1_e" name="cat1_e" class="likert-field" type="text" />
</td>
</tr>
</table>
</fieldset>
<fieldset>
<label class="top-label">
Enter the number of <strong>category 2</strong> staff that answered each level of importance on a 5-point likert-field scale for the question:<br/>
<em>Question 2?</em>
</label>
<table>
<tr class="likert">
<td>
<label for="cat2_a">Very Unimportant</label>
<input id="cat2_a" name="cat2_a" class="likert-field" type="text" />
</td>
<td>
<label for="cat2_b">Unimportant</label>
<input id="cat2_b" name="cat2_b" class="likert-field" type="text" />
</td>
<td>
<label for="cat2_c">Neutral</label>
<input id="cat2_c" name="cat2_c" class="likert-field" type="text" />
</td>
<td>
<label for="cat2_d">Important</label>
<input id="cat2_d" name="cat2_d" class="likert-field" type="text" />
</td>
<td>
<label for="cat2_e">Very Important</label>
<input id="cat2_e" name="cat2_e" class="likert-field" type="text" />
</td>
</tr>
</table>
</fieldset>
<input type="submit" value="Submit Data"/>
</form>
I want to validate each table row so that:
If there is no data in the row, no validation is applied (i.e. a user
can submit an empty row)
If there is any data in the row, all fields must be filled out.
My JS:
// Likert Row Validation
jQuery.validator.addMethod('likert', function(value, element) {
var $inputs = $(element).closest('tr.likert').find('.likert-field:filled');
if (0 < $inputs.length && $inputs.length < 5 && !($(element).val())){
return false;
} else {
return true;
}
}, 'Partially completed rows are not allowed');
// Likert Fields
jQuery.validator.addClassRules('likert-field', {
likert: true
});
var validator = $('.indicator-form').validate({
errorPlacement: function(error, element){
errorPos = element;
errorClass = 'alert-arrow-center';
error.insertAfter(errorPos).addClass(errorClass);
}
});
On the face of it, this validation works - but if you start playing around with it, it becomes clear that the rule is only applied to the fields that are blank when the submit button is clicked.
How can I make it so that the validation rule applies to all fields unless there is no data at all?
JSfiddle here: http://jsfiddle.net/6RtcJ/1/
It's behaving strangely because validation is only triggered for one field at a time (unless you click the submit). If you blank out data in one field, then only the one field is re-evaluated. This is why you have messages lingering around on other fields.
It's not ideal, but you can force the whole form to re-validate on every keyup and blur event using the valid() method like this...
$('input').on('blur keyup', function() {
$('.indicator-form').valid();
});
Your demo: http://jsfiddle.net/6RtcJ/20/
Same idea, but only triggered by blur event...
http://jsfiddle.net/6RtcJ/21/
Quote OP:
"... it becomes clear that the rule is only applied to the fields that are blank when the submit button is clicked."
If you're expecting validation messages to appear on a field even after the same field passes validation, then that's not how this plugin works.
There are ways to group messages together using the groups option, which may help you a bit. You can also use the errorPlacement callback to position the one message for the whole row.
The way the groups option works is that it will group all error messages for several fields into one message... so only after all fields in the group pass validation, the single message will go away.
I've set the onkeyup option to false in this example since all fields now share the same message.
groups option demo: http://jsfiddle.net/6RtcJ/22/
ok , i got your meaning.
there are some solution here.
1.remove the rules on this form when all input not insert any word.
2.add the rules ,if one of the input had data.
you should do a check before validation?
Try this:
$(document).ready(function(){
$('.indicator-form').validate({
onfocusout:false,
submitHandler: function (form) {
alert('Form Submited');
return false;
}
});
// Likert Fields
/*
$('.likert-field').each(function(){
$(this).rules('add',{
required: true,
messages: {
required: "Partially completed rows are not allowed",
},
});
});
*/
$("input[type='submit']").click(function(){
$("tr.likert").each(function(){
var $inputs = $(this).find('.likert-field:filled');
if (0 < $inputs.length && $inputs.length < 5) {
$(this).children('td').children('.likert-field').each(function() {
$(this).rules('add',{
required: true,
});
});
} else {
$(this).children('td').children('.likert-field').each(function() {
$(this).rules('remove');
});
}
});
});
});

Using mapping in javascript

I want a javascript function for mapping checkbox id with the value of someother field in grails
i have a gsp page with checkbox and cost field as follows
<td>
<g:checkBox type="checkbox" class="select_all" name="counTestUnit" id="${testUnitInstance.id}" />
</td>
<td>
<g:textField name="cost" maxlength="20" required="" id="${testUnitInstance.id}" />
</td>
i want a javascript function with mapping between checked checkbox id with cost field
you need a on change function for the check box and add intital for the id to diffrentiate it the cost text field,since intital follows ID later on you extract that ID and find the corresponding cost field.
"c_${testUnitInstance.id}"
example
<g:checkBox type="checkbox" class="select_all" name="counTestUnit" id="c_${testUnitInstance.id}" onChange="FindCost('c_${testUnitInstance.id}')"/>
<g:javascript>
function FindCost(chckboxname){
console.log("check Status:"+$("#"+chckboxname).prop("checked"));
var arrayOfchckBoxId = chckboxname.split("_"); //parse the two parts of the name after _
var commnidforcheckandcost = arrayOfchckBoxId[1];
var initialname = arrayOfchckBoxId[0];
var currentCheckbox = "#"+chckboxname ;
console.log("ID:"+arrayOfchckBoxId[1]);
console.log("Name:"+currentCheckbox);
if(initialname == 'c'){
//display the corresponsing cost text field.
$("#"+commnidforcheckandcost").show() //display the cost with a give id like checkbox
}
</g:javascript>
i guess this should resolve your problem for more help see ,the javascript console debug.
You can do as below
<td>
<g:checkBox type="checkbox" class="select_all" name="counTestUnit" id="checkbox${testUnitInstance.id}" onclick="mapCheckAndField(${testUnitInstance.id})"/>
</td>
<td>
<g:textField name="cost" maxlength="20" required="" id="textField${testUnitInstance.id}" />
</td>
<script>
function mapCheckAndField(testUnitId)
{
//we know that now checkboxId is "checkbox"+testUnitId
//and corresponding textField id is "textField"+testUnitId
//Simply you will get the value of checkbox corresponding textField value as below
$("#textField"+testUnitId).val()
}
</script>

Categories

Resources