displaying table on button click - javascript

I have index.jsp ,from which I am calling transaction.jsp.There is table on transaction.jsp,which i dont want to show on load of transaction.jsp,so i called a javascript method hideData() to hide the table.Now when i click on button showData on transaction.jsp,it will fetch data from database and data will be displayed in a table,which I want to display using javascript showData(),but problem is that,when i click on button,first showData() gets called and then hideData gets called as page is getting loaded again,so i am not able to diaply table on click of button.Then I tried using variable as below,but variable a is not retaining its value when it goes to hideData() after executing showData().My javascript is :
ORIGINAL POST :
<script type="text/javascript">
var a;
function hideData(){
alert("a is"+a);
alert("Inside HideData");
if(a == " ")
{
alert("Inside If");
document.getElementById('dataTable').style.display=" ";
a= " ";
}else{
alert("Inside else");
document.getElementById('dataTable').style.display="none";
a = "none";
}
}
function showData(){
document.getElementById('dataTable').style.display=" ";
a= " ";
}
</script>
Can anyone suggest,how i can achieve this.
Thanks in advance.
EDITED :
index.jsp :
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%# taglib prefix="s" uri="/struts-tags"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>Hello</title>
</head>
<body>
<s:form>
<h2>MI Reports Data</h2>
Transaction Data<br>
</s:form>
</body>
</html
>
transactionData.jsp :
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%# taglib prefix="s" uri="/struts-tags"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<script type="text/javascript">
function showData(){
document.getElementById('dataTable').style.display=" ";
}
</script>
<style type="text/css">
thead.special {
background:url('images/mcf-header-nav.jpg') no-repeat;
border: 1px solid #B0B0B0;
color: #fff;
font-size: 12px;
font-weight: bold;
padding: 3px 12px;
margin-right: 3px 12px;
text-align: left;
}
div.statusbar {
background:url('images/mcf-header-nav.jpg') no-repeat;
color: #fff;
width:100%
font-size: 16px;
font-weight: bold;
padding: 3px 20px;
text-align: left;
}
</style>
<title>Transaction Data</title>
<s:head theme="ajax" debug="true"/>
</head>
<body bgcolor="white">
<s:form validate="true">
<div class='statusbar'>Transactions Info</div>
<table border="true" id="dataTable" style="display:none">
<thead class="special">
<tr>
<td >
DateTime
</td>
<td>
channel
</td>
<td>
Transaction Type
</td>
<td>
Bic
</td>
<td>
Volume
</td>
</tr>
</thead>
<s:iterator value="listTransBean">
<tbody>
<tr>
<td>
<s:property value="dateTime"/><br/>
</td>
<td>
<s:property value="channel"/><br/>
</td>
<td>
<s:property value="transactionType"/><br/>
</td>
<td>
<s:property value="bic"/><br/>
</td>
<td>
<s:property value="volume"/><br/>
</td>
</tr>
</tbody>
</s:iterator>
</table>
<table>
<tr>
<td>
<s:submit id="submitButton" value="Show Chart" align="center" action="displayChartAction"/>
</td>
<td>
<s:submit value="Fetch Data" align="center" action="displayDataAction" onclick="showData();"/>
</td>
</tr>
</table>
</s:form>
</body>
</html>

To show data you have set display style to block..
document.getElementById('dataTable').style.display="block";

<input type="button" onclick="registerFunc()" Value="Register"></button>
<div id="demo" style="display: none">
<h2 class="mainmenu">Testing DB Connection</h2>
<table>
<tr>
<th>ID</th>
<th>Email</th>
<th>Password</th>
#foreach(var row in db.Query(userQuery))
{
<tr>
<td>#row.id</td>
<td>#row.email</td>
<td>#row.pswd</td>
</tr>
}
</table>
</div>
<p>The time is #DateTime.Now</p>
</form>
</div>
<script>
function registerFunc() {document.getElementById('demo').style.display="block";
};
</script>
function registerFunc() {document.getElementById('demo').style.display="block";
div id="demo" style="display: none"

Hi you can try out like this below. Hope this may help you out with this to get out from the challenge you may have obviously.
document.getElementById("name1").style.display= "none";
document.getElementById("name2 ").style.display = "block";
As I have mentioned in the above first thing see the id names I meant over there like name1, name2. Here name 1 will be the data which you not to show when you open a form or anything as per your requirement.name2 is the data you need to show up when you open the form etc..
First thing is you need use inline style use like this : style="display:none"; which one you need not to display by default. later use the condition in javascript wherever you need to override the condition applied using inline CSS property.
For an example:
HTML and CSS:
<table>
<tr>
<td class="text-center colspan-2 "><button onclick="saveEmp()" type="button" class="btn btn-primary btn-lg save" value="Save" id="save1">Save</button></td>
<td class="text-center colspan-2">
<button onclick="update()" type="button" class="btn btn-info btn-lg save" value="Update" id = "update1" style="display:none;" >Update</button></td>
</tr>
</table>
Javascript:
first condition:
document.getElementById("save1").style.display = "block";
document.getElementById("update1").style.display = "none";
second condition I making the second data to display and making the first data not to display:
document.getElementById("save1").style.display = "none";
document.getElementById("update1").style.display = "block";
function save() {
document.getElementById("save1").style.display = "block";
document.getElementById("update1").style.display = "none";
}
function update() {
document.getElementById("save1").style.display = "none";
document.getElementById("update1").style.display = "block";
}
And the HTML:
<table>
<tr>
<td class="text-center colspan-2 "><button onclick="saveEmp()" type="button" class="btn btn-primary btn-lg save" value="Save" id="save1">Save</button></td>
<td class="text-center colspan-2">
<button onclick="update()" type="button" class="btn btn-info btn-lg save" value="Update" id = "update1" style="display:none;" >Update</button></td>
</tr>
</table>

Related

Deleting a row from html table without refreshing the entire page in laravel

This is my route in web.php :
Route::get('/delete_row/id', 'MyController#delete_row');
In controller MyController:
delete row from months table in database.
public function delete_row($id)
{
DB::table('months')->where('id_month', $id)->delete();
return back();
}
In view :
<!DOCTYPE html>
<html>
<head>
<style>
table, th, td {
border: 1px solid black;
}
</style>
</head>
<body>
<h1>The table element</h1>
<table>
<tr>
<th>Month</th>
<th>delete row</th>
</tr>
<tr>
<td>January</td>
<td>
<form method="get" action="/delete_row/1">
<button type="submit"> delete</button>
</form>
</td>
</tr>
<tr>
<td>February</td>
<td>
<form method="get" action="/delete_row/2">
<button type="submit"> delete</button>
</form>
</td>
</tr>
</table>
</body>
</html>
I want to refresh only the row or table, not the whole page.
please how can do that with javascript or anything else?
You can achieve this via AJAX. Here's how.
First of all, your route definition is incorrect since your id is gonna be dynamic. And you should use a post request.
Change your route in web.php to this instead:
Route::post('/delete_row/{id}', 'MyController#delete_row')->name('row.delete');
// This is so your id parameter can be any value at all. I also gave it
// a name so we can access it with the route() method
Now change your controller to give a JSON response instead, this way:
public function delete_row($id)
{
DB::table('months')->where('id_month', $id)->delete();
return response()->json(['success' => 'Deleted successfully']);
Now in you view/blade file, there is absolutely no need to use html forms, since you are gonna be making use of AJAX
Change it to this:
<!DOCTYPE html>
<html>
<head>
<meta name="csrf_token" content="{{ csrf_token() }}">
{{-- Add crsf token so your ajax request will be allowed --}}
<style>
table, th, td {
border: 1px solid black;
}
</style>
</head>
<body>
<h1>The table element</h1>
<table>
<tr>
<th>Month</th>
<th>delete row</th>
</tr>
<tr>
<td>January</td>
<td>
<button data-id="1" class="delete" type="submit"> delete</button>
</td>
</tr>
<tr>
<td>February</td>
<td>
<button data-id="2" class="delete" type="submit"> delete</button>
</td>
</tr>
</table>
<script>
// here is your ajax script
$('.delete-button').click(function() {
var id = $(this).data('id');
var el = this;
var url = "{{ route('row.delete', ':id') }}";
var token= $('meta[name="csrf_token"]').attr('content');
url = url.replace(':id', id);
$.ajax({
url: url,
type: 'POST',
data: {'_method' : 'POST', '_token' :token},
dataType: 'json'
})
.done(function(response){
$(el).closest('tr').css('background','red');
$(el).closest('tr').fadeOut(900,function(){
$(this).remove();
});
})
.fail(function(){
// Do nothing
});
});
</script>
</body>
</html>

java script doesn't get the data from jsp

It's about search and paging functions.
this shows keyWord and keyField well on console when i search keyWord .
<%
String keyWord = (String)request.getParameter("keyWord");
String keyField = (String)request.getParameter("keyField");
System.out.println(keyWord);
System.out.println(keyField);
%>
but this doesn't work.
address appear like this. didn't get data from javascript code.
http://localhost:8090/mvcBoard/list.do?page=2&keyWord=&keyField=
function PageMove(page){
var keyWord = '<%request.getParameter("keyword");%>';
var keyField = '<%request.getParameter("keyField");%>';
console.log(keyWord);
location.href = "list.do?page="+page+"&keyWord=" + keyWord + "&keyField=" + keyField;
}
but it works!
location.href = "list.do?page="+page;
this is list.jsp
<!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>Insert title here</title>
<%
String keyWord = (String)request.getParameter("keyWord");
String keyField = (String)request.getParameter("keyField");
System.out.println(keyWord);
System.out.println(keyField);
%>
<script>
function searchCheck(frm){
//검색
if(frm.keyWord.value ==""){
alert("검색 단어를 입력하세요.");
frm.keyWord.focus();
return;
}
frm.submit();
}
function PageMove(page){
var keyWord = '<%request.getParameter("keyword");%>';
var keyField = '<%request.getParameter("keyField");%>';
console.log(keyWord);
if(keyWord){
location.href = "list.do?page="+page+"&keyWord=" + keyWord + "&keyField=" + keyField;
}
location.href = "list.do?page="+page+"&keyWord=" + keyWord + "&keyField=" + keyField;
}
</script>
</head>
<body>
<table width="800" cellpadding="0" cellspacing="0" border="1">
<tr>
<td>번호</td>
<td>이름</td>
<td>제목</td>
<td>날짜</td>
<td>조히수</td>
</tr>
<c:forEach items="${list}" var="dto">
<tr>
<td>${dto.bId}</td>
<td>${dto.bName}</td>
<td>
<c:forEach begin="1" end="${dto.bIndent}">-</c:forEach>
${dto.bTitle}</td>
<td>${dto.bDate}</td>
<td>${dto.bHit}</td>
</tr>
</c:forEach>
<tr>
<td colspan="5">
<form action="list.do" method="post" name="search">
<select name="keyField">
<option value="bTitle">글 제목</option>
<option value="bContent">글 내용</option>
<option value="bName">작성자</option>
</select>
<input type="text" name="keyWord">
<input type="button" value="검색" onclick="searchCheck(form)">
<input type="hidden" id=keyField value="${paging.keyField}">
<input type="hidden" id=keyWord value="${paging.keyWord}">
</form>
</td>
</tr>
<tr>
<td colspan="5"> 글작성 </td>
</tr>
</table>
<%-- <%=PageAction.pageNumber() %>
--%>
<div class="toolbar-bottom">
<div class="toolbar mt-lg">
<div class="sorter">
<ul class="pagination">
<li>맨앞으로</li>
<li>앞으로</li>
<c:forEach var="i" begin="${paging.startPageNo}" end="${paging.endPageNo}" step="1">
<c:choose>
<c:when test="${i eq paging.pageNo}">
<li class="active">${i}</li>
</c:when>
<c:otherwise>
<li>${i}</li>
</c:otherwise>
</c:choose>
</c:forEach>
<li>뒤로</li>
<li>맨뒤로</li>
</ul>
</div>
</div>
</div>
</body>
</html>
For a start this code looks wrong
<input type="hidden" value="${paging.getkeyField()}">
<input type="hidden" value="${paging.getKeyWord()}">
change to the same format as paging.nextPageNo
<input type="hidden" value="${paging.keyField}">
<input type="hidden" value="${paging.keyWord}">
next you either add an id to this hidden fields (and get the value using Javascript or jquery)
<input type="hidden" id="kf" value="${paging.keyField}">
or use the same parameter passing as paging.nextPageNo to PageMove
javascript:PageMove(${paging.nextPageNo}, ${paging.keyField}); // etc

Dynamic Button call JavaScript Function

I have a script and a Dinamic created Button and event OnClick doesn't work
I need to pass Id and inQuantidade to ValidarEstoqueVenda.htm and JavaScript is the only way i think its possible
page import="usuario.usuario"%>
<%#page import="DAO.DAO"%>
<%#page import="java.util.ArrayList"%>
<%#page import="produto.produto"%>
<%#page import="java.util.List"%>
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<% usuario Usuario = (usuario) session.getAttribute("Usuario");%>
<script>
function clickVender(){
var Id = document.getElementById('Id');
var inQuantidade = document.getElementById('inQuantidade');
if(Id.value != "")
alert("You entered: " + Id.value)
else
alert("Would you please enter some text?")
document.location.href="ValidarEstoqueVenda.htm?Id="+Id.value+"&inQuantidade="+inQuantidade;
}
</script>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<link rel="stylesheet" href="css/materialize.css">
<!-- Include CSS File Here -->
<script src="js/materialize.js"></script>
<title>Estoque Online - Estoque</title>
</head>
<body>
<div class="navbar-fixed">
<nav id="nav_f" class="default_color" role="navigation">
<div class="container">
<div class="nav-wrapper">
Controle de Estoque
<ul class="right hide-on-med-and-down">
<li>Estoque</li>
<%if (Usuario.getTipo() == 2){%>
<li>CadastroEstoque</li>
<li>Cadastro Tipo</li>
<li>Tipo</li>
<li>Usuario</li>
<%}%>
<li>Sair</li>
</ul>
<ul id="nav-mobile" class="side-nav">
<li>Estoque</li>
<%if (Usuario.getTipo() == 2){%>
<li>Cadastro Tipo</li>
<ul id='dropdown2' class='dropdown-content'>
<li>Usuario</li>
</ul>
<%}%>
<li>Sair</li>
</ul>
<i class="mdi-navigation-menu"></i>
</div>
</div>
</nav>
</div>
<form action="ValidarEstoque" method="get">
<table class="striped responsive-table black-text teal darken-1">
<thead>
<tr>
<th data-field="id">Id</th>
<th data-field="nome">Descricao</th>
<th data-field="email">Quantidade</th>
<th data-field="Alterar">Alterar</th>
<th data-field="Excluir">Exlcuir</th>
</tr>
</thead>
<tbody>
<tr>
<% List<produto> produtos = new ArrayList<produto>();
DAO dao = new DAO();
produtos = dao.listarEstoque();%>
<%for(produto produto : produtos){%>
<td><%=produto.getId()%></td>
<td><%=produto.getDescricao()%></td>
<td><input type="text" id="inQuantidade" name="inQuantidade" value="<%=produto.getQuantidade()%>"></td>
<% if(Usuario.getId() != 0){%>
<td>Alterar</td>
<td>Excluir</td>
<td><a class="btn waves-effect waves-light col s12" onclick="clickVender()">Vender</a></td>
<%
}
%>
</tr>
<%
}
%>
</tbody>
</table>
</form>
</body>
</html>
The last tag have the onCLick function.
Please Help me
Your code don't have id named 'Id'.
and you should don't use inline event handler.
You should refer to my code.
[HTML]
<td>
<input type="text" id="Id" name="MYID" value="my dummy Id">
</td>
<td>
<input type="text" id="inQuantidade" name="inQuantidade" value="getQuantidade">
</td>
<td><a class="govender">Vender</a></td>
[JavaScript]
function clickVender() {
var id = document.getElementById("Id");
var inQuantidade = document.getElementById("inQuantidade");
alert(id.value + ":" + inQuantidade.value);
}
document.querySelector(".govender").onclick = clickVender;
//or you can use addEventListener.
https://jsfiddle.net/nigayo/n81hd5f3/
[# additional explanation]
you can see error messages on console tab of Chrome developer tools.
https://developer.chrome.com/devtools/docs/console

JavaScript White Space Validation not working

I have written JSP code and I need to check white space validation, But it is not working can someone tell me the reason. While clicking submit button it must validate for white space and characters.
JSP Code
<%--
Document : LapsePeriodicFeedBack
Created on : Dec 7, 2012, 2:50:28 PM
Author : Admin
--%>
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<%# page import="java.util.*" %>
<%#page import="PeriodicFeedBack.PeriodicType"%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>LapsePeriodicList</title>
<script>
function validateForm(){
var selectindex=document.forms["lapse"]["periodmenu"].selectedIndex;
var whitespace = new RegExp("^\w*$");
var x= document.forms["lapse"]["lapsedays"].value;
var textlength=document.forms["lapse"]["lapsedays"].length;
if(x==""){
alert("Days Cant Be Empty");
return false;
}
if(x==whitespace){
alert("White Spaces are not Allowed");
return false;
}
if(selectindex==0){
alert("Please select Days from menu");
}
}
if(x=="/\\s"){
alert('Sorry, you are not allowed to enter any spaces');
x.value=x.value.replace(/\s/g,'');
}
</script>
</head>
<body>
<form method="post" name="lapse" onsubmit="return validateForm()">
<table width="500px" border="1" align="center" style='border-collapse: collapse;font: 13px Arial, Helvetica, sans-serif;' bordercolor='#000000'>
<tr style="color:'#ffffff';background-color:#CA1619;background-repeat:repeat-x;font: 13px Arial, Helvetica, sans-serif;">
<td colspan="4" align="center">
<font color="#ffffff" > <b>Periodic Feedback List</b></font></td></tr>
<tr>
<td align="center">
Periodic Feedback Days</td>
<td align="center">
<select id="periodmenu">
<option> Select</option>
<%
PeriodicType p = new PeriodicType();
ArrayList periodicList = p.getPeriodicType();
for (int i = 0; i < periodicList.size(); i++) {%>
<option>
<% out.println(periodicList.get(i));
}%>
</option>
</select></td>
</tr>
<tr>
<td align="center">
Lapse Days </td>
<td align="center">
<p>
<input name="lapsedays" type="text" id="lapsedays" onkeyup="nospaces(this)"/></p>
<input name="Submit" type="submit" value="Submit" /></td>
</tr>
</table>
</form>
<p>
</p>
</body>
</html>
You can't use x==whitespace to check x against a regular expression. Use the following:
whitespace.test(x);
That'll return true or false.
In addition, you should not use new RegExp for this, you should instead use the literal operators:
var whitespace = /^\w*$/;

Why firefox can't get elements node as well as IE?

This is a script for selecting a method for pay. It works in IE but when I run it in FF it stops with this error:
Error: document.getElementById("tdeposit").childNodes[0].childNodes[0] is undefined.
You can paste this code to a html file and see the problem:
I have removed some website addresses because of privacy issues , the image links changed
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Test</title>
<style>
#tdeposit {
width:550px;
margin:10px auto;
font-family:Arial;
font-size:13px;
font-weight:bold;
letter-spacing:1px;
color:#444;
text-align:center;
}
</style>
</head>
<body>
<script>
function methodis(method){
if(method=='wm'){
document.getElementById('tdeposit').childNodes[0].childNodes[0].childNodes[1].style.visibility='visible';
document.getElementById('tdeposit').childNodes[0].childNodes[0].childNodes[2].style.visibility='visible';
document.getElementById('tdeposit').childNodes[0].childNodes[0].childNodes[3].style.visibility='visible';
document.getElementById('tdeposit').childNodes[0].childNodes[0].childNodes[4].style.visibility='visible';
document.getElementById('tdeposit').childNodes[0].childNodes[1].childNodes[1].style.visibility='hidden';
document.getElementById('tdeposit').childNodes[0].childNodes[1].childNodes[2].style.visibility='hidden';
document.getElementById('tdeposit').childNodes[0].childNodes[1].childNodes[3].style.visibility='hidden';
document.getElementById('tdeposit').childNodes[0].childNodes[1].childNodes[4].style.visibility='hidden';
document.deposit.method[0].checked=true;
}
if(method=='lr'){
document.getElementById('tdeposit').childNodes[0].childNodes[0].childNodes[1].style.visibility='hidden';
document.getElementById('tdeposit').childNodes[0].childNodes[0].childNodes[2].style.visibility='hidden';
document.getElementById('tdeposit').childNodes[0].childNodes[0].childNodes[3].style.visibility='hidden';
document.getElementById('tdeposit').childNodes[0].childNodes[0].childNodes[4].style.visibility='hidden';
document.getElementById('tdeposit').childNodes[0].childNodes[1].childNodes[1].style.visibility='visible';
document.getElementById('tdeposit').childNodes[0].childNodes[1].childNodes[2].style.visibility='visible';
document.getElementById('tdeposit').childNodes[0].childNodes[1].childNodes[3].style.visibility='visible';
document.getElementById('tdeposit').childNodes[0].childNodes[1].childNodes[4].style.visibility='visible';
document.deposit.method[1].checked=true;
}
return 0;
}
function calculate(ob,per){
if(ob.value.length<8){
document.getElementById(ob.name).innerHTML = '$ '+(per*ob.value).toFixed(2);
}else{
document.getElementById(ob.name).innerHTML = '$ 0';
}
}
</script>
<form name='deposit' action='deposit.php'>
<table id='tdeposit' >
<tbody>
<tr>
<td><input type='radio' name='method' value='wm' style='width:20px; height:50px' />
<img src='http://www.xxxxxxxxx.com/images/webmoney.png' onclick='methodis("wm");' /></td>
<td style='width:110px; visibility: hidden;'> $
<input style='margin:5px; height:20px; width:50px; text-align:center' type='text' name='wmht' onkeyup='calculate(this,0.98);' />
WM</td>
<td style='width:25px; visibility: hidden;'><img src='http://www.xxxxxxxxx.com/images/convert.gif' /></td>
<td style='width:100px; visibility: hidden;' ><span id='wmht' style='color:#060'>$ 0.0</span> HT</td>
<td style='width:100px; visibility: hidden;'><input type='submit' value=' Deposit ' />
</tr>
<tr style='border-top:solid 1px #999'>
<td><input type='radio' name='method' value='lr' style='width:20px; height:50px' />
<img src='http://www.xxxxxxxxx.com/images/libertyreserve.png' onclick='methodis("lr");'/></td>
<td style='visibility: hidden;'> $
<input style='margin:5px; height:20px; width:50px; text-align:center' type='text' name='lrht' onkeyup='calculate(this,0.95);' />
LR</td>
<td style='visibility: hidden;'><img src='http://www.xxxxxxxxx.com/images/convert.gif' /></td>
<td style='visibility: hidden;'><span id='lrht' style='color:#060'>$ 0.0 </span> HT</td>
<td style='visibility: hidden;'><input type='submit' value=' Deposit ' />
</tr>
</tbody>
</table>
</form>
</body>
</html>
document.getElementById('tdeposit').childNodes[0] references the TextNode for whitespace following the <table> tag. Perhaps IE is disregarding it, but not other browsers. Use the children getter instead of childNodes.

Categories

Resources