I'm asking when I reset Jquery form - javascript

Jquery form.reset when clicking the reset button event,
The readonly part is also initialized and the value value disappears.
When data is loaded, the name and memo values ​​are set,
and the memo values ​​remain the same even when the reset button event occurs.
How can I keep data when reset event occurs?
// reset button event
$("#reset").on("click", function(){
var form = document.getElementById("SettingForm");
form.reset();
});
// ajax data load
success : function(data) {
$("#name").val(data.name);
$("#memo").text(data.memo);
}
<form id="SettingForm" action="" method="POST">
<table cellpadding="0" cellspacing="0" class="panelW">
<tr>
<th class="w35p">name</th>
<td><input id="name" name="name" type="text" value="" readonly/></td>
</tr>
<tr>
<th class="w35p"><c th:text="#{configure.memo}">memo</c></th>
<td><textarea id="memo" name="memo" value="" readonly></textarea>
</td>
</tr>
</table>
</form>

This is a case where it's important to distinguish between attributes and properties.
The value property is the current value of the input, which will be submitted in the form.
The value attribute is the input's initial default value. It's copied into the property when it's initially rendered, and again when form.reset() is used.
So if you want to update the default value, you need to assign the attribute; .val() just assigns the property.
Similarly, for a textarea, the text is used as the default when the form is reset.
success : function(data) {
$("#name").val(data.name).attr(data.name);
$("#memo").val(data.memo).text(data.memo);
}
const data = {
name: "Default name",
memo: "Default memo"
};
$("#name").val(data.name).attr("value", data.name);
$("#memo").val(data.memo).text(data.memo);
$("#reset").on("click", function(){
var form = document.getElementById("SettingForm");
form.reset();
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form id="SettingForm" action="" method="POST">
<table cellpadding="0" cellspacing="0" class="panelW">
<tr>
<th class="w35p">name</th>
<td><input id="name" name="name" type="text" value=""/></td>
</tr>
<tr>
<th class="w35p">
<c th:text="#{configure.memo}">memo</c>
</th>
<td><textarea id="memo" name="memo" value=""></textarea>
</td>
</tr>
</table>
</form>
<button id="reset">Reset</button>

Related

Table with two buttons. One jQuery-ajax doesn't replace <tbody> of <table>, but instead redirects browser to ajax url

EDIT: I originally simplified my code, hoping to isolate my problem, but I see I need to show the unsimplified code to discover my problem; so I'm replacing the HTML and JavaScript with the "full version", and have edited my description to include new information.
I have a table with two Buttons.
One button works fine: it triggers a jQuery overlay form so the user can enter data for a new row. AJAX then removes the "old" < tbody > and replaces it with a new < tbody > (with the new row added). That works fine. --critically, it also stores the new row into a database.
The other button is responsible for removing rows that have been checked by the user. jQuery AJAX does remove the selected rows from the database, but instead of replacing the "old" < tbody > with the new (now smaller) one, it loads the AJAX url into the browser, which shows the raw new set of rows that were intended to be put into the < tbody >. Using the back button and F5-ing shows that the rows were indeed removed.
I don't know how to 'blend' these buttons into one table.
Here is the jQuery:
// opens a pop-up form as an overlay (id: #box_form) that has its own buttons
$('#addy').click(function(e){
//e.preventDefault();
$('#box_form').dialog('open');
});
$( "#datepicker" ).datepicker(
{altFormat: "yy-mm-dd"}
);
$('#box_form').dialog({
autoOpen: false,
height: 340,
width: 400,
modal: true,
buttons: [
{
text: "Cancel",
click: function() {
$(this).dialog("close");
}
},
{
text: "Submit",
click: function() {
var symbol = $("#symbol").val();
var quant = $("#quant").val();
var price = $("#price").val();
var datepicker = $("#datepicker").val();
var fee = $("#fee").val();
var account = $("#account").val();
var owner = $("#owner").val();
// Returns successful data submission message when the entered information is stored in database.
var dataString = 'symbol='+ symbol + '&quant='+ quant + '&price='+ price + '&datepicker='+ datepicker + '&fee='+ fee + '&account='+ account + '&owner='+ owner;
if(symbol==''||quant==''||price==''||datepicker==''||fee==''||account=='')
{
alert("Please Fill All Fields");
}
else
{
$.ajax({
type: "POST",
url: "addPurch.php",
data: dataString,
cache: false,
success: function(result){
//document.getElementById("stocktablebody").innerHTML = result;
$("#stockstable tbody").html(result);
}
});
//close this little input form overlay
$( this ).dialog( "close" );
}
return false;
}
}
]
});
$('#selectAll').click(function(event){
$(this).closest('table').find('td input:checkbox').prop('checked', this.checked);
});
$('#removie').submit(function(event){
event.preventDefault();
var remove = $("#remove[]").val();
var owner = $("#owner").val();
var dataString = 'remove='+ remove + '&owner='+ owner;
//var url = "removePurch.php"; //$(this).attr('action');// this attribute's action (specified in <form> tag)
$.ajax({
type: "POST",
url: "removePurch.php",
data: dataString,
cache: false,
success: function(result){
//document.getElementById("stocktablebody").innerHTML = result;
$("#stockstable tbody").html(result);
}
});
return false;
});
Here is the HTML:
(First big div is for the Add button's jQuery pop-up; Second big block is the actual table.)
<!-- Pop-up form hidden by JavaScript until button is clicked -->
<div id="box_form" title="Add a purchase">
<form id="addsymbol" action="addPurch.php" method="POST"
name="addstock" enctype="multipart/form-data">
<input type="hidden" name="owner" id="owner" value="me" />
<table class="popuptable">
<thead>
<tr>
<td class="right"><label for="symbol">Symbol:</label></td>
<td><input type="text" name="symbol" id="symbol"></td>
</tr>
<tr>
<td class="right">
<!-- for="..." Specifies which form element a label is bound to -->
<label for="quant">Quantity:</label>
</td>
<td><input type="text" name="quant" id="quant"></td>
</tr>
<tr>
<td class="right"><label for="price">Price for each: </label>
</td>
<td><input type="text" name="price" id="price"></td>
</tr>
<tr>
<td class="right"><label for="fee">Fee: </label></td>
<td><input type="text" name="fee" id="fee"></td>
</tr>
<tr>
<td class="right"><label for="datepicker">Date
Purchased: </label></td>
<td><input type="text" name="datepicker" id="datepicker">
<!-- had real trouble getting data to POST, just made all names,ids === and it worked -->
</td>
</tr>
<tr>
<td class="right"><label for="account">Which account:
</label></td>
<td><select name="account" id="account">
<option value="note">must fix fee functionality</option>
<option value="FidelityIndividual">Fidelity Individual</option>
<option value="FidelitySEP">Fidelity SEP</option>
<option value="FidelityRoth">Fidelity Roth</option>
<option value="ScottradeIRA">Scottrade IRA</option>
</select></td>
</tr>
</thead>
</table>
</form>
</div>
<!-- Table with two buttons (Add-a-row and Remove-a-row), and a checkbox for each row, and a checkbox to "check all rows" -->
<table id="stockstable" class="center">
<thead>
<tr>
<th colspan="2">
<!-- this just triggers form to come up. Form has its own buttons -->
<input type="submit" id="addy" value="Add a stock purchase">
</th>
<th colspan="3">Activity Today</th>
<th colspan="2">Change Since Purchase</th>
<th colspan="3">Cost Basis</th>
<th colspan="3">Purchas Details</th>
<form action="removePurch.php" method="post"
enctype="multipart/form-data">
<input type="hidden" name="owner" id="owner" value="me" />
<th><button id="removie">Remove</button></th>
</tr>
<tr>
<th>Name</th>
<th>Symbol</th>
<th>Price</th>
<th>$ change</th>
<th>% change</th>
<th>Quantity</th>
<th>Purchase Price</th>
<th>Total Cost</th>
<th>Total % Change</th>
<th>Total $ Change</th>
<th>Fee</th>
<th>Account</th>
<th>Purchase Date</th>
<th><input type="checkbox" name="remove[]" id="selectAll"
value="all"></th>
</tr>
</thead>
<tbody>
<tr>
<td>International Business Machines</td>
<td>ibm</td>
<td>166.95</td>
<td>+3.10</td>
<td>1.86</td>
<td>1,986.88%</td>
<td>$158.95</td>
<td>8</td>
<td>8</td>
<td>71.00</td>
<td>7.00</td>
<td>note</td>
<td>07/16/2015</td>
<td><input type="checkbox" name="remove[]"
value="55a3436f5490c4ed4cbbe1a5"></td>
</tr>
<tr>
<td>Facebook, Inc.</td>
<td>fb</td>
<td>87.95</td>
<td>+2.07</td>
<td>2.35</td>
<td>999.38%</td>
<td>$79.95</td>
<td>8</td>
<td>8</td>
<td>71.00</td>
<td>7.00</td>
<td>note</td>
<td>07/30/2015</td>
<td><input type="checkbox" name="remove[]"
value="55a346745490c4ee4cbbe1a6"></td>
</tr>
</tbody>
</form>
</table>
I don't need the < form > tag in the table at all because JS has access to all the elements in the DOM.
in $('#removie').click(function(event) (I changed it from submit to click because it's no longer a form, but just a button), the checkboxes have to be "unpacked" or "discovered" by JavaScript, and put into a JavaScript array like so:
var remove = [];
$(':checkbox:checked').each(function(i){
remove[i] = $(this).val();
});
...it somehow knows which checkboxes, even though I removed the < form > tag.
The rest in that jQuery function is the same as the original question.
In the PHP, the checkbox data is received via POST only as a comma separated value, and has to be exploded into an array (oh, or not, depending on your code, really) like so:
$remove = explode(',', $_POST['remove']);
Profit.

Knockout Validation - Validation not binding to correct instance of object

I'm using knockout-validation and am having a problem with the error messages not showing correctly after changing what observable an input field is bound to.
I have the following html
<div id="editSection" data-bind="if: selectedItem">
<div>
<label>First Name</label>
<input data-bind="value:selectedItem().FirstName" />
</div>
<div>
<label>Last Name</label>
<input data-bind="value:selectedItem().LastName" />
</div>
</div>
<br/>
<table data-bind='if: gridItems().length > 0'>
<thead>
<tr>
<th>First Name</th>
<th>Last Name</th>
</tr>
</thead>
<tbody data-bind='foreach: gridItems'>
<tr>
<td data-bind='text: FirstName' ></td>
<td data-bind='text: LastName' ></td>
<td><a href='#' data-bind='click: $root.editItem'>Edit</a></td>
</tr>
</tbody>
</table>
And JavaScript
var lineViewModel = function(first, last) {
this.FirstName = ko.observable(first).extend({required:true});
this.LastName = ko.observable(last).extend({required: true});
this.errors = ko.validation.group(this);
}
var mainViewModel = function() {
this.gridItems = ko.observableArray();
this.gridItems([new lineViewModel('first1'), new lineViewModel(null,'last2')]);
this.selectedItem = ko.observable();
this.editItem = function(item){
if (this.selectedItem()) {
if (this.selectedItem().errors().length) {
alert('setting error messages')
this.selectedItem().errors.showAllMessages(true);
}
else{
this.selectedItem(item)
}
}
else
this.selectedItem(item)
}.bind(this)
}
ko.applyBindings(new mainViewModel());
Reproduce
Use this JSFiddle
Click Edit on the first line
Click Edit on the second line - You will be alerted of validation
message being shown and then it will show
Fill out required field
Click Edit on the second line again - You will see "First Name" go
blank and "Last Name" change to "last2"
Click Edit on the first line - You will be alerted of validation
message being shown, BUT it's not show (BUG)
Should I take another approach to this or should I do something different with the way that I am using ko.validation.group?
The validation is fine... your edit section has problems.
Use the with binding. Never use someObservable().someObservableProperty in a binding, it will not work like you might expect it. You should change the binding context.
<div id="editSection" data-bind="with: selectedItem">
<div>
<label>First Name</label>
<input data-bind="value: FirstName" />
</div>
<div>
<label>Last Name</label>
<input data-bind="value: LastName" />
</div>
</div>

Uncaught TypeError: Illegal invocation:error with modal form

this is my first question in stackoverflow, in my html page i have a table, i want to send data to the servlet using modal form. But, i have this error :Uncaught TypeError: Illegal invocation.
table.html
<body>
<table border="1">
<tr>
<th>ID</th>
<th>NAME</th>
<th>ACTION</th>
</tr>
<tr>
<td>1</td>
<td>JHON</td>
<td><input type="button" value="display" class="d"></td>
</tr>
<tr>
<td>2</td>
<td>Max</td>
<td><input type="button" value="display" class="d"></td>
</tr>
</table>
<div id="dialog-form">
<input type="text" value="" id="id">
<input type="text" value="" id="name">
</div>
<div id="res"></div>
</body>
test.js
$(".d").click(function(){
var id =$("#id").attr("value",$(this).parent().prev().prev().text());
var name =$("#name").attr("value",$(this).parent().prev().text());
$("#dialog-form").dialog({
modal: true,
buttons: {
"Send":function () {
$.post("Controller",{id:id,name:name},function(data){
$("#res").html(data);
}) ;
}
Servlet.java
String name=request.getParameter("name");
String id=request.getParameter("id");
out.println(id +" "+ name);
I guess you are trying to modify the value and update it in the backend.
var id =$("#id").attr("value",$(this).parent().prev().prev().text());
var name =$("#name").attr("value",$(this).parent().prev().text());
This will assign the objects to the variables id and name. You cannot send them in ajax and you don't need to. Hence the error.
In your case, you need to update the modal text box with the id and name values and send them to the server. Also do note that since it is a text box, you need to send the updated value which the user might have changed.
Hence we do the following changes.
First we just set the id and name values in the text box present in the modal
$("#id").attr("value", $(this).parent().prev().prev().text());
$("#name").attr("value", $(this).parent().prev().text());
Then in the ajax post, we send the updated value taken from the text box
$.post("Controller", {
id: $("#id").val(),
name: $("#name").val()
}, function (data) {
$("#res").html(data);
});
Here is the working code http://jsfiddle.net/xec61c0m/

Model is not getting updated - AngularJS

I have a simple page where there are list of existing item (these can be modified) and option to add new items to the existing list.
There are 2 sections, CodeLookup and Benchmark. Design of both section is same ( as explained above).
There is a link which will restore all the changes back to the initial state of page.
On JS , there are arrays, one for storing the list which is displayed and a backup array which stores initial state of list. There is an add function which adds newly input data to the list. Lastly there is a cancel method (linked to cancel link) which will restore the list to its initial state. This cancel method just put the original list in the list used to display data.
Now the codelookup value is restored on hit of cancel the first time. But if you modify again in the list and hot cancel, restoration doesnot happen. Also benchmark is not resored at all. I have put breakpoint on Chrome dev tool and found that the list contain the values from original list however its not reflecting on UI.
Any help in fixing this is appreciated.
Below is the code :
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
<SCRIPT type="text/javascript"
src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.7/angular.min.js"></SCRIPT>
<script type="text/javascript">
var referenceDataMaintainenceApp = angular.module('referenceDataMaintainenceApp',[] );
referenceDataMaintainenceApp.controller('referenceDataMaintainenceCtrl', function ($scope) {
$scope.orig_lookup_codes_details;
$scope.orig_calendar_details;
$scope.orig_pams_fields;
$scope.orig_brokers_details;
$scope.lookup_codes_details = [{'lookupName':'ac_asset','codeName':'ABCD','codeDetail':'sdfsdfsdf','ruleDetail':'sdsdsdsdsd','active':false}];
$scope.benchmarks_details = [{'benchmarkName':'Bench1','benchmarkDesc':'First Entry','active':false}];
$scope.orig_lookup_codes_details = angular.copy($scope.lookup_codes_details);
$scope.orig_brokers_details = angular.copy($scope.benchmarks_details);
$scope.addLookupCode = function() {
$scope.lookup_codes_details.push($scope.new_lookup_code);
$scope.new_lookup_code = getLookupCodeObject();
};
$scope.addBenchMark = function() {
$scope.benchmarks_details.push($scope.new_benchmark);
$scope.new_benchmark = getBenchMarkObject();
};
$scope.cancelData = function() {
$scope.brokers_details = $scope.orig_brokers_details;
$scope.lookup_codes_details = $scope.orig_lookup_codes_details;
console.log("sdsd");
//$http.post('/data/save', $scope.benchmarks_details);
};
});
function getLookupCodeObject () {
lookup_code = {
lookupName : '',
codeName : '',
codeDetail : '',
ruleDetail : '',
active : false
};
return lookup_code;
}
function getBenchMarkObject () {
benchmark = {
benchmarkName : '',
benchmarkDesc : '',
benchmarkId : '',
benchmarkType : ''
};
return benchmark;
}
</script>
</head>
<body ng-app="referenceDataMaintainenceApp" ng-controller="referenceDataMaintainenceCtrl" >
<div><A class="operationalnav" ng-click="cancelData()"
href="javascript:;">Cancel</A> </div>
<br />
<br />
<TABLE id="tblGridLookupCodes" class="tableData" border="0"
width="100%">
<THEAD>
<TR bgColor="#eaeaea">
<TD class="tableTitle" noWrap>Code Name</TD>
<TD class="tableTitle" noWrap>Description</TD>
<TD class="tableTitle" noWrap align="center">Active</TD>
</TR>
</THEAD>
<TBODY>
<TR ng-repeat="lookup_code_detail in lookup_codes_details">
<td nowrap="nowrap">{{lookup_code_detail.codeName}}</td>
<td nowrap="nowrap">
<input type="text" name="codeLookupBean[0].codeDescription"
maxlength="100" size="80" ng-model="lookup_code_detail.codeDetail" />
</td>
<td nowrap="nowrap" align="center">
<input type="checkbox" name="codeLookupBean[0].active"
ng-model="lookup_code_detail.active" />
</td>
</TR>
</TBODY>
</TABLE>
<HR width="100%">
<table>
<tr>
<td>
<INPUT id="codeNameInput" name="codeNameInput"
maxLength="32" ng-model="new_lookup_code.codeName" />
</td>
<td>
<INPUT id="descInput" name="descInput" maxLength="100"
size="80" ng-model="new_lookup_code.codeDetail">
</td>
<td>
<INPUT id="activeInput" name="activeInput" CHECKED type="checkbox"
ng-model="new_lookup_code.active" />
</td>
<td>
<INPUT id="btnAddRow" class="btnz" title="Add Row"
ng-click="addLookupCode($event)" name="btnAddRow" value=" Add "
type="button" />
</td>
</tr>
</table>
<br /><br /><br />
<TABLE id="tblGridBenchmarks" class="tableData" border="0" width="100%">
<THEAD>
<TR bgColor="#eaeaea">
<TD class="tableTitle" noWrap>Benchmark Name</TD>
<TD class="tableTitle" noWrap>Description</TD>
</TR>
</THEAD>
<TBODY>
<TR ng-repeat="benchmark_detail in benchmarks_details">
<TD>{{benchmark_detail.benchmarkName}}</TD>
<TD><INPUT name="benchmarkBean[0].benchmarkDesc"
maxLength="255" size="120" ng-model="benchmark_detail.benchmarkDesc"></TD>
</TR>
</TBODY>
</TABLE>
<HR width="100%">
<table>
<tr>
<td>Enter Benchmark Name:<BR> <INPUT
id="benchmarkNameInput" name="benchmarkNameInput"
ng-model="new_benchmark.benchmarkName" maxLength="100" size="30">
</td>
<td>Description:<BR> <INPUT name="benchmarkDescInput"
ng-model="new_benchmark.benchmarkDesc" maxLength="255" size="80">
</td>
<td><INPUT id="btnAddRowComment" class="btnz" title="Add Row"
ng-click="addBenchMark($event)" name="btnAddRowComment"
value=" Add " type="button"></td>
</tr>
</table>
It seems like $digest cycle was not run at all or correctly.
try to run $scope.$apply() and see if it works.
example:
http://jsfiddle.net/00d0ux1x/
For more information see
http://www.sitepoint.com/understanding-angulars-apply-digest/
However in your case problem is
javascript:; change to javascript:void(0);
use angular.copy(); to copy original array if you don't want to modify it in later use.
in cancel function you are setting $scope.brokers_details and in view using $scope.benchmarks_details. (also having orig_brokers_details)
See fixed solution
http://jsfiddle.net/00d0ux1x/3/

Creating and submitting a form in tiptip

I just implemented tiptip and found it fantastic to use. Now i want to make a form and use it in tiptip tool tip so that user can fill and submit it.
I have created tiptip as
$('.div').tipTip({
maxWidth: 1000,
defaultPosition: 'right',
content: function (e) {
$.ajax({
url: 'tets.php',
datatype: JSON,
success: function (response) {
$('#tiptip_content').html(response);
$('body').append(response).fadeIn('1000');// the var e is the callback function data (see above)
}
});
return 'Please wait...'; // We temporary show a Please wait text until the ajax success callback is called.
}
});
I get a form in my tooltip. Now as soon as i take my mouse in it, it disappears (obviously, its a tooltip at the end). Is there any way to do what i am trying to achieve??
My html
<div class="div">Hover on Me</div>
tets.php
<form id = "testForm" method="post" action="newEmptyPHP.php">
<table width="400" border="0" align="center" cellpadding="5" cellspacing="0">
<tr>
<td width="150">Username</td>
<td width="250"><input name="username" type="text" class="textfield" /></td>
</tr>
<tr>
<td>Password</td>
<td><input name="password" type="password" class="textfield" /></td>
</tr>
<tr>
<td> </td>
<td><input name="remember" type="checkbox" value="d"> Remember me</td>
</tr>
<tr>
<td> </td>
<td><input type="submit" name="login" value="Login" /></td>
</tr>
</table>
</form>
http://code.drewwilson.com/entry/tiptip-jquery-plugin
"keepAlive: true of false (false by default) - When set to true the TipTip will only fadeout when you hover over the actual TipTip and then hover off of it."
Try adding this property and set it to true
Update:
Example here: http://jsbin.com/imeqes/2/
Appears to work fine when you hover over image, then hover over tip, it stays there.

Categories