Add row, date picker script is not working after adding other functionality screen - ajax

Add row script is not working after adding other functionality screen.
I am trying to do dynamically adding table tows when user clicks "addrow" button. It works when i do it separately. But when i add along with my main jsp code which has other functionality script, that time its not working. Please help me on this.
<%# page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>section</title>
<style>
</style>
<!-- date picker -->
<link rel="stylesheet" href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.16/themes/base/jquery-ui.css" type="text/css" media="all" />
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js" type="text/javascript"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.16/jquery-ui.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(function() {
$( "#datepicker" ).datepicker();
} );
</script>
<!-- addrows functionality -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
var i=1;
$("button").click(function(){
$('#add'+i).html("<td><select name='inpparameter0"+i+"'id='input_parameter'><option value='P1'>Type/Rating</option><option value='P2'>Operating Check</option><option value='P3'>Ext.Apperance</option><option value='P4'>Verify TC</option><option value='P5'>Material</option<option value='P6'>Dimension Check</option><option value='P7'>Threads Check</option> <option value='P8'>Visual Check</option><option value='P9'>Specification</option><option value='P10'>Batch no</option><option value='P11'>Mfg. Date</option><option value='P12'>Exp. Date</option></select></td><td><select name='inpspec0"+i+"' id='input_spec'><option value='S1'>As per PO</option><option value='S2'>Damage</option><option value='S3'>OK</option><option value='S4'>Stainless Steel</option><option value='S5'>Gaues</option><option value='S6'>Mild Steel</option><option value='S7'>As per Drawing]</option><option value='S8'>Cast Iron</option><optionvalue='S9'>Copper</option><optionvalue='S10'>Aluminium</option><optionvalue='S11'>Brass</option><option value='S12'>Spring Steel</option><option value='S13'>Tool Steel</option></select> </td><td class='Body_Cell'><input type='text' name='inpact1"+i+"' id='inpact1' value='NIL'></td><td class='Body_Cell'><input type='text' name='inpact2"+i+"' id='inpact2' value='NIL'></td><td class='Body_Cell'><input type='text' name='inpact3"+i+"' id='inpact3' value='NIL'></td><td class='Body_Cell'><input type='text' name='inpact4"+i+"' id='inpact4' value='NIL'></td><td class='Body_Cell'><input type='text' name='inpact5"+i+"' id='inpact5' value='NIL'></td>");
$('#tab_logic').append('<tr id="add'+(i+1)+'"></tr>');
i++;
});
});
</script>
<script>
<!-- For calling Populate Table Servlet for getting Item list -->
<script src="http://code.jquery.com/jquery-latest.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$("#tablediv").hide();
$("#showTable").click(function(event){
$.post('PopulateTable',{pono : $('#pono').val()},function(responseJson) {
if(responseJson!=null){
$("#itemtable").find("tr:gt(0)").remove();
var table1 = $("#itemtable");
$.each(responseJson, function(key,value) {
var rowNew = $("<tr><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td></tr>");
rowNew.children().eq(0).html('<input type="checkbox"/>');
rowNew.children().eq(1).text(value['itemname']);
rowNew.children().eq(2).text(value['itemcode']);
rowNew.children().eq(3).text(value['supplier']);
rowNew.children().eq(4).text(value['totalqty']);
rowNew.children().eq(5).html('<input type="text"/>');
rowNew.children().eq(6).html('<input type="text"/>');
rowNew.children().eq(7).html('<input type="text"/>');
rowNew.appendTo(table1);
});
}
});
$("#tablediv").show();
});
});
</script>
</script>
<script>
$(document).ready(function() {
$("#find").click(function(event){
$.ajax({
url : 'callserv0',
type: 'POST',
data : {
grnno : $('#grn').val()
},
success : function(data) {
alert("Please hold on!");
var str = data;
var res = str.split(",");
$('#pono').val(res[0]);
$('#podt').val(res[1]);
return false;
}
});
});
});
</script>
<script>
/* function to show dropdown list of print menu*/
function myFunction() {
document.getElementById("myDropdown").classList.toggle("show");
}
// Close the dropdown if the user clicks outside of it
window.onclick = function(e) {
if (!e.target.matches('.dropbtn')) {
var dropdowns = document.getElementsByClassName("dropdown-content");
for (var d = 0; d < dropdowns.length; d++) {
var openDropdown = dropdowns[d];
if (openDropdown.classList.contains('show')) {
openDropdown.classList.remove('show');
}
}
}
}
/* reload the page when user clicks new button*/
function myfun1() {
location.reload(true);
}
/* to allow only numerical values in GRn field*/
function isNumber(evt) {
evt = (evt) ? evt : window.event;
var charCode = (evt.which) ? evt.which : evt.keyCode;
if (charCode > 31 && (charCode < 48 || charCode > 57)) {
return false;
}
return true;
}
</script>
</head>
<body>
<form>
<img border="0" src="mwlogo.gif" alt="logo" id="topright">
<header><h1>testing</h1></header>
<ul>
<li>Newreload</li>
<li>Helptest</li>
<li>Logout</li>
<li class="dropdown">
Print
<div class="dropdown-content" id="myDropdown">
Print Current Report
Print Preview
Print Report for given date
Print Report for given period
</div>
</li>
</ul>
<p>
Receipt number: <input type="text" id="grn" onkeypress="return isNumber(event)" required/>
<input type="button" id="find" value="Find" class="button0"/>
Type of Evaluation <select name="Evalu">
<option value="electrical">Electrical</option>
<option value="mechanical">Mechanical</option>
</select>
Unit <select name="unit">
<option value="unit1">xx</option>
<option value="unit2">yy</option>
<option value="unit3">zz</option>
<option value="unit5">rr</option>
</select>
<br>
Report No <input type="text" name="irepno" maxlength="8"/>
Inspection date <input type="date" name="inspdate" id="datepicker" required/>
<br></br>
POod number: <input type="text" id="pono" />
POdt Date : <input type="text" id="podt" />
doc No <input type="text" name="invno"/>
doc Date <input type="text" name="invdate"/>
</p>
<input type="button" value="Show Item List" id="showTable" class="button1"/>
<br/>
<div id="tablediv">
<table cellspacing="0" id="itemtable" align="center">
<tr>
<td><input type="checkbox" /></td>
<th scope="col">Item name</th>
<th scope="col">Item code</th>
<th scope="col">Supplier</th>
<th scope="col">Received qty</th>
<th scope="col">Accepted qty</th>
<th scope="col">Rejected qty</th>
<th scope="col">Remarks</th>
</tr>
</table>
</div>
<br></br>
<table cellspacing="0" cellpadding="0" width="100%" id="tab_logic" >
<tr>
<th class="Header_Cell" width="91" align="center">Parameters</th>
<th class="Header_Cell" width="150" align="center">Specification</th>
<th class="Header_Cell" width="150" align="center">Actual1</th>
<th class="Header_Cell" width="50" align="center">Actual2</th>
<th class="Header_Cell" width="50" align="center">Actual3</th>
<th class="Header_Cell" width="50" align="center">Actual4</th>
<th class="Header_Cell" width="50" align="center">Actual5</th>
</tr>
<tr id ='add0'>
<td>
<select name="inpparameter0" id="input_parameter">
<option value="P1">Type/Rating</option>
<option value="P2">Operating Check</option>
<option value="P3">Ext.Apperance</option>
<option value="P4">Verify TC</option>
<option value="P5">Material</option>
<option value="P6">Dimension Check</option>
<option value="P7">Threads Check</option>
<option value="P8">Visual Check</option>
<option value="P9">Specification</option>
<option value="P10">Batch no</option>
<option value="P11">Mfg. Date</option>
<option value="P12">Exp. Date</option>
</select>
</td>
<td>
<select name="inpspec0" id="input_spec">
<option value="S1">As per PO</option>
<option value="S2">Damage</option>
<option value="S3">OK</option>
<option value="S4">Stainless Steel</option>
<option value="S5">Gaues</option>
<option value="S6">Mild Steel</option>
<option value="S7">As per Drawing]</option>
<option value="S8">Cast Iron</option>
<option value="S9">Copper</option>
<option value="S10">Aluminium</option>
<option value="S11">Brass</option>
<option value="S12">Spring Steel</option>
<option value="S13">Tool Steel</option>
</select>
</td>
<td class="Body_Cell"><input type="text" name="inpacta0" id="inpact1" value="NIL"/></td>
<td class="Body_Cell"><input type="text" name="inpactb0" id="inpact2" value="NIL"/></td>
<td class="Body_Cell"><input type="text" name="inpactc0" id="inpact3" value="NIL"/></td>
<td class="Body_Cell"><input type="text" name="inpactd0" id="inpact4" value="NIL"/></td>
<td class="Body_Cell"><input type="text" name="inpacte0" id="inpact5" value="NIL"/></td>
</tr>
</table>
<br>
<input type="button" value="Addrow" id="addrow" class="button1" style="float: right;">
<input type="button" value="Save the record" class="button0">
</form>
</body>
</html>

You have not used the id of the button while using the click event listener. You have used the 'button' class. Please use 'addrow' id of button to trigger the event. Also, use .on for triggering click events as .click doesn't work when DOM is manipulated. Move the $('#tab_logic').append above $("#addrow").on('click',function(){ because on first click there will be no <tr> to append the row.
$(document).ready(function(){
var i=1;
$("#addrow").on('click',function(){
$('#tab_logic').append('<tr id="add'+(i+1)+'"></tr>');
$('#add'+i).html("<td><select name='inpparameter0"+i+"'id='input_parameter'><option value='P1'>Type/Rating</option><option value='P2'>Operating Check</option><option value='P3'>Ext.Apperance</option><option value='P4'>Verify TC</option><option value='P5'>Material</option<option value='P6'>Dimension Check</option><option value='P7'>Threads Check</option> <option value='P8'>Visual Check</option><option value='P9'>Specification</option><option value='P10'>Batch no</option><option value='P11'>Mfg. Date</option><option value='P12'>Exp. Date</option></select></td><td><select name='inpspec0"+i+"' id='input_spec'><option value='S1'>As per PO</option><option value='S2'>Damage</option><option value='S3'>OK</option><option value='S4'>Stainless Steel</option><option value='S5'>Gaues</option><option value='S6'>Mild Steel</option><option value='S7'>As per Drawing]</option><option value='S8'>Cast Iron</option><optionvalue='S9'>Copper</option><optionvalue='S10'>Aluminium</option><optionvalue='S11'>Brass</option><option value='S12'>Spring Steel</option><option value='S13'>Tool Steel</option></select> </td><td class='Body_Cell'><input type='text' name='inpact1"+i+"' id='inpact1' value='NIL'></td><td class='Body_Cell'><input type='text' name='inpact2"+i+"' id='inpact2' value='NIL'></td><td class='Body_Cell'><input type='text' name='inpact3"+i+"' id='inpact3' value='NIL'></td><td class='Body_Cell'><input type='text' name='inpact4"+i+"' id='inpact4' value='NIL'></td><td class='Body_Cell'><input type='text' name='inpact5"+i+"' id='inpact5' value='NIL'></td>");
i++;
});
});
Hope it helps. :)

Related

unexcepted thymeleaf symbols and unexcepted values

I want ro concate some things in thymeleaf but concate symbol throws
unexcepted '+' error, I define ctotal in my common.kt class and want
to use the reference of the ctotal in cart.html but ctotal shows under
redline error I donot know which type of error it
cart.html
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head th:replace="fragments/head.html">
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<nav th:replace="/fragments/nav :: nav-front"></nav>
<div class="container-fluid mt-5">
<div class="row">
<div th:replace="/fragments/categories"></div>
<div class="col"></div>
<div class="col-7">
<div class="overlay text-center d-none">
<h4 class="display-4">You are being redirected to paypal...</h4>
<img src="/images/ajax-loader.gif" alt="">
</div>
<h2 class="display-4">Cart Overview</h2>
<table class="table">
<tr>
<th>Product</th>
<th>Image</th>
<th>Quantity</th>
<th>Price</th>
<th>Total</th>
</tr>
<tr th:each="el: ${cart}">
<td th:text="${el.value.name}"></td>
<td>
<img style="width: 100px;" th:src="#{'/media/' + ${el.value.image}}" />
</td>
<td>
<span th:text="${el.value.quantity}"></span>
<a th:href="#{'/cart/add/'+${el.value.id}} + '?cartPage=true'"
class="btn btn-success btn-sm">+</a>
<a th:href="#{'/cart/subtract/'+${el.value.id}}" class="btn btn-primary btn-sm">-</a>
<a th:href="#{'/cart/remove/'+${el.value.id}}" class="btn btn-danger btn-sm">remove</a>
</td>
<td th:text="'$' + ${el.value.price}"></td>
<td th:with="formattedTotal=${el.value.price} * ${el.value.quantity}" th:text="'$' + ${#numbers.formatDecimal(formattedTotal, 0, 'COMMA', 2, 'POINT')}"
>
</td>
</tr>
<tr>
<td class="text-right" colspan="4"><b>Grand Total:</b></td>
<td colspan="1" th:text="'$' + ${#numbers.formatDecimal(ctotal, 0, 'COMMA', 2, 'POINT')}"></td>
</tr>
<tr>
<td>
Clear Cart
</td>
<td colspan="4" class="text-right">
Checkout
</td>
</tr>
</table>
</div>
<div class="col"></div>
</div>
</div>
<form id="paypalform" action="https://www.sandbox.paypal.com/cgi-bin/webscr" method="post">
<input type="hidden" name="cmd" value="_cart">
<input type="hidden" name="upload" value="1">
<input type="hidden" name="business" value="zennil1305014666#gmail.com">
<th:block th:each="el, iter : ${cart}">
<input type="hidden" th:name="'item_name_'+${iter.count}" th:value="${el.value.name}">
<input type="hidden" th:name="'amount_'+${iter.count}" th:value="${el.value.price}">
<input type="hidden" th:name="'quantity_'+${iter.count}" th:value="${el.value.quantity}">
</th:block>
<input type="hidden" name="currency_code" value="USD">
<input type="image" src="http://www.paypal.com/en_US/i/btn/x-click-but01.gif" name="submit" alt="Make payments with PayPal - it's fast, free and secure!">
</form>
<div th:replace="/fragments/footer"></div>
<script>
$(function () {
$("a.checkout").click(function (e) {
e.preventDefault();
$("div.overlay").removeClass("d-none");
$.get("/cart/clear", {}, function () {});
$("form#paypalform").submit();
});
});
</script>
</body>
</html>
i got error exact line 33 on the '+' symbol
<a th:href="#{'/cart/add/'+${el.value.id}} + '?cartPage=true'"
class="btn btn-success btn-sm">+</a>
And got red underlined error below line
<td colspan="1" th:text="'$' + ${#numbers.formatDecimal(ctotal, 0, 'COMMA', 2, 'POINT')}"></td>
at ctotal i got redline error .ctotal i defined in my common class
common.kt
package com.nilmani.cmsshopingcart
import com.nilmani.cmsshopingcart.model.Cart
import com.nilmani.cmsshopingcart.model.Category
import com.nilmani.cmsshopingcart.model.Page
import com.nilmani.cmsshopingcart.repository.CategoryRepository
import com.nilmani.cmsshopingcart.repository.PageRepository
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.ui.Model
import org.springframework.web.bind.annotation.ControllerAdvice
import org.springframework.web.bind.annotation.ModelAttribute
import java.security.Principal
import javax.servlet.http.HttpSession
#ControllerAdvice
class Common {
#Autowired
private lateinit var pageRepo: PageRepository
#Autowired
private lateinit var categoryRepo: CategoryRepository
#ModelAttribute
fun sharedData(model: Model, session: HttpSession, principal: Principal?) {
if (principal != null) {
model.addAttribute("principal", principal.name)
}
val pages: List<Page> = pageRepo.findAllByOrderBySortingAsc()
val categories: List<Category> = categoryRepo.findAllByOrderBySortingAsc()
var cartActive = false
if (session.getAttribute("cart") != null) {
val cart: HashMap<Int, Cart> = session.getAttribute("cart") as HashMap<Int, Cart>
var size = 0
var total = 0.0
for (value in cart.values) {
size += value.quantity
total += value.quantity * value.price.toDouble()
}
model.addAttribute("csize", size)
model.addAttribute("ctotal", total)
cartActive = true
}
model.addAttribute("cpages", pages)
model.addAttribute("ccategories", categories)
model.addAttribute("cartActive", cartActive)
}
}

Ajax to load table data

Request your help, as the below line of code if not loading the data into the table when i choose the related radio button, not sure what is wrong nor missing, if there is any alternate way other then this please do let me know.
Code
<div>
<label class="form-check-label><input type="radio" class="form-check-input" name="Gender" value="M" checked>Male</label>
<label class="form-check-label><input type="radio" class="form-check-input" name="Gender" value="F" checked>Female</label>
</div>
<div class="row" id="Dbackup">
<table id="Backup">
<thead>
<tr>
<th>Name</th><th>Gender</th>
</tr>
</thead>
<tbody>
<tr><td>xxxx<</td><td>Male</td></tr>
.
.
<tr><td>xxxx<</td><td>Female</td></tr>
</tbody>
</table>
</div>
**Ajax script**
<script type="text/javascript">
$(document).ready(function(){
$("input[type='radio']").on('click', function(){
var radioValue = $("input[name='Gender']:checked").val();
$.ajax({
url: "/gdata/" + radioValue,
method: "GET",
data:{rvalue:radioValue},
success: function(data){
$('#Backup').load(data);
}
});
});
});
</script>
From,
Vino

Validating Checkboxlist inside a Datalist

the validation is not working on my checkboxlist.
<td style="background-color:#cbd5df">
<span id="DataList1_ctl01_CheckBoxList1" style="font-family: Trebuchet MS;background-color: #cbd5df">
<input id="DataList1_ctl01_CheckBoxList1_0" type="checkbox" name="DataList1$ctl01$CheckBoxList1$0" />
<label for="DataList1_ctl01_CheckBoxList1_0">Product A</label><br /><input id="DataList1_ctl01_CheckBoxList1_1"
type="checkbox" name="DataList1$ctl01$CheckBoxList1$1" /><label for="DataList1_ctl01_CheckBoxList1_1">Product B</label>
<br /><input id="DataList1_ctl01_CheckBoxList1_2" type="checkbox" name="DataList1$ctl01$CheckBoxList1$2" />
<label for="DataList1_ctl01_CheckBoxList1_2">Product c</label></span><br/><br/>
<span id="DataList1_ctl01_Labelx"></span>
</td>
Then the JS below:
<script type = "text/javascript">
function ValidateCBL(source, args) {
var cblist= $(source).parent().find("table[id$='DataList1_ctl01_CheckBoxList1']");
if (cblist.length==0 || cblist.find('input:checkbox:checked').length > 0)
{
args.IsValid = true;
}
else {args.IsValid = false;}
}
</script>
What am I doing wrong??

How can I Add Custom Validation in Kendo Grid Popup

How can I add validation for minimum length to a Textbox and display custom error messages?
I want validation for the following:
UserName to have a minimum length of 6
Password and Confirm Password to match
Address1 is required
Here is the code for the popup template. The specified minlength in the template is not working but the maxlength is working properly.
<script id="popup_editor" type="text/x-kendo-template">
<table cellpadding="0" cellspacing="0">
<tr>
<td>
<label for="UserName"><b>UserName*</b></label>
</td>
<td>
<div class="control-row">
<input type="text"
name="UserName"
id="UserName"
class="k-input k-textbox"
required
**minLength**="6"
maxlength="8"
pattern="[a-zA-Z0-9]+"
validationMessage="Please enter username"/>
<span class="k-invalid-msg" data-for="UserName" ></span>
</div>
</td>
<td></td>
<td></td>
</tr>
<tr>
<td>
<div>
<label for="Password"><b>Password*</b></label>
</div>
</td>
<td>
<div class="k-edit-label">
<input type="password"
id="Password"
name="Password"
class="k-input k-textbox"required
validationMessage="Please enter Password"/>
<span class="k-invalid-msg" data-for="Password"></span>
</div>
</td>
<td>
<div>
<label for="ConfirmPassword" style=""><b>Confirm Password</b></label>
</div>
</td>
<td>
<div class="k-edit-label">
<input type="password"
id="ConfirmPassword"
name="ConfirmPassword"
class="k-input k-textbox"required
validationMessage="Please enter Confirm Password"/>
</div>
</td>
</tr>
<tr>
<td>
<div>
<label for="Company_Name"><b>Company Name*</b></label>
</div>
</td>
<td>
<div class="k-edit-label">
<input name="Company_Name"
id="Company_Name"
required
pattern="[a-zA-Z0-9]+"
validationMessage="Please enter Valid CompanyName"/>
</div>
</td>
<td></td>
<td></td>
</tr>
<tr>
<td>
<div>
<label for="First_Name"><b>First Name*</b></label>
</div>
</td>
<td>
<div class="k-edit-label">
<input type="text"
name="First_Name"
id="First_Name"
data-type="string"
data-bind="value:First_Name"
class="k-input k-textbox" required
pattern="[a-zA-Z]+"
validationMessage="Please enter FirstName"/>
</div>
</td>
<td>
<div>
<label for="Last_Name"><b>Last Name*</b></label>
</div>
</td>
<td>
<div class="k-edit-label">
<input type="text"
id="Last_Name"
name="Last_Name"
class="k-input k-textbox" required
pattern="[a-zA-Z]+"
validationMessage="Please enter LastName"/>
</div>
</td>
</tr>
<tr>
<td>
<div>
<label for="Address1"><b>Address1*</b></label>
</div>
</td>
<td>
<div class="k-edit-label">
<textArea style="resize: none;"
rows="5"
cols="18"
name="Address1"
maxlength="150"
id="Address1" required
pattern="[a-zA-Z0-9]+"
validationMessage="Please enter Address">
</textarea>
</div>
</td>
</tr>
</table>
You can add custom validation for popup editing within the dataSource of your grid.
var dataSource = new kendo.data.DataSource({
transport: {
...
},
schema: {
model: {
id: "UserName",
fields: {
UserName: {}
Password: {}
ConfirmPassword: {}
Company_Name: {}
First_Name: {}
Last_Name: {}
Address1: {
validation: {
minLength: function (input) {
if (input.is("[name=UserName]")) {
return input.val().length >= 6;
}
return true;
},
match: function (input) {
if (input.is("[name=ConfirmPassword]")) {
return input.val() == $("#Password").val();
}
return true;
}
}
}
}
}
}
});
There are a few things to respect:
The validation runs for ALL input elements within your popup, therefore
you only have to define it for ONE of the fields in your model. Which one does not matter.
you have to check which input element is checked in the current run, which does the if statement in my example.
you have to append a return true at the end of each and every rule you define or otherwise you'll get an error message for every input you're not explicitly checking. If there's no return value passed, kendo automatically assumes the check had a false result.
Every validation rule needs its own validation message or otherwise your validation tooltip box will only display a warning logo without any text. You can add it as an html attribute (data-{validation rule}-msg) in your input elements, like this:
<input type="text"
name="UserName"
id="UserName"
class="k-input k-textbox"
required
maxlength="8"
pattern="[a-zA-Z0-9]+"
validationMessage="Please enter username"
data-minLenght-msg="Username must be at least 6 characters"/>
<input type="password"
id="ConfirmPassword"
name="ConfirmPassword"
class="k-input k-textbox"
required
validationMessage="Please enter Confirm Password"
data-match-msg="Password and confirmation must be equal"/>
Hope this helps
In rules add this:
match: function (input) {
if ((input.is('[name=\'Password\']') || input.is('[name=\'ConfirmPassword\']'))&& $('#ConfirmPassword').length !== 0) {
if ($('#Password').val().length > 0 && $('#ConfirmPassword').val().length > 0) {
if (input.is('[name=\'Password\']')) {
return input.val() === $('#ConfirmPassword').val();
}
else if (input.is('[name=\'ConfirmPassword\']')) {
return input.val() === $('#Password').val();
}
}
}
return true;
},
minLength: function (input) {
if (input.is("[name=UserName]")) {
return input.val().length >= 6;
}
return true;
},
requiredAddress: function (input) {
if (input.is("[name=Address1]")) {
return $('#Address1').val() !== '' ? false : true;
}
return true;
}

How to add an increment value for each id attribute within the div contents with cloned jQuery object

Having a hard time figuring out how to add an increment value for each id attribute within the div contents with cloned jQuery object.
http://jsfiddle.net/hvK8d/
===================== HTML=====================
<div class="upload-file-container">
<div class="uploadFile left clearfix">
<input type="file" id="FileUpload1">
<table id="RadioButtonList1">
<tbody>
<tr>
<td><input type="radio" value="Resume" id="RadioButtonList1_1">
<label for="RadioButtonList1_1">Resume</label></td>
<td><input type="radio" value="Letter of Recommendation" id="RadioButtonList1_2">
<label for="RadioButtonList1_2">Letter of Recommendation</label></td>
<td><input type="radio" value="Other" id="RadioButtonList1_3">
<label for="RadioButtonList1_3">Other</label></td>
</tr>
</tbody>
</table>
</div>
Remove </div>
<div class=""><a class="plus" href="javascript:;">plus one</a></div>
===================== JQUERY =====================
//Cloning upload file control
$('.remove').live('click', function () {
if (confirm("Are you sure you wish to remove this item?")) {
$(this).parent().slideUp('fast', function () {
$(this).remove();
});
}
return false;
});
$('.plus').click(function () {
console.log('cloning');
var divCloned = $('.upload-file-container:first').clone();
divCloned.hide().insertAfter('.upload-file-container:last').slideDown('fast');
return false;
});
For the sake of completeness I will put here a small solution making use of a "template."
A class for hiding the template:
.upload-file-container.template {
display: none;
} ​
A small function to do replacements:
$.fn.template = function(variables) {
return this.each(function() {
this.innerHTML = this.innerHTML.replace(/{{(.+)}}/g, function(match, variable) {
return variables[variable];
});
return this;
});
};
A template:
<div class="upload-file-container template">
<div class="uploadFile left clearfix">
<input type="file" id="FileUpload{{id}}">
<table id="RadioButtonList{{id}}"><tbody>
<tr>
<td>
<input type="radio" value="Resume" id="RadioButtonList{{id}}_1">
<label for="RadioButtonList{{id}}_1">Resume</label>
</td>
</tr>
</tbody></table>
</div>
</div>
Usage:
var count = 0;
var divCloned = $(".upload-file-container.template")
.clone()
.removeClass("template")
.template({
id: count++
});
Instead of using numbered IDs, you should be using the array-like notation (e.g. RadioButtonList[]) in the name attribute, and wrap your labels around the inputs:
<td>
<label for="RadioButtonList1_1">
<input type="radio" value="Resume" name="RadioButtonList1[]">
Resume
</label>
</td>
<td>
<label for="RadioButtonList1_2">
<input type="radio" value="Letter of Recommendation" name="RadioButtonList2[]">
Letter of Recommendation
</label>
</td>
<td>
<label for="RadioButtonList1_3">
<input type="radio" value="Other" name="RadioButtonList3[]">
Other
</label>
</td>
P.S. You should also consider using a more descriptive name than RadioButtonList.

Resources