jsp- How to copy URL in a javascript function? - javascript

I have a JSP page that looks like this:
I added a button Copy URL and it's self explanatory that when I click the button, I need to copy the unique URL for that particular link itself.
This is how my front end looks:
<%
//need to input logic to populate data on each row
int counter=0;
String[] split = request.getParameter("nodeID").split(",",0);
for(int i=0;i<split.length;i++){
long file=Long.parseLong(split[i]);
List files = fileFacade.list_items(file);
for (Iterator rstltr = files.iterator(); rstltr.hasNext();) {
Fmedia fv = (Fmedia) rstltr.next();
Node nd = nodeFacade.get(fv.getNodeid(), false);
// Fmedia fm = fileFacade.get_file(fv.getNodeid());
int count = 0;
count++;
long fileid= nd.getNodeid();
%>
<tbody>
<tr>
<td width="5%">
<!--Display Checkbox -->
<input type="checkbox" name="name1" />
</td>
<td>
<!--Display No -->
<% counter=counter+1;
out.print(counter);
%>
</td>
<td width="28%">
<!-- Display Filename -->
<%=nd.getNodedesc()%>
</td>
<td width="100%">
<!-- Display URL -->
<%="http://localhost:8080/repository/file/view/viewPDF.jsp?count=1&f0="+nd.getNodeid()%>
<%
fileFacade.insert_url(nd.getNodeid(),"http://localhost:8080/repository/file/view/viewPDF.jsp?count=1&f0="+nd.getNodeid());
%>
</td>
<td>
<!-- Display EDIT/DEL -->
</td>
<td> <!-- Display COPY feature -->
<input type="button" value="Copy URL" onclick="msg()">
<script>
function msg() {
alert("Hello world!");
}
</script>
</td>
</tr>
</tbody>
<%}}
%>
I need a way that each button is independent of each row and a javascript function to be able to copy the link after selecting the checkbox.
I am not too sure how to proceed from here.
Can anyone suggest a good approach?
EDIT:
Javascript function:
<input type="button" value="Copy URL" onclick="getURL()">
<script>
function getURL() {
var copyText = "http://localhost:8080/repository/file/view/viewPDF.jsp?count=1&f0="+<%nd.getNodeid();%>
var el = document.createElement('textarea');
el.value = copyText;
el.setAttribute('readonly', '');
el.style = {
position: 'absolute',
left: '-9999px'
};
document.body.appendChild(el);
el.select();
document.execCommand('copy');
document.body.removeChild(el);
}
</script>
</td>

You have to pass URL to the function, follow the below code
<tbody>
<tr>
<td width="5%">
<!--Display Checkbox -->
<input type="checkbox" name="name1" />
</td>
<td>
<!--Display No -->
<% counter=counter+1;
out.print(counter);
%>
</td>
<td width="28%">
<!-- Display Filename -->
<%=nd.getNodedesc()%>
</td>
<td width="100%">
<!-- Display URL -->
<%="http://localhost:8080/repository/file/view/viewPDF.jsp?count=1&f0="+nd.getNodeid()%>
<%
fileFacade.insert_url(nd.getNodeid(),"http://localhost:8080/repository/file/view/viewPDF.jsp?count=1&f0="+nd.getNodeid());
%>
</td>
<td>
<!-- Display EDIT/DEL -->
</td>
<td> <!-- Display COPY feature -->
<input type="button" value="Copy URL" onclick="copyURL('<%="http://localhost:8080/repository/file/view/viewPDF.jsp?count=1&f0="+nd.getNodeid()%>')">
</td>
</tr>
</tbody>
<%}}
%>
<script>
function copyURL(url) {
var copyText = url;
var el = document.createElement('textarea');
el.value = copyText;
el.setAttribute('readonly', '');
el.style = {
position: 'absolute',
left: '-9999px'
};
document.body.appendChild(el);
el.select();
document.execCommand('copy');
document.body.removeChild(el);
}
</script>

Related

docent display pop up with table id

When I click on my button "Select" it should show me the HTML popup, and for some reason is not happening.
Could it be some id problem or hard code?
The main idea is to click and bring some kind of list reading from a random array list.
Below: my .js with the call back id and display.
Any ideas?
<!-- This hosts all HTML templates that will be used inside the JavaScript code -->
<table class ="cls-{id} active-{active}" style="display: none;" width="100%" id="rowTemplate">
<tr class ="bb cls-{id} active-{active}">
<td class="active-{active}" id="{id}-question" width="70%">{question}</td>
<td class="cls-{id} active-{active}" width="30%">
<button class="buttons" step="0.01" data-clear-btn="false" style="background: #006b54; color:white !important ;" id="{id}-inspectionResult"></button>
</td>
</tr>
</table>
<div id="projectPopUp" class="popup-window" style="display:none">
<div class="popuptitle" id="details-name"></div>
<table width="100%" id="detailsgrid">
<tr>
<td style="text-align:left">Start Time</td>
<td> <select id="details-startTime" data-role="none"></select></td>
</tr>
<tr>
<td style="text-align:left">End Time</td>
<td> <select id="details-endTime" data-role="none"></select></td>
</tr>
</table>
<div>
<button class="smallButton" onClick="closeProjectPopup()">Cancel</button>
<button class="smallButton" onClick="submitProjectPopup()">Submit</button>
</div>
</div>
<table style="display: none;" id="sectionRowTemplate">
<tr width="100%" class="bb cls-{id}-row2 sectionheader">
<td class="cls-{id}" colspan="3">{question}</td>
</tr>
</table>
Javascript code:
var buildQuestionnaire = function(){
parseInitialDataHolder();
for (var i = 0; i < ARRAY_OF_QUESTIONS.length; i++){
var id = i;
var data = {
id: id,
question: ARRAY_OF_QUESTIONS[i].question,
inspectionResult: '',
active: true
};
var initialdata = initialdataholder[id];
if(initialdata) {
data = initialdata;
}
dataholder.push(data);
if (typeof ARRAY_OF_QUESTIONS[i].header == 'undefined') {
$('#questionsTable tbody').append(Utils.processTemplate("#rowTemplate tbody", data));
$("#" + id + "-inspectionResult").text(data.inspectionResult || 'Select');
$("#" + id + "-inspectionResult").click(resultHandler.bind(data));
updateActiveStatus(data);
commentvisibilitymanager(data);
}
else {
$('#questionsTable tbody').append(Utils.processTemplate("#sectionRowTemplate tbody", data));
}
}
}
//to show the popup
$('#projectPopUp').show();
//to close the popup
$('#projectPopUp').hide();
$(document).ready(function() {
buildQuestionnaire();
});

jQuery function to create HTML table from another HTML table

I have an HTML table on a page that I'd like to use jQuery to take the information from, clean/sanitize it, and create a new "clean" HTML table with the information.
I have the table with the following <tr> structure:
<tr class="dirRow">
<td style="border-style:None;width:35px;">
<a href="http://www.link.com">
<img class="class-here" src="/media/proxy.ashx?id=xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx&size=50w50h_fxd" style="border-width:0px;height:35px;width:35px;">
</a>
</td>
<td style="border-style:None;">
Full Name
</td>
<td style="border-style:None;">
<span>123.456.7890</span>
</td>
<td style="border-style:None;">
<span>456.789.0123</span>
</td>
<td style="border-style:None;">
<span>Office</span>
</td>
<td style="border-style:None;">
<span>Title</span>
</td>
<td style="border-style:None;">
<span>Supervisor</span>
</td>
</tr>
<!-- 150+ more tr with same structure -->
Which I'd like to input the information into the following table (formatted this way to use a plugin that takes this table input and formats it into an org chart). I've commented how the information should be modified from the original HTML table.
<table id="orgChartData">
<tbody>
<tr>
<th>id</th>
<th>parent id</th>
<th>image</th>
<th>name</th>
<th>phone</th>
<th>phonecell</th>
<th>office</th>
<th>title</th>
<th>supervisor</th>
</tr>
<tr>
<td>
<!-- Full Name (text only, no href, goes here) -->
Full Name
</td>
<td>
<!-- Supervisor (text only, no span, goes here) -->
Supervisor
</td>
<td>
<!-- img src (just the relative path, no query string) -->
/media/proxy.ashx?id=xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx
</td>
<td>
<!-- Full Name (including href with "xlink:" added to the beginning of the href) -->
<a xlink:href="http://www.google.com/" target="_blank">Full Name</a>
</td>
<td>
<!-- Phone (no span) -->
123.456.7890
</td>
<td>
<!-- Phonecell (no span) -->
456.789.0123
</td>
<td>
<!-- Office (no span) -->
Office
</td>
<td>
<!-- Title (no span) -->
Title
</td>
<td>
<!-- Supervisor (no span) -->
Supervisor
</td>
</tr>
</tbody>
</table>
Updated my code based on Michael Sacket's answer below
I now have all the variables in the right format, but need to create the new <tr>s based on these variables.
$('tr.dirRow').each(function () {
var tds = $(this).children();
var fullName = tds.eq(1).text();
var supervisor = tds.eq(6).text();
var imgSource = tds.eq(0).find("img").attr("src");
var imgSourceClean = imgSource.substring(0, imgSource.indexOf('&'));
var fullNameHref = tds.eq(1).find("a").attr("href");
var fullNameHyperlink = '<a xlink:href="' + fullNameHref + '">' + fullName + '</a>';
var phone = tds.eq(2).text();
var phoneCell = tds.eq(3).text();
var office = tds.eq(4).text();
var title = tds.eq(5).text();
});
Thanks for any help.
My suggestion is to break it up, one part at a time. To get you started:
Getting the data
var data = [];
var tds = null;
$('tr.dirRow').each(function(){
tds = $(this).children();
data.push({
"fullName": tds.eq(1).text()
});
});
console.log(data);
Sending it to the destination table
// grab a reference to the destination table
var destTbody = $('#orgChartData > tbody');
// loop through the data adding rows
var newRow = null;
for(var i=0;i<data.length;i++){
newRow = $('<tr/>');
newRow.append( $('<td>' + data[i].fullName + '</td>') );
destTbody.append(newRow);
}
Note: You could also do all that in a single loop within the $('tr.dirRow').each().

Issue replacing input value in array

I did an example about replacing the input value when the row is deleted but is not working (this is not a static example).
<script src="./edit_files/prototype.js" type="text/javascript"></script>
<script src="./edit_files/application.js" type="text/javascript"></script>
<div class="contact">
<table border="0">
<tr>
<td><select class="position_id" id="obj_client_contact_attributes__position_id" name="obj_client[contact_attributes][][position_id]"><option value="1" selected="selected">INTELIGENT</option><option value="2">OTHER</option></select></td>
<td><input class="should_change_value" id="obj_client_contact_attributes__phone_mail" name="obj_client[contact_attributes][][phone_mail]" type="text" value="cristianoronaldo#realmadrid.com"/></td>
<td>
DELETE
<input id="obj_client_contact_attributes__id" name="obj_client[contact_attributes][][id]" type="hidden" value="16594"/>
<input class="should_destroy" id="obj_client_contact_attributes__should_destroy" name="obj_client[contact_attributes][][should_destroy]" type="hidden"/>
</td>
</tr>
</table>
</div>
<div class="contact">
<table border="0">
<tr>
<td><select class="position_id" id="obj_client_contact_attributes__position_id" name="obj_client[contact_attributes][][position_id]"><option value="1" selected="selected">INTELIGENT</option><option value="2">OTHER</option></select></td>
<td><input class="should_change_value" id="obj_client_contact_attributes__phone_mail" name="obj_client[contact_attributes][][phone_mail]" type="text" value="ONLY THE INPUT WILL BE test#hotmail.com IF I CLICK ON DELETE"/></td>
<td>
DELETE
<input id="obj_client_contact_attributes__id" name="obj_client[contact_attributes][][id]" type="hidden" value="16594"/>
<input class="should_destroy" id="obj_client_contact_attributes__should_destroy" name="obj_client[contact_attributes][][should_destroy]" type="hidden"/>
</td>
</tr>
</table>
</div>
Here is the application.js file:
function mark_for_destroy_contact(element,should_destroy,should_change_value) {
var element_text = $(element).up('.contact').down('.position_id',0);
element_text.className = 'position_id';
element_text.value = '';
if (should_destroy) {
$(element).next('.should_destroy').value = 1;
}
$(element).up('.contact').hide();
}
I tried this code but only works if I remove the first row.
function mark_for_destroy_contact(element,should_destroy,should_change_value) {
var element_text = $(element).up('.contact').down('.position_id',0);
element_text.className = 'position_id';
element_text.value = '';
$('should_change_value').update("test#hotmail.com");
if (should_destroy) {
$(element).next('.should_destroy').value = 1;
}
$(element).up('.contact').hide();
}
Here is the live example in jsfiddle
Here is the example download on Github but is not replacing the input value correctly
Ok I got it, you want to change the input value when the row is deleted, so do this:
function mark_for_destroy_contact(element,should_destroy,should_change_value) {
var element_text = $(element).up('.contact').down('.position_id',0);
element_text.className = 'position_id';
element_text.value = '';
var element_text2 = $(element).up('.contact').down('.should_change_value',0);
element_text2.className = 'should_change_value';
element_text2.value = 'test#hotmail.com';
if (should_destroy) { $(element).next('.should_destroy').value = 1;}
$(element).up('.contact').hide();
}

Trying to serialize a form with dynamically created input elements, but values of elements aren't posted

I am dynamically adding elements. However when I try and serialize the form, none of the dynamically generated elements are serialized.
This is the function I'm using to add elements to the page :
function addObjects(IDname,classname)
{
//to add more objects
var number;
switch(classname)
{
case "name":
number = no_Name++;
break;
case "part":
number = no_part++;
break;
}
var id = classname + number;
$("#"+IDname).append('<tr class="'+id+'"><td><input id="'+id+'" class="'+id+'" type="text"> <button class="'+id+'" onclick=removeAdditions("'+id+'")>x</button></td></tr>');
}
The page looks like this:
<html>
<head>
<script src="Controller.js" type="text/javascript"></script>
<script type="text/javascript" src="https://ajax.microsoft.com/ajax/jQuery/jquery-1.4.2.min.js"></script>
<script type="text/javascript">
//in order to prevent form reload when button click occurs
$(document).ready(function(){
document.getElementById("ReportForm").onsubmit = function (event) { event.preventDefault(); }
});
</script>
</head>
<body>
<div class="detailsPane" id="detailsPane1" >
<form id="ReportForm" name="ReportForm" >
<table style="width: 100%;">
<tbody>
<tr>
<td>
1. Describe the Status briefly-
</td>
<td>
<textarea id="StatDescp" name="StatDescp"></textarea>
</td>
</tr>
</tbody>
</table>
<br>
<table style="width: 100%;">
<thead>
<tr>
<th colspan="4" align="top">
Part Status
</th>
</tr>
</thead>
<tbody>
<tr>
<td style="vertical-align:top;">
Part Name:
</td>
<td style="vertical-align:top;">
<table >
<tbody id="PartName">
<tr class="partname0">
<td><input class="part_name" type="text"> <button onclick='addObjects("PartName","part_name");'>+</button></td>
</tr>
</tbody>
</table>
</td>
<tbody>
</table>
</form>
</div>
<div id="buttonDiv" >
<a class="bottomLeftResultDiv" id="messageBox"></a>
<input type="button" id="saveButton" value="Save" style="width:85px" onclick="save();" />
</div>
</body>
</html>
And finally here is the save Button.
function save() {
var select = document.getElementById('newReportPane');
var contents = $('#ReportForm').serialize();
contents = contents.replace(/=on/g, "=checked");
contents = contents.replace(/\+/g, " ");
$("#messageBox").html("Saving report...");
console.log(contents);
$.post("/Report/Report1", { action: "save", content: contents }, function (data) {
if (data != "ACK")
$("#messageBox").html("Unable to save.");
else
$("#messageBox").html("Report saved successfully");
});
}
When I click on the save button, it only posts this StatDescp= without any of the dynamically generated elements.
I really can't figure out why.
Any help would be appreciated.
Give a name= attribute to each of your added inputs.
From http://api.jquery.com/serialize/
For a form element's value to be included in the serialized string,
the element must have a name attribute.

Generate an error if number is repeated in a form

I have a web form for admin purposes where the user can change the order that a group of records is shown on a webpage.
For example: A table (tblStuff) in a database has three fields:
ContentID, Content, RecordPosition
The table has, say, four records:
1, Guess what, 1
2, More stuff, 2
3, Some stuff, 3
4, That's right, 4
The SQL code is:
SELECT * FROM tblStuff ORDER BY RecordPosition ASC
The user can use the form to change the RecordPosition number so that the order can read:
3, Some stuff, 1
2, More stuff, 2
1, Guess what, 3
4, That's right, 4
So... How can I validate the form so that the same number isn't entered twice into the RecordPosition field?
Hope this makes sense.
Here's the whole page
<%#LANGUAGE="VBSCRIPT" CODEPAGE="1252"%>
<!--#include virtual="/Connections/ENG.asp" -->
<%
' *** Restrict Access To Page: Grant or deny access to this page
MM_authorizedUsers=""
MM_authFailedURL="../default.asp"
MM_grantAccess=false
If Session("MM_Username") <> "" Then
If (true Or CStr(Session("MM_UserAuthorization"))="") Or _
(InStr(1,MM_authorizedUsers,Session("MM_UserAuthorization"))>=1) Then
MM_grantAccess = true
End If
End If
If Not MM_grantAccess Then
MM_qsChar = "?"
If (InStr(1,MM_authFailedURL,"?") >= 1) Then MM_qsChar = "&"
MM_referrer = Request.ServerVariables("URL")
if (Len(Request.QueryString()) > 0) Then MM_referrer = MM_referrer & "?" & Request.QueryString()
MM_authFailedURL = MM_authFailedURL & MM_qsChar & "accessdenied=" & Server.URLEncode(MM_referrer)
Response.Redirect(MM_authFailedURL)
End If
%>
<%
If Request.Form("action")="update" Then
'Set variables for update
Dim updateSQL, i
Dim cContentID, cPositionNumber
'Loop through records on screen and update
For i = 1 To fFormat(Request.Form("counter"))
'Create the proper field names to reference on the form
cContentID = "ContentID" & CStr(i)
cPositionNumber = "PositionNumber" & CStr(i)
'Create the update sql statement
updateSQL = "UPDATE tblContent SET PositionNumber=" & fFormat(Request.Form(cPositionNumber)) & " WHERE ContentID=" & fFormat(Request.Form(cContentID))
'Run the sql statement
Call sRunSQL(updateSQL)
Next
'Refresh page
Response.Redirect("record-order-modify-updated.asp")
End If
Function fFormat(vText)
fFormat = Replace(vText, "'", "''")
End Function
Sub sRunSQL(vSQL)
set cExecute = Server.CreateObject("ADODB.Command")
With cExecute
.ActiveConnection = MM_ENG_STRING
.CommandText = vSQL
.CommandType = 1
.CommandTimeout = 0
.Prepared = true
.Execute()
End With
End Sub
%>
<%
Dim rsCharityDetails
Dim rsCharityDetails_cmd
Dim rsCharityDetails_numRows
Set rsCharityDetails_cmd = Server.CreateObject ("ADODB.Command")
rsCharityDetails_cmd.ActiveConnection = MM_ENG_STRING
rsCharityDetails_cmd.CommandText = "SELECT * FROM tblCharityDetails"
rsCharityDetails_cmd.Prepared = true
Set rsCharityDetails = rsCharityDetails_cmd.Execute
rsCharityDetails_numRows = 0
%>
<%
Dim rsNavBar
Dim rsNavBar_cmd
Dim rsNavBar_numRows
Set rsNavBar_cmd = Server.CreateObject ("ADODB.Command")
rsNavBar_cmd.ActiveConnection = MM_ENG_STRING
rsNavBar_cmd.CommandText = "SELECT * FROM tblMainMenu WHERE MainMenuID <6 OR MainMenuID >7"
rsNavBar_cmd.Prepared = true
Set rsNavBar = rsNavBar_cmd.Execute
rsNavBar_numRows = 0
%>
<%
Dim rsContent__smID
rsContent__smID = "1"
If (Request.QueryString("smID") <> "") Then
rsContent__smID = Request.QueryString("smID")
End If
%>
<%
Dim rsContent
Dim rsContent_cmd
Dim rsContent_numRows
Set rsContent_cmd = Server.CreateObject ("ADODB.Command")
rsContent_cmd.ActiveConnection = MM_ENG_STRING
rsContent_cmd.CommandText = "SELECT tblContent.*, tblMainMenu.MainMenuName, tblSubMenu.SubMenuName, tblSubMenu.SubMenuID FROM (tblContent LEFT JOIN tblMainMenu ON tblContent.MainMenuID = tblMainMenu.MainMenuID) LEFT JOIN tblSubMenu ON tblContent.SubMenuID = tblSubMenu.SubMenuID WHERE tblContent.SubMenuID = ? AND tblContent.DisplayRecord =1 ORDER BY tblContent.PositionNumber"
rsContent_cmd.Prepared = true
rsContent_cmd.Parameters.Append rsContent_cmd.CreateParameter("param1", 5, 1, -1, rsContent__smID) ' adDouble
Set rsContent = rsContent_cmd.Execute
rsContent_numRows = 0
%>
<%
Dim rsMenuList
Dim rsMenuList_cmd
Dim rsMenuList_numRows
Set rsMenuList_cmd = Server.CreateObject ("ADODB.Command")
rsMenuList_cmd.ActiveConnection = MM_ENG_STRING
rsMenuList_cmd.CommandText = "SELECT tblMainMenu.MainMenuID, tblMainMenu.MainMenuName, tblSubMenu.SubMenuID, tblSubMenu.SubMenuName FROM tblMainMenu INNER JOIN tblSubMenu ON tblMainMenu.MainMenuID = tblSubMenu.MainMenuID WHERE tblSubMenu.SubMenuID <> 6 AND tblSubMenu.SubMenuID <16 OR tblSubMenu.SubMenuID >19"
rsMenuList_cmd.Prepared = true
Set rsMenuList = rsMenuList_cmd.Execute
rsMenuList_numRows = 0
%>
<%
Dim rsHeaderImage
Dim rsHeaderImage_cmd
Dim rsHeaderImage_numRows
Set rsHeaderImage_cmd = Server.CreateObject ("ADODB.Command")
rsHeaderImage_cmd.ActiveConnection = MM_ENG_STRING
rsHeaderImage_cmd.CommandText = "SELECT MainMenuImage, MainMenuID FROM tblMainMenu"
rsHeaderImage_cmd.Prepared = true
Set rsHeaderImage = rsHeaderImage_cmd.Execute
rsHeaderImage_numRows = 0
%>
<%
Dim navBar__numRows
Dim navBar__index
navBar__numRows = -1
navBar__index = 0
rsNavBar_numRows = rsNavBar_numRows + navBar__numRows
%>
<%
Dim rptContent__numRows
Dim rptContent__index
rptContent__numRows = -1
rptContent__index = 0
rsContent_numRows = rsContent_numRows + rptContent__numRows
%>
<%
Dim Repeat_MenuList__numRows
Dim Repeat_MenuList__index
Repeat_MenuList__numRows = -1
Repeat_MenuList__index = 0
rsMenuList_numRows = rsMenuList_numRows + Repeat_MenuList__numRows
%>
<!DOCTYPE HTML>
<html>
<head>
<meta charset="iso-8859-1">
<!-- disable iPhone inital scale -->
<meta name="viewport" content="width=device-width; initial-scale=1.0">
<title><%=(rsCharityDetails.Fields.Item("CharityName").Value)%> | English Website Administration</title>
<!-- main css -->
<link href="../../scripts/mfm-standard-stylesheet.css" rel="stylesheet" type="text/css">
<!--[if lt IE 9]>
<link href="../scripts/mfm-standard-stylesheet_ie.css" rel="stylesheet" type="text/css">
<![endif]-->
<!-- Admin css -->
<link href="../scripts/mfm-admin-stylesheet.css" rel="stylesheet" type="text/css">
<script src="../../scripts/jquery-1.7.2.min.js"></script>
<!-- jQuery NailThumb Plugin - any image to any thumbnail Examples and documentation at: http://www.garralab.com/nailthumb.php -->
<script src="../../scripts/jquery.nailthumb.1.1.js"></script>
<!-- Lightbox2 v2.51 by Lokesh Dhakar For more information, visit: http://lokeshdhakar.com/projects/lightbox2/ -->
<script src="../../scripts/lightbox.js"></script>
<!-- Lightbox css -->
<link href="../../scripts/lightbox.css" rel="stylesheet" type="text/css" media="screen" />
<script src="../tiny_mce/tiny_mce.js"></script>
<script src="../tiny_mce/tiny-mce-mfm.js"></script>
<!-- html5.js for IE less than 9 -->
<!--[if lt IE 9]>
<script src="http://html5shim.googlecode.com/svn/trunk/html5.js"></script>
<![endif]-->
<!-- css3-mediaqueries.js for IE less than 9 -->
<!--[if lt IE 9]>
<script src="http://css3-mediaqueries-js.googlecode.com/svn/trunk/css3-mediaqueries.js"></script>
<![endif]-->
</head>
<body id="other">
<div id="wrapper">
<header class="innerWidth">
<!--#include file="includes/header-modify-record.asp" -->
</header>
<nav class="innerWidth">
<!--#include file="includes/navbar-modify-record.asp" -->
</nav>
<!-- pageContent -->
<div id="content" class="innerWidth">
<!-- Aside -->
<aside>
<h3>Record Order</h3>
<ul>
<%
Dim txtOldHeading
txtOldHeading = ""
While ((Repeat_MenuList__numRows <> 0) AND (NOT rsMenuList.EOF))
If txtOldHeading = rsMenuList.Fields.Item("MainMenuName").Value Then
Else
txtOldHeading = rsMenuList.Fields.Item("MainMenuName").Value
%>
<li class="menuHeading"><%=(rsMenuList.Fields.Item("MainMenuName").Value)%></li>
<%
END IF
%>
<li class="menuList">
<% If (rsMenuList.Fields.Item("SubMenuID").Value) = "3" Then %>
<%=(rsMenuList.Fields.Item("SubMenuName").Value)%>
<% ElseIf (rsMenuList.Fields.Item("SubMenuID").Value) = "15" Then %>
<%=(rsMenuList.Fields.Item("SubMenuName").Value)%>
<% ElseIf (rsMenuList.Fields.Item("SubMenuID").Value) = "20" Then %>
<%=(rsMenuList.Fields.Item("SubMenuName").Value)%>
<% Else %>
<%=(rsMenuList.Fields.Item("SubMenuName").Value)%>
<% End If %>
</li>
<%
Repeat_MenuList__index=Repeat_MenuList__index+1
Repeat_MenuList__numRows=Repeat_MenuList__numRows-1
rsMenuList.MoveNext()
Wend
%>
</ul>
</aside>
<!-- /Aside -->
<!-- Article -->
<article>
<% IF Request.ServerVariables("QUERY_STRING") <> "" THEN %>
<h3><span style="font-size:small">Order/Re-order records for: </span><%=(rsContent.Fields.Item("SubMenuName").Value)%></h3>
<%
Dim counter
While ((rptContent__numRows <> 0) AND (NOT rsContent.EOF))
counter = counter + 1
%>
<form action="record-order-modify.asp" method="post" class="recordPosition">
<table width="100%">
<tr>
<td align="left" valign="top" name="ContentTitle" colspan="2"><h2><%=(rsContent.Fields.Item("ContentTitle").Value)%></h2><input type="hidden" value="<%=(rsContent.Fields.Item("ContentID").Value)%>" name="ContentID<%=counter%>"></td>
</tr>
<tr>
<td align="left" valign="top" name="ContentData"><%
Dim tmp
tmp = rsContent.Fields.Item("ContentData").Value
%>
<% =LEFT(tmp, INSTR((tmp & "."), ".")) %>..
</td>
<% IF (IsNull(rsContent.Fields.Item("ContentImage").Value)) THEN %>
<td width="140" align="center" valign="top" name="ContentImage"><img src="../images/system_images/red-x.png"></td>
<% ELSE %>
<td width="140" align="center" valign="top" name="ContentImage"><div class="nailthumb-container">
<!-- Thumbnail Container -->
<img src="<%=(rsContent.Fields.Item("ContentImage").Value)%>"> </div></td>
<% END IF %>
</tr>
<tr>
<td align="left"><label>Current Record Position: <small class="brown" style="text-transform:none">(You may change it here)</small></label> <input type="text" name="PositionNumber<%=counter%>" tabindex="<%=counter%>" value="<%=(rsContent.Fields.Item("PositionNumber").Value)%>"></td>
</tr>
</table>
<hr>
<%
rptContent__index=rptContent__index+1
rptContent__numRows=rptContent__numRows-1
rsContent.MoveNext()
Wend
%>
<table align="center" class="positionButtons">
<tr>
<td width="50%" align="right"><input name="Submit" type="submit" value="Update Positions" tabindex="<%=counter%>"></td>
<td width="50%" align="left"><input name="Reset" type="reset" value="Reset All Changes" tabindex="<%=counter%>"></td>
</tr>
</table>
<input type="hidden" name="action" value="update">
<input type="hidden" name="counter" value="<%=counter%>">
</form>
<% ELSE %>
<h3>Select a listing to order/re-order using the list on the left.</h3>
<% END IF %>
</article>
<!-- /Article -->
<script type="text/javascript">
jQuery(document).ready(function() {
jQuery('.nailthumb-container').nailthumb({width:125,height:125,fitDirection:'top center'});
});
</script>
</div>
<!-- /pageContent -->
<div class="push"></div>
</div>
<!-- #wrapper -->
<footer class="innerWidth">
<!--#include file="includes/footer.asp" -->
</footer>
</body>
</html>
<%
rsCharityDetails.Close()
Set rsCharityDetails = Nothing
%>
<%
rsNavBar.Close()
Set rsNavBar = Nothing
%>
<%
rsContent.Close()
Set rsContent = Nothing
%>
<%
rsMenuList.Close()
Set rsMenuList = Nothing
%>
<%
rsHeaderImage.Close()
Set rsHeaderImage = Nothing
%>
As requested by Allende, here's the generated form code.
<form action="record-order-modify.asp" method="post" class="recordPosition">
<table width="100%">
<tr>
<td align="left" valign="top" name="ContentTitle" colspan="2"><h2>Investing in people and the environment</h2><input type="hidden" value="15" name="ContentID1"></td>
</tr>
<tr>
<td align="left" valign="top" name="ContentData"><p>Madagascar is an environmental hotspot...
</td>
<td width="140" align="center" valign="top" name="ContentImage"><div class="nailthumb-container">
<!-- Thumbnail Container -->
<img src="/images/framed-images/mfm-website-(26).jpg"> </div></td>
</tr>
<tr>
<td align="left"><label>Current Record Position: <small class="brown" style="text-transform:none">(You may change it here)</small></label> <input type="text" name="PositionNumber1" tabindex="1" value="1"></td>
</tr>
</table>
<hr>
<table width="100%">
<tr>
<td align="left" valign="top" name="ContentTitle" colspan="2"><h2>The next generation</h2><input type="hidden" value="16" name="ContentID2"></td>
</tr>
<tr>
<td align="left" valign="top" name="ContentData"><p>Teaching Malagasy children to respect and nurture their environment is critical to the survival of Madagascar's biodiversity...
</td>
<td width="140" align="center" valign="top" name="ContentImage"><div class="nailthumb-container">
<!-- Thumbnail Container -->
<img src="/images/framed-images/mfm-website-(292).jpg"> </div></td>
</tr>
<tr>
<td align="left"><label>Current Record Position: <small class="brown" style="text-transform:none">(You may change it here)</small></label> <input type="text" name="PositionNumber2" tabindex="2" value="2"></td>
</tr>
</table>
<hr>
<table width="100%">
<tr>
<td align="left" valign="top" name="ContentTitle" colspan="2"><h2>Recognition for our work</h2><input type="hidden" value="17" name="ContentID3"></td>
</tr>
<tr>
<td align="left" valign="top" name="ContentData"><p>Our work over 2 decades with 73 villages surrounding the Reserve of Betampona recently gained recognition at an international conference held at the University of East Anglia...
</td>
<td width="140" align="center" valign="top" name="ContentImage"><div class="nailthumb-container">
<!-- Thumbnail Container -->
<img src="/images/framed-images/mfm-website-(56).jpg"> </div></td>
</tr>
<tr>
<td align="left"><label>Current Record Position: <small class="brown" style="text-transform:none">(You may change it here)</small></label> <input type="text" name="PositionNumber3" tabindex="3" value="3"></td>
</tr>
</table>
<hr>
<table width="100%">
<tr>
<td align="left" valign="top" name="ContentTitle" colspan="2"><h2>Adding value by adding forests</h2><input type="hidden" value="18" name="ContentID4"></td>
</tr>
<tr>
<td align="left" valign="top" name="ContentData"><p>Often the best way to protect an old forest is to plant a new one...
</td>
<td width="140" align="center" valign="top" name="ContentImage"><div class="nailthumb-container">
<!-- Thumbnail Container -->
<img src="/images/framed-images/mfm-website-(217).jpg"> </div></td>
</tr>
<tr>
<td align="left"><label>Current Record Position: <small class="brown" style="text-transform:none">(You may change it here)</small></label> <input type="text" name="PositionNumber4" tabindex="4" value="4"></td>
</tr>
</table>
<hr>
<table align="center" class="positionButtons">
<tr>
<td width="50%" align="right"><input name="Submit" type="submit" value="Update Positions" tabindex="4"></td>
<td width="50%" align="left"><input name="Reset" type="reset" value="Reset All Changes" tabindex="4"></td>
</tr>
</table>
<input type="hidden" name="action" value="update">
<input type="hidden" name="counter" value="4">
</form>
Let's suppose you have form like this (notice all the inputs has the same class):
<form id="myForm" method="POST" action"someUrl">
<input type="text" class="recordPosition"></input>
<input type="text" class="recordPosition"></input>
<input type="text" class="recordPosition"></input>
<input type="text" class="recordPosition"></input>
</form>
You could do with jQuery something like this:
$(document).ready(function(){
$(".recordPosition").on("blur", function(){
var allFieldsForOrder = $('.recordPosition');
var count = 0;
var i=0
//console.log(allFieldsForOrder.length );
while((i<allFieldsForOrder.length) && (count < 2)){
if ($(allFieldsForOrder[i]).val()===$(this).val())
{
count++
}
i++;
}
if (count==2){
alert("A duplicated value"); return false;}
});
});
For the html you posted you can use this:
Notice I don't store the position of the duplicated the value.
$(document).ready(function(){
//console.log($("input[type='text'][name^='PositionNumber'").length);
$("input[type='text'][name^='PositionNumber'").each(function(){
$(this).on("blur", function(){
var allFieldsForOrder = $("input[type='text'][name^='PositionNumber'");
var count = 0;
var i=0
while((i<allFieldsForOrder.length) && (count < 2)){
if ($(allFieldsForOrder[i]).val()===$(this).val())
{
count++
}
i++;
}
if (count==2){
alert("A duplicated value");
}
});
});
});
For the code above we assume you want to check for all the fields where the attribute name starts with the string "PositionNumber"
I will try to reduce the code later, I think there's a shortest way to check if is duplicated the "RecordPosition" value, but need to test some ideas.
This will be your solution (one of them):
$(document).ready(function(){
$('form').on("submit",function(){
var tempArray=[];
$("input[type='text'][name^='PositionNumber'").each(function(){
tempArray.push($(this).val());
});
var i=0;
var duplicated=false;
var currentElement;
while((tempArray.length >= 0) && (duplicated==false)){
//pop it out from the array
currentElement = tempArray.pop();
duplicated = tempArray.indexOf(currentElement)
}
//after you can use "duplicated" to cancel the submit
if (duplicated){
alert("duplicated value:" + currentElement);
return false;
}
});
});
I shorter version:
$(document).ready(function(){
$('form').on("submit",function(){
var tempArray=[];
var exists=0;
$("input[type='text'][name^='PositionNumber'").each(function(){
exists = tempArray.indexOf($(this).val());
if (exists>=0){
return false;//break the loop
}
tempArray.push($(this).val());
});
//after you can use "exist" to check if duplicated and retrieve the value to cancel the submit
if (exists>=0){
alert("duplicated value:" + tempArray[exists]);
} else{
alert("no duplicated value:");
}
return false;
});
});
If you want to prevent duplicate values in RecordPosition no matter how you insert/update them you can create a unique constraint this column
CREATE UNIQUE INDEX uq_idx_RecordPosition ON tblStuff(RecordPosition);
Here is SQLFiddle demo
If you're trying to do some client-side validation, you'd have to build an array that contains all the RecordPosition values.
Once you have that, you can check the array for duplicates. This has been asked a couple of times on SO: Easiest way to find duplicate values in a JavaScript array
Unfortunately I can't help any more than that because you don't include any code that shows how this is structured on your web page
Check before inserting data in to data base
ex: recordposition value 3 --> 1 then pass value 1
SELECT * FROM tblStuff Where RecordPosition=1
if record exist then give message to user this position is exist

Categories

Resources