Onclick function button inside a javascript - java

I want to direct the button to another page
function showInput() {
document.getElementById("demo").innerHTML = '<input type="submit"
onclick="location.href = "addnewcustomer.php";" id ="newcust"
class="btnRegister" value = "New Customer">';
}
I want when i click the New Customer button, it will redirect to addnewcustomer.php but when i run the code, nothing happened.
There are no errors. Just the button didn't function the way i want it to

You have to escape quotes in element. Try following code
function showInput() {
document.getElementById("demo").innerHTML = '<input type="submit" onclick="location.href = \'addnewcustomer.php\';" id ="newcust" class="btnRegister" value = "New Customer">';
}
<a onclick="showInput()" >Add New Buton</a>
<div id="demo"></div>

You can use following code to redirect page.
function showInput() {
document.getElementById("demo").innerHTML = '<input type="submit" id ="newcust" class="btnRegister" value = "New Customer" />';
}
document.getElementById("newcust").onclick = function () {
location.href = "addnewcustomer.php";
}
<div id="demo"></div>
<a onclick="showInput()" >Click To Get Button</a>

Try this
function showInput() {
document.getElementById("demo").innerHTML = '<input type="submit" onclick="location.href = \'https://www.youtube.com/\';" class="btnRegister" value = "New Customer">';
}
showInput()
<p id="demo">click</p>

It is because you didn’t close your input tag
Try this...
function showInput() {
document.getElementById("demo").innerHTML = '<input type="submit"
onclick="location.href = "addnewcustomer.php";" id ="newcust"
class="btnRegister" value = "New Customer"/>';
}
If you don’t close it the button will not work.

function showInput() {
document.getElementById("demo").innerHTML = '<input type="submit" onclick="location.href = "yourpage.php";" id ="newcust" class="btnRegister" value = "New Customer">';
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a onclick="showInput()" >Click To Get Button</a>
<p id="demo"></p>
Right Click And inspect Button.

Try the code below, the inner html text is missing with escape string. Call window.onload to trigger your method and display your button. HTH.
<head>
<script type="text/javascript">
function showInput() {
document.getElementById("demo").innerHTML = '<input type="submit" onclick="location.href = \'addnewcustomer.php\';" id ="newcust" class="btnRegister" value = "New Customer">';
}
window.onload = showInput;
</script>
</head>
<body>
<p id="demo"></p>
</body>

Related

How can I make JQuery parse information and evaluate everytime it clicks

I made this coding myself recently but just simply doesn't seem to work. This code is supposed to get the value of the name I've submitted and using ajax, if the name equals, "James", the code is supposed to return "Hello James" and just "Hello" for other names inputted. The response when the input is not "James" sort of works, but it only works some of the time and I also hope to fix that.
Tried reviewing some of my codes
<fieldset>
<form style="padding:15px;">
<label for=name>Enter Name:</label>
<input type="text" name="name" id="name">
<br>
<input type="submit" style="margin: 15px;" value="SUBMIT" id="submit">
</form>
</fieldset>
<div id="result"></div>
$(document).ready(function() {
$("#submit").click(function() {
var name = $("#name").val();
var send = {
name: "name"
};
$.ajax({
type: "POST",
url: "process2.jsp",
data: send,
success: function(data) {
$("#result").html(data);
}
})
});
});
<% if(request.getParameter("name").equals("James"))
{
<% out.println("Hello James"); %>
} else { %>
<% out.println("Hello"); %>
<% } %>

How to make HTML Button perform action in Java?

Basically I'm creating an upvote/downvote system, Now I've created two buttons in HTML :
<button type="button" name="upvote"></button>
<br>
<input type="number" th:value = "${commentValue}" disabled>
<br>
<button type="button" name="downvote"></button>
First button with name attribute - "upvote" and second with "downvote" , Now I want to catch a click on button and change the commentValue accordingly, If user clicks upvote, comment value must incriment and on downvote it must decrement
I found some topics that said to implement ActionListener, Create JButton objects and etc. but isn't there any simpler way ?
This is my code right now, The buttons do nothing. :
Controller :
private int numberValue = 0;
#GetMapping("/check")
public String nuberCheck(Model model){
model.addAttribute("commentValue", numberValue);
return "numberCheck";
}
#PostMapping("/check")
public String upvote(Model model, #RequestParam String action){
if (action == "upvote"){
numberValue++;
model.addAttribute("commentValue", numberValue);
}else if (action == "downvote"){
numberValue --;
model.addAttribute("commentValue", numberValue);
}
return "numberCheck";
}
numberCheck :
<form action="#" th:action="#{/check}" method="post">
<button type="button" name="action" th:value="upvote" th:text = "upvote"></button>
<br>
<input type="number" th:value = "${commentValue}" disabled>
<br>
<button type="button" name="action" th:value = "dowvnote" th:text = "dowvnote"></button>
</form>
FIXED
Change button types to "submit" and then in controller :
#PostMapping("/check")
public String check(Model model,#RequestParam String action) {
System.out.println(action);
if (action.equals("upvote")) {
numberValue++;
model.addAttribute("numberValue", numberValue);
}
if (action.equals("dowvnote")) {
numberValue--;
model.addAttribute("numberValue", numberValue);
}
return "numberCheck";
}
#RequestParam String action "action" is the name attribute of button and "save" and "cancel" are the "value" attributes :) hope it helps
Sample:
HTML:
<form action="#" data-th-action="#{/action}" data-th-object="${model}" method="post">
<button type="submit" name="upvote"></button>
<button type="submit" name="downvote"></button>
</form>
Java:
#RequestMapping(value="/action", method=RequestMethod.POST)
public ModelAndView onClickAction() {}
Use the following and implement in your code
$(document).ready(function(){
$("#up").click(function(){
var up = $.post("/upvote", {changeBy: 1}, function(dataBack){
$("#upvote").text(dataBack);
});
});
$("#down").click(function(){
var down = $.post("/downvote", {changeBy: 1},
function(dataBack){
$("#downvote").text(dataBack);
});
});
});
You can use jquery for that. first add jquery library in your html page and write function like below inside script tag
function upVote(){
var counter= $('.comment').val();
counter++;
$('.coment').val(counter);
}
function downVote(){
var counter= $('.comment').val();
counter--;
$('.coment').val(counter);
}
<button type="submit" name="upvote" th:onclick="'upVote();'"></button>
<br>
<input type="number" class="comment"th:value = "${commentValue}" disabled>
<br>
<button type="submit" name="downvote" th:onclick="'upVote();'"></button>
There is one best way to solve this. When you click button trigger one event and at that event increase or decrease value. Use that value in an thymeleaf and pass it to the controller.

Which dynamic created button was pressed in Servlet

I have dynamically created buttons.
<form action="/" method="post">
<table cellpadding="4">
<%
List<Room> rl = (List<Room>) request.getAttribute("roomList");
if(rl != null) {
for (Room r : rl) {
String name = r.getName();
%>
<tr>
<td><%=name%></td>
<td><input type="submit" value="Add a Booking" name=<%=name%> /></td>
</tr>
<%
}
}
%>
</table>
I know which button was clicked with the following code;
String addButton = req.getParameter("addButton");
However, in this situation, I am not able to know the name of the button. Because the name of the button could be anything. How could I know which button was pressed? Thanks in advance!
You can possibly have at least two solutions:
1. Solution in Java code on the server side
in JSP each of the submit button will be named with the submit_ prefix
<input type="submit" value="Add a Booking" name=<%="submit_"+name%> />
When request is send to the server you will loop parameters and search for one with this prefix, saving its value to submit attribute:
private void setSubmitValue(HttpServletRequest request) {
String SUBMIT_PREFIX = "submit_";
for (Enumeration e = request.getParameterNames(); e.hasMoreElements();) {
String key = (String) e.nextElement();
if (key.startsWith(SUBMIT_PREFIX)) {
String value = key.substring(SUBMIT_PREFIX.length());
request.setAttribute("submit", value);
break;
}
}
}
2. Solution with JavaScript on the client (browser) side
Introduce in the form new hidden widget that will hold the number of room clicked. When button is clicked its value is stored in that widget.
When request is send, on the server side you just read the value of that parameter (widget name).
Below is an example: room-nr will have value of clicked button
var form = document.forms['add-room'];
$(form).on('click', 'button', function(e) {
e.preventDefault();
var name = $(this).attr('name')
form['room-nr'].value = name.replace(/\D+/, '');
console.log(form['room-nr'].value);
//form['add-booking'].click();
});
.hide {
display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<form name="add-room" action='.'">
<input type="hidden" name="room-nr" value="" />
<table cellpadding="4">
<tr>
<td>room1</td>
<td>
<button type="button" name="room-1">Add</button>
</td>
</tr>
<tr>
<td>room2</td>
<td>
<button type="button" name="room-2">Add</button>
</td>
</tr>
<tr>
<td>room3</td>
<td>
<button type="button" name="room3">Add</button>
</td>
</tr>
</table>
<input type="submit" value="Add a Booking" name="add-booking" class="hide" />
</form>
You need to do the following:
<input type="submit" value="<%name%>" name="Add Booking"
/>

how can i set and display another filed in local database?

i am trying the example todo app,i download that example in ionic and i tried that it is working, and i trued to add another filed inside newTask.html and add in local database as same as previous value,but it is not working can you please help me how can i add another filed in the local database and get results in list html file....
NewTask.html
------------
<div class="modal" ng-controller="newTaskCtrl">
<ion-header-bar class="bar-stable">
<h1 class="title">Add New Task</h1>
<button class="button button-clear button-positive" ng-click="closeNewTask()">Cancel</button>
</ion-header-bar>
<ion-content>
<form ng-submit="createTask(task)">
<div class="list">
<!--label class="item item-input">
<input type="text" placeholder="Title What do you need to do?" ng-model="task.title">
</label-->
<label class="item item-input item-stacked-label">
<span class="input-label">Title</span>
<input type="text" placeholder="What do you need to do?" ng-model="task.title">
<span class="input-label">Lasr Name</span>
<input type="text" placeholder="Firstname?" ng-model="task.firstname">
</label>
<!--div class="row">
<label class="col">
<input type="" ng-model="time">
</label>
<label class="col">
<input type="text" placeholder="End?" >
</label>
</div-->
</div>
<div class="padding">
<button type="submit" class="button button-block button-positive">Create Task</button>
</div>
</form>
</ion-content>
</div>
NewTaskCtrl.js
-------------------
todoApp.controller('newTaskCtrl', function($scope, $ionicModal, $ionicPopup, SQLService) {
// Called when the form is submitted
$scope.createTask = function(task) {
SQLService.set(task.title,task.firstname);
$scope.loadTask();
$scope.taskModal.hide();
task.title = "";
task.firstname = "";
};
SQLService.js
------------------
todoApp.factory("SQLService", function ($q) {
var db;
var task='';
var deltask;
function createDB() {
try {
db = window.openDatabase("todoDB", "1.0", "ToDoApp", 10*1024*1024);
db.transaction(function(tx){
tx.executeSql("CREATE TABLE IF NOT EXISTS tasks (id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT, title VARCHAR(100), firstname VARCHAR(100) )",[]);
});
} catch (err) {
alert("Error processing SQL: " + err);
}
console.log('database created');
}
function setTasks(title,firstname){
return promisedQuery("INSERT INTO tasks(title,firstname) VALUES ('" + title + "','" + firstname + "')", defaultResultHandler, defaultErrorHandler);
}
function getTasks(){
return promisedQuery('SELECT * FROM tasks', defaultResultHandler, defaultErrorHandler);
}
function defaultResultHandler(deferred) {
return function(tx, results) {
var len = results.rows.length;
var output_results = [];
for (var i=0; i<len; i++){
var t = {'id':results.rows.item(i).id,'title':results.rows.item(i).title,'firstname':results.rows.item(i).firstname};
output_results.push(t);
}
deferred.resolve(output_results);
}
}
function defaultErrorHandler(deferred) {
return function(tx, results) {
var len = 0;
var output_results = '';
deferred.resolve(output_results);
}
}
function promisedQuery(query, successCB, errorCB) {
var deferred = $q.defer();
db.transaction(function(tx){
tx.executeSql(query, [], successCB(deferred), errorCB(deferred));
}, errorCB);
return deferred.promise;
}
return {
setup: function() {
return createDB();
},
set: function(title,firstname) {
return setTasks(title,firstname);
},
all: function() {
return getTasks();
}
}
});
PLease see the SQL Service and help me,is it correct what i add the filed name in "setTasks function.."
Ok, so you had tried the example that you had downloaded, now you have added another field in NewTask.html. But the new field that you added is not getting added to the table right??
Did you try to change the version of the DB opened??
db = window.openDatabase("todoDB", "1.0", "ToDoApp", 10*1024*1024);
to
db = window.openDatabase("todoDB", "2.0", "ToDoApp", 10*1024*1024);

Adding Item in list dynamically on Button click .Help Please

So i have created div with static data from controller and model.Now when i click on ADD button a new item should be added to list and div should automatically be dispalyed to page. Hope i am clear :)
Please guide me how do i achieve it?? Thanks
It should work before but I guess you changed the html , Okay Try This one
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<script>
var i=y=0;
var newarr = new Array();
var divContent = '';
#foreach (var job in Model)
{
divContent = '<div class="panel panel-default" id="panel2"><div class="panel-heading-new"><h4 class="panel-title" id="newpanel1"><a data-toggle="collapse" data-target="#collapseTwo" href="#collapseTwo">';
divContent += '#Html.DisplayFor(modelItem => job.Header, new { job.Id })';
divContent += '</a></h4></div><div id="collapseTwo" class="panel-collapse collapse in"><div class="panel-body"><p class="lead justified">';
divContent += 'Qualifications and Skills:';
divContent += '</p><ul class="fa-ul">';
divContent += '<li><i class="fa-li fa fa-hand-o-right pad-icon"></i><span class="lead justified">#Html.DisplayFor(modelItem => job.Content, new { job.Id })</span></li>';
divContent += '</ul><br /></div></div></div>';
newarr[i] = $(divContent);
i = i +1;
}
$(document).ready(function(){
$("a#add").click(function(){
if (y<i) {
var content = newarr[y];
$('#maincontainer').append(content);
y++;
} else {
alert('No other Job!');
}
return false;
});
});
</script>
ADD
<div class="container">
<div class="col-lg-12" id="maincontainer">
</div>
</div>
<script>
</script>
#model IEnumerable<Nexcentus.UI.Models.JobOpening>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<script>
var i=0;
var y=0;
var newarr = new Array();
</script>
<script>
#foreach (var job in Model)
{
newarr[i] = $( "<li><i class=\"fa-li fa fa-hand-o-right pad-icon\"></i><span class=\"lead justified\">#Html.DisplayFor(modelItem => job.Content, new { job.Id })</span></li>");
i = i +1;
}
</script>
<div class="container">
ADD
<div class="col-lg-12">
#foreach (var job in Model)
{
<div class="panel panel-default" id="panel2">
<div class="panel-heading-new">
<h4 class="panel-title-new" id="newpanel1">
<a data-toggle="collapse" data-target="#collapseTwo" href="#collapseTwo">
#Html.DisplayFor(modelItem => job.Header, new { job.Id })
</a>
</h4>
</div>
<div id="collapseTwo" class="panel-collapse collapse in">
<div class="panel-body">
<p class="lead justified">
Qualifications and Skills:
</p>
<ul class="fa-ul">
<li><i class="fa-li fa fa-hand-o-right pad-icon"></i><span class="lead justified">#Html.DisplayFor(modelItem => job.Content, new { job.Id })</span></li>
</ul>
<br />
</div>
</div>
</div>
<script>
$("a#add").click(function(){
if (y<i) {
var content = newarr[y];
$('ul.fa-ul').append(content);
y = y+1;
}
return false;
});
</script>
Try this one

Categories