Using mapping in javascript - 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>

Related

jQuery data attribute updates only after second click

I have this jquery code which should print all selected checkboxes:
$('.engagement-type').on('click', function () {
var engagementTypes = $('.engagement-type').parent().find('[data-checkbox="checked"]');
console.log(engagementTypes);
});
12 checkboxes are in the table:
<td>
<input name="EngagementTypes[0].EngagementTypeId"
id="EngagementTypes_0__EngagementTypeId"
type="hidden" value="1" data-val-required="The Engagement field is required."
data-val="true" data-val-number="The field Engagement must be a number.">
<span class="pull-left">
<div class="engagement-type" data-checkbox="checked">
<input name="EngagementTypes[0].IsSelected"
id="EngagementTypes_0__IsSelected" type="checkbox" value="true"
data-val-required="The IsSelected field is required."
data-val="true">
<input name="EngagementTypes[0].IsSelected" type="hidden" value="false">
</div>
</span>
Audit
</td>
After first click on the checkbox I get empty list of selected engagement types. The first checkbox appears only after the second checkbox is checked. Why is that?
var engagementTypes = $('.engagement-type').parent().find('[data-checkbox="checked"]')
This will only work if you click on the div engagement-type. But if you click on one of the checkboxes in the div the parent is the one with the checkbox attribute, so he will not find another within this.
So you should always select
var elementYouWant = $('.engagement-type')
Then check if the data attribute is checked.
var dataElement = elementYouWant.data();
if (dataElement['checkbox'] == "checked") {
console.log("Oh yeah baby")
}
Ofcourse if there are multiple, you should do this in a loop for each of them.
As #T.J. Crowder mentioned, there must be additional code which you do not have provided.
At least the part which will set the data-checkbox = checked.
I would assume to use the checkbox state itself like:
$('.engagement-type').on('click', function () {
var engagementTypesChecked = $('.engagement-type').parent().find('input[type="checkbox"]:checked');
console.log(engagementTypesChecked);
});

Validating input field contained in table row

<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>

Append html string as a table row (<tr>) via javascript-jquery

I'm trying to append an HTML string to
var field = '<input type="text" name="featureName" class="form-control" id="featureName" placeholder="Feature Name" value="">'
var jfield = $(field);
$('#featureContainer').append(jfield);
When the button is clicked it will crete a input field, but if I click again it creates the input in the same row.
How can I make a new row with the input in it?
The following is my HTML code
<tr>
<td id="featureContainer"></td>
</tr>
If I click the button for the second time it creates it in the same row.
I want it to create it in new row.
As we don't know wether trs are wrapped inside table or tbody, .... We have to look for the closest tr and then get its parent then append a new row to that parent.
So, you should replace this:
$('#featureContainer').append(jfield);
with:
$('#featureContainer').closest('tr').parent().append('<tr><td>' + field + '</td></tr>');
NOTE: that inside field you have a static ID which will be on all the inputs you spawn which will be wrong since IDs are unique. So you may want to assign diferent IDs for diferent inputs.
You can just add the html code into field variable, like below:
var field = "<tr><td id="featureContainer"><input type="text" name="featureName" class="form-control" id="featureName" placeholder="Feature Name" value=""></td>
</tr>"
var jfield = $(field);
Assuming there is a button with id = 'add' and a table with id='data', then you can add this after above code:
$('#add').click(function(){
$('#data').append(jfield);
});
Your on the right track. But you don't need the jfield.
this appends the value of 'field' inside the td element:
$('#featureContainer').append(field);
but what you want is to append inside the table. So give your table a id (or the tbody) and do the following:
You need to embed the field inside a <tr><td> section and append that as a whole.
var field = var field = '<tr><td><input type="text" name="featureName" class="form-control" id="featureName" placeholder="Feature Name" value=""></td></tr>';
then in the click event:
$('#tableid').append(field);
Thr issue with your code is that you are trying to append to an element using id selector. Since in a valid html there should be only a single element with an unique id, you will be appending the new element always to the same td#featureContainer.
I will suggest you to change the id to class. To select the td.featureContainer where you need to append the new element, you can check inside the clicked button element event handler and find the td.featureContainer
$(".feature").on("click", function() {
var field = '<input type="text" name="featureName" class="form-control" id="featureName" placeholder="Feature Name" value="">'
var jfield = $(field);
$(this).parent().prev(".featureContainer").append(jfield);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<table>
<tr>
<td class="featureContainer"></td>
<td>
<input type="button" class="feature" value="click for row one">
</td>
</tr>
<tr>
<td class="featureContainer"></td>
<td>
<input type="button" class="feature" value="click for row two">
</td>
</tr>
</table>
First the id should be unique in the same document so better to use a common classes instead, then you could use append() to add new row (including tr/td), check the example below.
Hope this helps.
$('#add-row').on('click', function(){
var field = '<input type="text" name="featureName" class="form-control" placeholder="Feature Name" value="">'
$('table').append('<tr><td>'+field+'</td></tr>');
console.log($('table tr').length+' rows');
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<tr>
<td>Default row</td>
</tr>
</table>
<button id='add-row'>Add row</button>

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');
});
}
});
});
});

jquery get next input element value in <td>

I have some piece of an html table which reads like
<table>
<tr>
<td>
<input type="text" class="myclass" name="first_ele[]" value="100" />
</td>
<td>
<input type="text" class="anotherclass" name="secon_ele[]" value="" />
</td>
</tr>
</table>
I have a piece of jquery that will get the value of the element that contains class "myclass" on keyup and I am getting the proper value.
I need to get the value of the next input element.
FYI , The table gets rows added dynamically.
My issue is I don't know how to point to the next available input element.
my jquery to get the element which has the class "myclass" is as follows.
$('.tInputd').keyup(function(){
var disc = $(this).val();
});
your help is greatly appreciated.
Try
$('.myclass').on('keyup', function () {
var disc = $(this).closest('td').next().find('input').val();
});
or
$('.myclass').on('keyup', function () {
var disc = $('.anotherclass').val();
});

Categories

Resources