Generate an error if number is repeated in a form - javascript

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

Related

how to get the value of the button by clicking that was created dynamically using loop

i created a html button in jsp using while loop i want to get the value of the specific button that was clicked but it shown result as undefined.
i don't no what to do and also don't no is it possible or not i am new to java Script.
Please help me thanks in advance.
Blockquote
this is what i tried but its not working giving the resut as undefined
<td><button value="<%= path%>" onclick="myFunction()"><%= path %></button></td>
<script>
function myFunction() {
alert(this.value);
<% session.setAttribute("gurufile",path );%>
}
</script>
Blockquote
this is my whole code i fetch the value of the button from the database
<%#page import="java.util.ArrayList"%>
<%#page import="java.sql.Statement"%>
<%#page import="java.sql.DriverManager"%>
<%#page import="java.sql.Connection"%>
<%#page import="java.sql.ResultSet"%>
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP Page</title>
</head>
<body>
<%
out.println(request.getParameter("roll_no"));
%>
<h3 align="center" style="color:BROWN;"> Dr.A.P.J. Abdul Kalam Technical University, Uttar Pradesh, Lucknow</h3>
<h4 align="center" >( Formerly Uttar Pradesh Technical University )</h4>
<h4 align="center" style="color:blue;">AKTU-OneView</h4>
</br>
<hr align="center" style="color:lightgrey;">
<h3>Student Result</h3>
<%!
//golbally declear
String class_name=null;
String branch=null;
String rollno =null;
String path =null;
ArrayList a = new ArrayList();
int count =0;
%>
<%
//String roll_no = "1634010009";
String roll_no = request.getParameter("roll_no");
String url="jdbc:mysql://localhost/student_result";
String username="root";
String password="bilalminto";
String query="select * from new_student where roll_no='"+roll_no+"'";
System.out.println("rollno "+roll_no);
try{
Class.forName("com.mysql.jdbc.Driver").newInstance();
Connection con=DriverManager.getConnection(url, username, password);
Statement st=con.createStatement();
ResultSet rs=st.executeQuery(query);
String student_name=null;
//String class_name=null;
//String branch=null;
//String rollno =null;
String father_name = null;
String mother_name = null;
if(rs.next()){
student_name=rs.getString("student_name");
class_name=rs.getString("class");
branch=rs.getString("branch");
rollno=rs.getString("roll_no");
father_name=rs.getString("fathers_name");
mother_name=rs.getString("mothers_name");
}
//Statement stm=con.createStatement();
//ResultSet rst=stm.executeQuery(query);
%>
<hr align="center" style="color:lightgrey;"></br>
<table width=100% border=1 cellspacing="0">
<tr align="left">
<td><b>Institute Code & Name :</b></td>
<td colspan="5"> (340) VIVEKANANDA COLLEGE OF TECHNOLOGY & MANAGEMENT, ALIGARH</td>
<td rowspan="5">print view</td>
</tr>
<tr>
<td><b>Course Code & Name:</b></td>
<td colspan="2"><%=class_name%></td>
<td ><b>Branch Code & Name</b></td>
<td colspan="2"><%=branch%></td>
<%
System.out.println("branch "+branch);
%>
</tr>
<tr>
<td><b>Roll No:</b></td>
<td colspan="2"><%=roll_no %></td>
<td><b>Enrollment No</b></td>
<td colspan="2">163401047822</td>
</tr>
<tr>
<td><b>Name:</b></td>
<td colspan="2"><%=student_name%></td>
<td><b>Mother Name</b></td>
<td> <%=mother_name%></td>
</tr>
<tr>
<td><b>Father's Name:</b></td>
<td colspan="2"><%=father_name%></td>
<td><b>Gender</b></td>
<td colspan="2">M</td>
</tr>
</table></br>
<%
}
catch(Exception e){
e.printStackTrace();
}
session.setAttribute("roll_no", roll_no);
%>
<hr align="center" style="color:lightgrey;">
<h3>One View Result</h3>
<hr align="center" style="color:lightgrey;">
<%
//String roll_no=session.getAttribute("roll_no").toString();
String query1 = "select distinct semester from subject where class_name='"+class_name+"' && branch='"+branch+"'";
try{
Class.forName("com.mysql.jdbc.Driver").newInstance();
Connection con=DriverManager.getConnection(url, username, password);
Statement st=con.createStatement();
ResultSet rs=st.executeQuery(query1);
Statement st1 =con.createStatement();
ResultSet rs1 =null;
Statement st4 =con.createStatement();
ResultSet rs4 =null;
Statement st5 =con.createStatement();
ResultSet rs5 =null;
String semester =null;
String subject_code=null;
String subject_name=null;
String max_marks=null;
String marks_obtained = null;
//String path =null;
while(rs.next()){
semester=rs.getString("semester");
%>
<lable><b>Samester:</b></lable><label><%=semester%></label><lable><b>Total Subjects:</b></lable><label></label></br>
<lable><b>Total Marks:</b></lable><label>900</label><lable><b>Marks Obt:</b></lable><label>500</label></br>
</br>
<table width=100% border=1 cellspacing="0">
<tr>
<td><b>Code</b></td>
<td><b>Name</b></td>
<td><b>Max Marks</b></td>
<td><b>Marks Obtain</b></td>
<td><input type="text" name="" value="view copy"></td>
</tr>
<%
String query2 ="select * from subject where semester='"+semester+"'";
rs1=st1.executeQuery(query2);
while(rs1.next()){
subject_code=rs1.getString("subject_code");
subject_name=rs1.getString("subject_name");
max_marks=rs1.getString("max_marks");
String query3 ="select * from add_marks where roll_no='"+roll_no+"' and subject_code='"+subject_code+"'";
System.out.println(subject_code);
rs4 = st4.executeQuery(query3);
if(rs4.next() && rs4.getString("roll_no").equalsIgnoreCase(roll_no) && rs4.getString("subject_code").equalsIgnoreCase(subject_code)){
// if(rs4.next()){
marks_obtained=rs4.getString("marks_obtained");
path=rs4.getString("path");
}else{
marks_obtained = "Not Updated";
path = "Not Updated";
}
//session.setAttribute("gurufile",path );
a.add(count, path);
//out.println("pathof" +path);
%>
<tr>
<td><%=subject_code%></td>
<td><%=subject_name%></td>
<td><%=max_marks%></td>
<td><%=marks_obtained%></td>
<td><button value="<%= path%>" onclick="myFunction()"><%= path %></button></td>
</tr>
<%
count++;
}
%>
</table>
</br>
</br></br>
<%
}
%>
<%
}
catch(Exception e){
e.printStackTrace();
}
session.setAttribute("roll_no", roll_no);
%>
</body>
</html>
<script>
function myFunction() {
alert(this.value);
<% session.setAttribute("gurufile",path );%>
}
</script>
Blockquote or there is any other technique to get the the value of the button that was clicked
You need to pass the this reference to the function:
<button value="<%= path%>" onclick="myFunction(this)">
This way you get the clicked button as a parameter in the function:
function myFunction(button) {
alert(button.value);
}

jsp- How to copy URL in a javascript function?

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>

How to get variable passed from input box to another page [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 5 years ago.
Improve this question
I am trying to get a variable from hidden INPUT text box to another page. I created a search.asp page, when I search a Form from this page, clicked search button, then view.asp page will open with that specific Form ID. On View.asp page, I created a link to open a new page called view2.asp that keeps the same Form ID. But it didn't work. Can you please help? Thanks.
view.asp code
<%#LANGUAGE="VBSCRIPT" CODEPAGE="1252"%>
<!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=iso-8859-1">
<title>Menus Search</title>
</head>
<body>
<style>
table, td, th {
border: 1px solid #ddd;
}
th, td {
padding: 3px;
}
</style>
</head>
<body>
<!--#include file="openConn.asp" -->
<%
SET objRS = Server.CreateObject("ADODB.Recordset")
SET objRS1 = Server.CreateObject("ADODB.Recordset")
SET objRS2 = Server.CreateObject("ADODB.Recordset")
SET objRS3 = Server.CreateObject("ADODB.Recordset")
If Request.Form("FormSource") = "SubmitForm" Then
For j = 1 to Request.Form("txtCount")-1
strReport = Request.Form("Report[" & j &"]")
strValue = split(strReport,"$")
sMenuID = strValue(0)
sCategoryID = strValue(1)
sStatus = strValue(2)
'response.write strReport & "::" & sMenuID & "::" & sCategoryID & "::" & sStatus & "<br>"
'response.end
sFormID = Request.Form("FormID")
sSQL = "INSERT INTO Report (FormID, MenuID, CategoryID, Status) VALUES " &_
"('" & sFormID & "', '" & sMenuID & "', '" & sCategoryID & "', '" & sStatus & "');"
objConn.Execute(sSQL)
Next
End If
%>
<form action="" method="post" id="newMenu" name="frmReport" onsubmit="return validateForm(this)">
<p>
<%
'''' RR added today
nFormID= Request("FormID") ''Request.Form("SearchObj")
response.write "FormID: " & nFormID & "<br>"
sSQL2 = "SELECT * FROM Form WHERE Formid = " & nFormID
''response.write "SQL:::: " & sSQL2 & "<br>"
objRS2.Open sSQL2, objConn
'response.Write sSQL2
Do Until objRS2.EOF
sFormName = objRS2("Form_Name")
%>
<h2><%= objRS2("Form_Name") %></h2>
<p><a href="#" onclick="openview2.asp();"/>Click me</a></p>
<input type="hidden" id="idFormName" name="FormID" size="40" maxlength="50" value="<%= objRS2("FormID") %>"><br />
<%
objRS2.MoveNext
Loop
objRS2.Close
%>
<p>
<table>
<thead bgcolor="#336666" style="color:#FFFFFF">
<tr>
<td>Trainer Name:</td>
<td>Pass</td>
<td>Fail</td>
<td>NA</td>
<td>Not taken</td>
</tr>
</thead>
<%
currMenu = ""
sSQL = "SELECT MenuID, Menu_Name FROM Menu where MENUID in (SELECT MENUID FROM Category where formid=" & nFormID & ")"
objRS.Open sSQL, objConn
i=1
While Not objRS.EOF
nMenuID = objRS("MenuID")
sMenuName = objRS("Menu_Name")
If currMenu <> sMenuName Then
currMenu = sMenuName
%>
<tr>
<th bgcolor="#CCCCCC"><%= sMenuName %></th>
</tr>
<input type="hidden" name="MenuID" value="<%=nMenuID%>">
<%
End If
sSQL3 = "SELECT Categoryid, Category_Name FROM Category WHERE MenuID = " & nMenuID & " and FormID=" & nFormID
Set objRS3 = Server.CreateObject("ADODB.Recordset")
objRS3.Open sSQL3, objConn
While Not objRS3.EOF
nCategoryID = objRS3("Categoryid")
sCategoryName = objRS3("Category_Name")
%>
<tr>
<td><%= sCategoryName %></td>
<input type="hidden" name="CategoryID" value="<%=nCategoryID%>">
<td align="center"><input type="radio" id ="Report<%=i%>" name="Report[<%=i%>]" value="<%=nMenuID%>$<%=nCategoryID%>$1"></td>
<td align="center"><input type="radio" id ="Report<%=i%>" name="Report[<%=i%>]" value="<%=nMenuID%>$<%=nCategoryID%>$2"></td>
<td align="center"><input type="radio" id ="Report<%=i%>" name="Report[<%=i%>]" value="<%=nMenuID%>$<%=nCategoryID%>$3"></td>
<td align="center"><input type="radio" id ="Report<%=i%>" name="Report[<%=i%>]" value="<%=nMenuID%>$<%=nCategoryID%>$4"></td>
</tr>
<%
objRS3.MoveNext
i = i + 1
Wend
objRS3.Close
objRS.MoveNext
Wend
objRS.Close
%>
</table>
</p>
<p>
<input type="hidden" name="txtCount" value="<%= i %>">
<input type="button" value="Create Menu" onclick="openwin();" />
<input type="hidden" name="FormSource" value="SubmitForm">
<input type="button" value="View2" onclick="openview2();" />
<input type="submit" value="Update">
Go To Search
</p>
</form>
</div>
<script src="https://code.jquery.com/jquery-3.2.1.min.js" type="text/javascript" ></script>
<script type="text/javascript">
function validateForm(daForm) {
nCount = document.frmReport.txtCount.value;
// check all rb radio buttons
for (var i = 1; i < nCount; i++) {
if (! getCheckedRadioValue(daForm["Report"+i])) {
alert ("Please select a value for option " + i)
return false
}
}
// add other checks here...
return true
}
function getCheckedRadioValue(radio) {
for (var i=0; i < radio.length; i++) {
if (radio[i].checked) return radio[i].value
}
return false
}
function openwin()
{
//alert($('#idFormName').val());
//window.location.href = "Create.asp?FormID=" + $('#idFormName').val();
window.open("Create.asp?FormID=" + $('#idFormName').val(), "Create New Menu", "menubar=0,width=700,height=450");
}
function openView2()
{
alert($('#idFormName').val());
window.open("view2.asp?FormID=" + $('#idFormName').val(), "Create New Menu", "menubar=0,width=700,height=450");
}
</script>
</body>
</html>
view2.asp
<%#LANGUAGE="VBSCRIPT" CODEPAGE="1252"%>
<!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=iso-8859-1">
<title>Menus Search</title>
</head>
<body>
<style>
table, td, th {
border: 1px solid #ddd;
}
th, td {
padding: 3px;
}
</style>
</head>
<body>
<!--#include file="openConn.asp" -->
<%
SET objRS = Server.CreateObject("ADODB.Recordset")
SET objRS1 = Server.CreateObject("ADODB.Recordset")
SET objRS2 = Server.CreateObject("ADODB.Recordset")
SET objRS3 = Server.CreateObject("ADODB.Recordset")
If Request("FormID")="" then
iFormID =0
Else
iFormID = Request("FormID") ''Request.Form("FormID")
End If
If Request.Form("FormSource") = "SubmitForm" Then
For j = 1 to Request.Form("txtCount")-1
strReport = Request.Form("Report[" & j &"]")
strValue = split(strReport,"$")
sMenuID = strValue(0)
sCategoryID = strValue(1)
sStatus = strValue(2)
'response.write strReport & "::" & sMenuID & "::" & sCategoryID & "::" & sStatus & "<br>"
'response.end
sFormID = Request.Form("FormID")
sSQL = "INSERT INTO Report (FormID, MenuID, CategoryID, Status) VALUES " &_
"('" & sFormID & "', '" & sMenuID & "', '" & sCategoryID & "', '" & sStatus & "');"
objConn.Execute(sSQL)
Next
End If
%>
<form action="" method="post" id="newMenu" name="frmReport" onsubmit="return validateForm(this)">
<p>
<%
'''' RR added today
nFormID= Request("FormID") ''Request.Form("SearchObj")
response.write "FormID: " & nFormID & "<br>"
sSQL2 = "SELECT * FROM Form WHERE Formid = " & nFormID
''response.write "SQL:::: " & sSQL2 & "<br>"
objRS2.Open sSQL2, objConn
'response.Write sSQL2
Do Until objRS2.EOF
sFormName = objRS2("Form_Name")
%>
<h2><%= objRS2("Form_Name") %></h2>
<input type="hidden" id="idFormName" name="FormID" size="40" maxlength="50" value="<%= objRS2("FormID") %>"><br />
<%
objRS2.MoveNext
Loop
objRS2.Close
%>
<p>
<table>
<thead bgcolor="#336666" style="color:#FFFFFF">
<tr>
<td>Trainer Name:</td>
<td>Pass</td>
<td>Fail</td>
<td>NA</td>
<td>Not taken</td>
</tr>
</thead>
<%
currMenu = ""
sSQL = "SELECT MenuID, Menu_Name FROM Menu where MENUID in (SELECT MENUID FROM Category where formid=" & nFormID & ")"
objRS.Open sSQL, objConn
i=1
While Not objRS.EOF
nMenuID = objRS("MenuID")
sMenuName = objRS("Menu_Name")
If currMenu <> sMenuName Then
currMenu = sMenuName
%>
<tr>
<th bgcolor="#CCCCCC"><%= sMenuName %></th>
</tr>
<input type="hidden" name="MenuID" value="<%=nMenuID%>">
<%
End If
sSQL3 = "SELECT Categoryid, Category_Name FROM Category WHERE MenuID = " & nMenuID & " and FormID=" & nFormID
Set objRS3 = Server.CreateObject("ADODB.Recordset")
objRS3.Open sSQL3, objConn
While Not objRS3.EOF
nCategoryID = objRS3("Categoryid")
sCategoryName = objRS3("Category_Name")
%>
<tr>
<td><%= sCategoryName %></td>
<input type="hidden" name="CategoryID" value="<%=nCategoryID%>">
<td align="center"><input type="radio" id ="Report<%=i%>" name="Report[<%=i%>]" value="<%=nMenuID%>$<%=nCategoryID%>$1"></td>
<td align="center"><input type="radio" id ="Report<%=i%>" name="Report[<%=i%>]" value="<%=nMenuID%>$<%=nCategoryID%>$2"></td>
<td align="center"><input type="radio" id ="Report<%=i%>" name="Report[<%=i%>]" value="<%=nMenuID%>$<%=nCategoryID%>$3"></td>
<td align="center"><input type="radio" id ="Report<%=i%>" name="Report[<%=i%>]" value="<%=nMenuID%>$<%=nCategoryID%>$4"></td>
</tr>
<%
objRS3.MoveNext
i = i + 1
Wend
objRS3.Close
objRS.MoveNext
Wend
objRS.Close
%>
</table>
</p>
<p>
<input type="hidden" name="txtCount" value="<%= i %>">
<input type="button" value="Create Menu" onclick="openwin();" />
<input type="hidden" name="FormSource" value="SubmitForm">
<input type="submit" value="Update">
Go To Search
</p>
</form>
</div>
<script src="https://code.jquery.com/jquery-3.2.1.min.js" type="text/javascript" ></script>
<script type="text/javascript">
function validateForm(daForm) {
nCount = document.frmReport.txtCount.value;
// check all rb radio buttons
for (var i = 1; i < nCount; i++) {
if (! getCheckedRadioValue(daForm["Report"+i])) {
alert ("Please select a value for option " + i)
return false
}
}
// add other checks here...
return true
}
function getCheckedRadioValue(radio) {
for (var i=0; i < radio.length; i++) {
if (radio[i].checked) return radio[i].value
}
return false
}
</script>
</body>
</html>
It's hard to understand what you are trying to do.
But as I could understand, you want to open view2.asp and be able to have a value from view.asp there.
As I can see you open view2.asp with this line
<input type="button" value="View2" onclick="openview2();" />
And you want this hidden input
<input type="hidden" id="idFormName" name="FormID" size="40" maxlength="50" value="<%= objRS2('FormID') %>">
If this is what you are trying to do. Then your naming is wrong with the javascript. You probably copied and forgot to change name.
See here, where you try to open view2.asp
function openwin()
{
window.openView2("view2.asp?FormID=" + $('#idFormName').val(), "Create New Menu", "menubar=0,width=700,height=450");
}
You need to change openwin() to openview2()
EDIT:
I just also saw you have this strange code
<a href="#" onclick="openview2.asp();"/>Click me</a>
Which is a link to it self, because you have href="#". But you also trying to call a javascript function with this onclick="openview2.asp();".
You do not have a function called openview2.asp(). And this is not how it works.
If you are trying to call view2.asp with this link and pass the hidden input idFormName. Then it's better if you just do a correct link and pass the ID in the url.
I must say it's a very bad solution, because there is no security here. But the code you provided shows that you are only after a function and ignoring any security aspect.
So change this
<h2><%= objRS2("Form_Name") %></h2>
<p><a href="#" onclick="openview2.asp();"/>Click me</a></p>
<input type="hidden" id="idFormName" name="FormID" size="40" maxlength="50" value="<%= objRS2("FormID") %>"><br />
for this
<h2><%= objRS2("Form_Name") %></h2>
<p><a href="view2.asp?idFormName=<%= objRS2("FormID") %>" />Click me</a></p>
<input type="hidden" id="idFormName" name="FormID" value="<%= objRS2("FormID") %>"><br />
I'm leaving the hidden there in case you refer to this somewhere else in your code.
Good luck and Have a nice day!

Get data/text from website to HTA [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 5 years ago.
Improve this question
I'm programming a HTA where I can look up data on companies (company name, entity type etc.) from an external website, based on the company registration number.
Since I'm programming in a HTA I'm struggeling to find a solution that is supported. I have tried different scripts in JavaScript, jQuery and VBScript, but none seemed to work in the HTA (some worked in JSFiddle, but not in the HTA).
I have the following URL: https://datacvr.virk.dk/data/visenhed?enhedstype=virksomhed&id=24256790.
(Note the 8 digit code which is the registration number).
I would like to have the following text:
Novo Nordisk A/S
Virksomhedsform: Aktieselskab
Hopefully someone knows how I can get the data which is requested.
Update #2: Below is my full HTA code:
<html>
<HTA:APPLICATION ID="Company Data" APPLICATIONNAME="Company Data" BORDER="thick" CAPTION="yes" ICON=images\icon.ico MAXIMIZEBUTTON="yes" MINIMIZEBUTTON="yes" SHOWINTASKBAR="yes" SINGLEINSTANCE="no" SYSMENU="yes" RESIZE="yes" contextMenu=no></HTA:APPLICATION>
<head>
<title>Regnskabskommetar</title>
<link href="include/stylesheet.css" rel="stylesheet" type="text/css" />
<link rel="SHORTCUT ICON" href="images/icon.ico"/>
<script type="text/javascript" charset="utf-8" src="include/jquery-1.7.min.js"></script>
<script type="text/javascript" charset="utf-8" src="include/underscore-min.js"></script>
<script type="text/javascript" charset="utf-8" src="include/autoNumeric-1.9.18.js"></script>
<script type="text/javascript" charset="utf-8" src="include/addFormat.js"></script>
<script>
function init()
{
var input = document.getElementById("cvr_nr").focus();
}
</script>
<script language="vbscript">
Set fso = CreateObject("Scripting.FileSystemObject")
Set ie = CreateObject("InternetExplorer.Application")
ie.Visible = false
ie.Navigate("https://datacvr.virk.dk/data/visenhed?enhedstype=virksomhed&id=24256790")
Dim dteWait
dteWait = DateAdd("s", 1, Now())
Do Until (Now() > dteWait)
Loop
Set Table = ie.document.getElementsByClassName("table stamdata")
For x = 0 to (Table.length)-1
Data = Data & Table(x).innerText
Next
ie.Quit()
MyFile = "DataLog.txt"
If fso.FileExists(MyFile) Then
fso.DeleteFile(MyFile)
End If
WriteTextFile Data, MyFile, -1
set ws = createObject("wscript.shell")
ws.run MyFile
Sub WriteTextFile(sContent, sPath, lFormat)
' lFormat -2 - System default, -1 - Unicode, 0 - ASCII
With CreateObject("Scripting.FileSystemObject").OpenTextFile(sPath, 8, True, lFormat)
.WriteLine sContent
.Close
End With
End Sub
</script>
<script type="text/javascript">
function reloadpage() {
location.reload();
}
</script>
<script language="vbscript">
resizeto (screen.width)/2,(screen.height - 40) // 40 is the height of task bar
moveto (screen.width)/2,0
</script>
</head>
<body onLoad="init()" language="vbscript">
<table width="100%" border="0" cellpadding="0" cellspacing="0" style='margin-bottom: 5px;' id="sticky_navigation">
<tr>
<td height="40" id="top_bar" style="padding-left: 10px;">Company Data</td>
<td height="40" id="top_bar" align="right">Help</td>
<td width="10" id="top_bar" align="right" style="padding-right: 10px;"><img src="images/footer-logo.png" border="0" title="Opdatér" /></td>
</tr>
</table>
<table border="0" width="98%" cellpadding="0" cellspacing="0" style="margin-left: 10 px">
<tr>
<td width="40%">
<table border="0" width="100%" cellpadding="0" cellspacing="0">
<tr>
<td width="110">
<b>CVR.</b><br>
<input name="cvr_nr" id="cvr_nr" title="CVR - Kan angives med og uden 00 foran" onchange="" style="text-align: left" size="12" type="number" required></td>
</td>
<td valign="top">
<b >Virksomhedsnavn</b><br>
<input style="text-align: left" value="Novo Nordisk A/S" size="50"></input>
<td valign="top">
<b>Virksomhedsform</b><br>
<input style="text-align: left" value="Aktieselskab" size="22" disabled></input>
</tr>
</table>
<div id="include_facility" class="switchcontent1"></div>
<br>
<table border="0" width="100%" cellpadding="0" cellspacing="0">
<tr>
<td style="padding-top:5px">
<hr>
<button id="Scraper" onclick="Scraper()" name="Scraper" tabindex="1">Get company</button>
<hr>
</td
</tr>
</table>
<br>
<div id="content1"></div>
</body>
</html>
Since you don't provide any code, give a try for this vbscript :
Set fso = CreateObject("Scripting.FileSystemObject")
Set ie = CreateObject("InternetExplorer.Application")
ie.Visible = false
ie.Navigate("https://datacvr.virk.dk/data/visenhed?enhedstype=virksomhed&id=24256790")
Do until ie.ReadyState = 4
WScript.Sleep 50
Loop
Set Table = ie.document.getElementsByClassName("table stamdata")
For x = 0 to (Table.length)-1
Data = Data & Table(x).innerText
Next
ie.Quit()
MyFile = "DataLog.txt"
If fso.FileExists(MyFile) Then
fso.DeleteFile(MyFile)
End If
WriteTextFile Data, MyFile, -1
set ws = createObject("wscript.shell")
ws.run MyFile
Sub WriteTextFile(sContent, sPath, lFormat)
' lFormat -2 - System default, -1 - Unicode, 0 - ASCII
With CreateObject("Scripting.FileSystemObject").OpenTextFile(sPath, 8, True, lFormat)
.WriteLine sContent
.Close
End With
End Sub

error with document.getElementById()

I am trying to write a jdo query in which I have to get a set of values based on the category that the user selects on the jsp...my query looks like this
Query query2 = pm.newQuery("select from " + ProductDB.class.getName()+ "where pCategory = " document.getElementById("cname").text);
Now on my jsp page, I have a dynamic drop-down box and in the tag I have given the id tag as "cname". So when I execute the above query I am hoping it will get the category that the user selects.
However I am getting this error:
Syntax error on token "document", delete this token
My select tag looks like this :
<select name = "cname" id="cname">
.
.
.
</select>
What am i missing here?
UPDATE :
I am putting my entire code for the jsp file below :
<%# page contentType="text/html;charset=UTF-8" language="java"%>
<%# page import="java.util.*"%>
<%# page import="javax.jdo.Query"%>
<%# page import="javax.jdo.PersistenceManager"%>
<%# page import="com.google.appengine.api.users.User"%>
<%# page import="com.google.appengine.api.datastore.Key"%>
<%# page import="com.google.appengine.api.users.UserService"%>
<%# page import="com.google.appengine.api.users.UserServiceFactory"%>
<%# page import="java.net.*"%>
<%# page import="javax.servlet.http.HttpServletRequest"%>
<%# page import="com.nerdy.needs.*"%>
<html>
<head>
<title>Product Inventory</title>
<META HTTP-EQUIV="Refresh" CONTENT="450">
<link rel="stylesheet" href="login.css" type="text/css" />
</head>
<h1 align="center">Product Inventory</h1>
<body>
<form>
<table>
<tr>
<td>View</td>
<td><select name="cname" id="cname">
<option value="all">All</option>
<%
PersistenceManager pm = PMF.get().getPersistenceManager();
Query query = pm.newQuery("select cname from "
+ CategoryDB.class.getName());
List<String> categories = new ArrayList<String>();
categories = (List<String>) query.execute();
String[] c = categories.toArray(new String[categories.size()]);
for (int i = 0; i < c.length; i++) {
String s = c[i];
%>
<option value="<%=s%>"><%=s%></option>
<%
}
%>
</select></td>
<td>Products</td>
</tr>
</table>
</form>
<%
if (document.getElementById("cname").value == "all") {
PersistenceManager pm1 = PMF.get().getPersistenceManager();
Query query1 = pm1.newQuery("select * from "
+ ProductDB.class.getName());
List<ProductDB> prods1 = (List<ProductDB>) query1.execute();
if (prods1.isEmpty()) {
%>
<table class="items">
<tr>
<th class="main">Image</th>
<th class="main">Category</th>
<th class="main">Name</th>
<th class="main">Price</th>
<th class="main">Description</th>
</tr>
<tr class="lightBlue">
<td class="actions" colspan=100%>
<p>No items were found.</p>
</td>
</tr>
</table>
<%
} else {
%>
<table class="topics">
<tr>
<th class="main">Image</th>
<th class="main">Category</th>
<th class="main">Name</th>
<th class="main">Price</th>
<th class="main">Description</th>
</tr>
<%
for (ProductDB p : prods1) {
%>
<tr>
<td>
<p><b> <img width="100" height="100"
src="http://localhost:8888/serve?id= <%=p.getProductImage()%>">
</b></p>
</td>
<td>
<p><b><%=p.getProductCategory()%></b></p>
</td>
<td>
<p><b><%=p.getProductName()%></b></p>
</td>
<td>
<p><b><%=p.getProductPrice()%></b></p>
</td>
<td>
<p><b><%=p.getProductDescription()%></b></p>
</td>
</tr>
<%
}
%>
</table>
<%
pm1.close();
}
} else {
PersistenceManager pm2 = PMF.get().getPersistenceManager();
Query query2 = pm.newQuery("select * from "
+ ProductDB.class.getName() + "where pCategory = "
+ document.getElementById("cname").value);
List<ProductDB> prods2 = (List<ProductDB>) query2.execute();
if (prods2.isEmpty()) {
%>
<table class="items">
<tr>
<th class="main">Image</th>
<th class="main">Category</th>
<th class="main">Name</th>
<th class="main">Price</th>
<th class="main">Description</th>
</tr>
<tr class="lightBlue">
<td class="actions" colspan=100%>
<p>No items were found.</p>
</td>
</tr>
</table>
<%
} else {
%>
<table class="topics">
<tr>
<th class="main">Image</th>
<th class="main">Category</th>
<th class="main">Name</th>
<th class="main">Price</th>
<th class="main">Description</th>
</tr>
<%
for (ProductDB p : prods2) {
%>
<tr>
<td>
<p><b> <img width="100" height="100"
src="http://localhost:8888/serve?id= %=p.getProductImage()%>">
</b></p>
</td>
<td>
<p><b><%=p.getProductCategory()%></b></p>
</td>
<td>
<p><b><%=p.getProductName()%></b></p>
</td>
<td>
<p><b><%=p.getProductPrice()%></b></p>
</td>
<td>
<p><b><%=p.getProductDescription()%></b></p>
</td>
</tr>
<%
}
%>
</table>
<%
pm2.close();
}
}
%>
</body>
</html>
I am getting "document cannot be resolved" errors in two places - one at the if statement
if(document.getElementById("cname").value=="all")
and the other at the query statement
Query query2 = pm.newQuery("select * from " + ProductDB.class.getName()+ "where pCategory = " + document.getElementById("cname").value);
Can anyone help me to figure out what is wrong?
Your concrete problem is that you're mixing Java/JSP with JavaScript. You seem to expect that they run in sync and you seem to expect that JavaScript's document object variable is also present in JSP scriptlet code.
This is wrong. Java/JSP is a HTML code generator. It runs in webserver upon a HTTP request and generates HTML/JS code and sends it back to webbrowser as HTTP response. All the webbrowser retrieves is plain HTML/JS code. Rightclick the page in webbrowser and do View Source to see it yourself.
Your concrete functional requirement seems to be that you need to grab the the submitted value of
<select name="cname">
in the Java/JSP side.
You need to get it as a request parameter by HttpServletRequest#getParameter(). So, replace
<%
if (document.getElementById("cname").value == "all") {
// ...
}
%>
by
<%
if ("all".equals(request.getParameter("cname"))) {
// ...
}
%>
That said, writing Java code in JSP files is a poor practice. Work on that as well. Note that this problem is unrelated to JDO.
You forgot the plus mark before the document.getElementById.
The correct code would be
Query query2 = pm.newQuery("select from " + ProductDB.class.getName() + "where pCategory = " + document.getElementById("cname").text);
Also, although that will fix the syntax error, the code still won't work. According to W3C DOM specification, the <select/> element doesn't have the text attribute; you should use the value, or selectedIndex in conjunction with options instead.
Try this way:-
var i = document.getElementById("cname").selectedIndex;
document.getElementById("cname").options[i].text;
OR
document.getElementById("cname").value
UPDATE:
Column names are missing too. It should be either * or specific column names.
Query query2 = pm.newQuery("select * from " + ProductDB.class.getName()+ "where pCategory = " + document.getElementById("cname").value);
As per your error update
your code should be as follows:-
if(document.getElementById("cname").value=="all")
{
<%
PersistenceManager pm1 = PMF.get().getPersistenceManager();
Query query1 = pm1.newQuery("select * from " + ProductDB.class.getName());
List<ProductDB> prods1 = (List<ProductDB>) query1.execute();
%>
}
JSP tags should be declared between tags <% and %> and other html tags should be outside.
As per your Code:
The problem is document.getElementById("cname").value calling inside the JSP tags. That is wrong.
Here either you can pass cname value as query string and get value through the parameter
OR
Assign document.getElementById("cname").value value to JSP variable and process it.

Categories

Resources