JQuery, Javascript button - javascript

Sorry for the vague title, couldn't think of how to title my question. So I've made a html/css table wherein I placed an edit button for each row. Pressing the button would transform a certain text field into a text-input field there by allowing the user to edit the data inside; at the same time the edit button then transforms to save button. After editing , the user then would press the save button and the text-input field would then revert back into a text field and the save button back to an edit button. But it's not entirely working
This is my problem, after editing the data inside, upon pressing the save button, the data inside is deleted and replaced with: <input type= and outside the text-input field is: " />
and the save button remains as is, a "SAVE" button and not back to an "EDIT" button
here's the script:
$(document).ready(function () {
// listen for email edit button click
$("button#edit").on('click', function () {
// get email inline to this edit button
var email = $(this).parent().siblings('td.email').html();
alert(email);
// change button from edit to save
$(this).attr('id', 'save-email').html('SAVE');
// change email display to input field
$(this).parent().siblings('td.email').html('<input type="text" id="user-email" value="' + email + '" />');
});
// listen for email save button click
$("button#save-email").on('click', function () {
// get new email inline to this save button
var newEmail = $(this).parents('tr').find($('input#user-email')).val();
alert(newEmail);
// change input field back to display
$(this).parent().siblings('td.email').html(email);
// change button from save to edit
$(this).attr('id', 'edit').html('EDIT');
});
});
sorry for the wall of text.

try to put it this way :
$(document).on('click',"button#save-email", function() {...
instead of
$("button#save-email").on('click', function()
using the second one won't work, because when it is run, $("button#save-email"), doesn't exist yet.

The problem is that the first handler is the only one attached in script.
Your javascript code is executed when the page is ready.
At that moment only the first handler is attached because there is not yet an element button#save-email. When you click save, it is the first handler that is executed again, not the one think !
Why don't you create two distinct buttons and show one or the other ?
<table>
<tr>
<td class="email">myemail#domain.com</td>
<td>
<button class="btn-edit">Edit</button>
<button class="btn-save" style="display:none">Save</button>
</td>
</tr>
<tr>
<td class="email">myemail#domain.com</td>
<td>
<button class="btn-edit">Edit</button>
<button class="btn-save" style="display:none">Save</button>
</td>
</tr>
</table>
Javascript
// listen for email edit button click
$('.btn-edit').on('click', function() {
var $this = $(this),
$parentRow = $this.closest('tr');
// get email inline to this edit button
var email = $this.parent().siblings('td.email').html();
// change button from edit to save
$parentRow.find('.btn-edit').hide();
$parentRow.find('.btn-save').show();
// change email display to input field
$(this)
.parent()
.siblings('td.email')
.html('<input type="text" id="user-email" value="'+email+'" />');
});
// listen for email save button click
$('.btn-save').on('click', function() {
var $this = $(this),
$parentRow = $this.closest('tr');
// get new email inline to this save button
var newEmail = $(this).parent().siblings('td.email').find('#user-email').val();
// change input field back to display
$(this).parent().siblings('td.email').html(newEmail);
// change button from save to edit
$parentRow.find('.btn-edit').show();
$parentRow.find('.btn-save').hide();
});
DEMO

Take a look at KnockoutJS, which utilizes nice Bindings helping you to do things like that much easier. Here is an example of an editable grid with KnockoutJS
KnockoutJS Editable Data example

Neat & Works
<table>
<tr>
<td>some text</td>
<td><input type='button' value='edit' id='btn'/></td>
</tr>
</table>
$(document).ready(function() {
$("#btn").click(function() {
var $btn=$(this);
var opn= $btn.val()
switch(opn){
case 'edit':
var $td=$(this).parent().parent().find('td:first');
var email=$td.html();
$td.html("").append('<input type="text" value="'+email+'">');
$btn.val("save");
break;
case 'save':
var $input=$(this).parent().parent().find('td:first input');
var email=$input.val();
$input.parent().html(email);
$btn.val("edit");
break;
}
});
});
http://jsfiddle.net/h55rc/

Related

Child Div is not removed when tried to remove using Jquery

Clearing child div inside parent div, there are many answers like :
$(".ChildDiv").html("");
$('.ChildDiv > div').remove();
$(".ChildDiv").html("");
$("#ParentDiv").html("");
$(".ChildDiv div").remove();
$(".ChildDiv div").empty();
$('.ChildDiv ').find('div').remove();
Probably I have listed all possible way to remove the div's, but even after using all these, I still not able to clear all the div's inside Parent Div. let me explain what I am doing and what I need.
Scenario :
I have two container-1, one of the container has input search box, where I can search for entering employee name and select few employees Ex. 5 and can use "Add" button to move those employees to the other container-2 which is 'div'.
Now I click on report button event and get the information of those 5 people in different aspx, now if i go back to the page where i have to search for another 3 employees and when I again click on the "Add" button, it should add only 3 employees instead it is adding last searched 5 + 3 employees!!.
So i am trying to clear the 5 employees inside that div after i click on "Report" button , when i use alert() it says it has 0 element, but when I add it for the second time, it appends the data again, which i dont need. here is the code :
Points to remember :
1. ParentDiv is the container-2
2. ChildDiv is the child div inside ParentDiv(which is dynamically appended when we select 5 employees on "Add" button click"
Here is the code:
HTML :
<table id="topTable">
<tr>
<td id="leftpane">
<h4>Search for Employee by Name or Profile:</h4>
<input type="text" id="EmployeeSearchBox" class="search-box" aria-multiselectable="true" />
<select id="EmployeeList" size="20" multiple></select>
</td>
<td id="centerpane">
<div> <input type="button" value="Add >>" class="AddButton" id="buttonAdd" /></div>
<div> <input type="button" value="Add All >>" class="AddButton" id="buttonAddAll" /></div>
</td>
<td id="rightpane">
<h4>Selected Employees:</h4>
<div id="ParentDiv"></div>
</td>
</tr>
</table>
Run Report button event
<input class="data" type="submit" name="cmdSubmit" value="Run Report" onclick="return FormValidate();"
onserverclick="RunReport" runat="server" id="Submit1" />
Add Button Click :
which moves the employees from container-1 to container-2.
$(document).on('click', '#buttonAdd', function (e) {
$('#EmployeeList :selected').each(function (i, selected) {
myHash[$(selected).val()] = $(selected).text();
});
var myNode = $("#ParentDiv")[0];
while (myNode.firstChild) {
myNode.removeChild(myNode.firstChild);
}
for (var emp_id in myHash) {
var emp = $("#ParentDiv").append("<div class= ChildDiv id=" + emp_id + ">" + myHash[emp_id] + " <span class='close'>×</Span> </div>");
}
$('#EmployeeSearchBox').val("").trigger('input');
});
On click of "Report" button it should clear all the elements from ParentDiv/ChildDiv which is what I did, but still it is not clearing it, how can I resolve/remove these elements once "Report" button event clicked.
Here is a sample of "Report" button event :
function FormValidate() {//Part of my other code
$(".ChildDiv").html("");
$('.ChildDiv > div').remove();
$(".ChildDiv").html("");
$("#ParentDiv").html("");
$(".ChildDiv div").remove();
$(".ChildDiv div").empty();
$('.ChildDiv ').find('div').remove();
}
None of them is working, i feel there is an issue with the "Add" button event, where it is storing the data.
NOTE :
I don't want to clear the array of employee list, since I want to select multiple employees again again Ex. I can select 2 employees starts with the letter "M" and I can search the 2 employees of letter "L" and add those 2 employees, the container should hold 4 employees before "Report" button click.
Let me know if I am clear enough.
Console Log
Finally I could able to fix the issue, i was facing, I am posting the answer, now it is working as I need.
$(document).on('click', '#buttonAdd', function (e) {
var div_count = $('#ParentDiv').find('div').length;
if (div_count === 0) {
myHash = []; // Clearing the hash, so that it can add fresh employees, if count == 0 in container- 2.
$('#EmployeeList :selected').each(function (i, selected) {
myHash[$(selected).val()] = $(selected).text();
});
}
else { // If there are existing employees in container-2 then append few more.
$('#EmployeeList :selected').each(function (i, selected) {
myHash[$(selected).val()] = $(selected).text();
});
}
var myNode = $("#ParentDiv")[0];
console.log(myNode);
while (myNode.firstChild) {
myNode.removeChild(myNode.firstChild);
}
for (var emp_id in myHash) {
var emp = $("#ParentDiv").append("<div class= ChildDiv id=" + emp_id + ">" + myHash[emp_id] + " <span class='close'>×</Span> </div>");
}
$('#EmployeeSearchBox').val("").trigger('input');
});
What I did
Since I should be able to append multiple employees by searching, that is handled in 'else' part, if I generated the "Report" then, I am clearing the Container-2.
When I come back to page to search few more employees, by this time Container-2 will not be having any employees, so
var div_count = $('#ParentDiv').find('div').length;
if (div_count === 0) {
myHash = [];
//....
}
will clear the array which allow me to add fresh employees, hence it solved my problem :)
Thanks all for the support.
Edited to adjust on comments:
You need to clear the myHash variable. Otherwise employees will be added again from there.

HTML Form: How to remember text values of button click?

If you have a form, type some text into it, and press the Enter key, whenever revisiting that form you can double-click on the input box and see the past text submissions.
I have a site that when you press Enter OR click a button, it should take whatever is in the text box and use it for data processing.
This works totally fine when not surrounded by a form but when surrounded by a form an you press the Enter key, it does not act as an enter button push, I believe it's being overridden by the form.
My goal is to have the user be able to press the Enter key as well as click the button to submit the data, but to also remember the text values that were in the text box regardless of which way you submitted the data.
What I have:
<input type="text" id="username-field" class="form-control" placeholder="username">
<input class="btn btn-default" type="button" id="get-name" value="Get Name">
Javascript
$("#get-name").click(function() {
var name = $("#username-field").val();
// ... call other function with name ...
});
$("#get-name").keydown(function(e) {
if (e.which == 13) {
var name = $("#username-field").val();
// ... call other function with name ...
}
");
What I would like to use:
<form>
<input type="text" id="username-field" class="form-control" placeholder="username">
</form>
I tried doing e.preventDefault() when the Enter key is pressed, but this does not remember the text in the input field.
I also considered doing a small cache type thing but am unsure of how I'd go about this.
Any help would be much appreciated!
Thanks!
Doesn't use form at all. Just, why you added it, if you don't use it as intended?
You either mistyped provided code copy-paste, or have errors in yours script (the $("#get-name").val() mistake).
If you want to prevent form from submission, you should e.preventDefault()-it in submission handler, and return false from it:
$('#form-id').submit(function (e) {
e.preventDefault();
// do smth. else here
...
return false;
})
Saving/retriving data with localStorage for HTML5-supporting browsers:
$(function () {
$('form input[type=text]').doubleclick(function () {
var id = $(this).attr("id");
value = localStorage.getItem("form_xxx_" + id);
// do smth. with cached value, ie:
if (value != "")
$(this).val(value); // put in textfield
});
});
$('form').submit(function (e) {
$('form input[type=text]').each(function () {
var id = $(this).attr("id");
localStorage.setItem("form_xxx_" + id, $(this).val());
});
...
// all other work
});
Note: make sure you don't put some user's personal data in browser's local storage -_-

How to set text box to appear blank after .click function

So I have a simple log in that requires a user to input values from a json file into two different text boxes ,when the user name and (in this case I have used ID as password) matches then an alert appears to say... "welcome"
After the .click function is carried out the users text still remains in the text box, how can I get both text boxes to appear blank after the .click function?
$(document).ready(function() {
//Hide alert when page loads
$("#loginalert").hide();
$("#invalid").hide();
$("#loginbtn").click(function(event){
$.getJSON('result.json', function(jd) {
var id = $('#userName').val();
var name = $('#userName2').val();
var valid = false;
for (var i=0; i<jd.user.length; i++) {
if ((jd.user[i].ID == id) && (jd.user[i].name == name)) {
valid=true;
$('#loginalert').html('<img src="' + jd.user[i].imgpath + '"><br><p> Welcome: ' + jd.user[i].name + '</p><button type="button" id="btnhide" class="btn btn-primary btn-md">Hide</button>');
//show the alert after loading the information
$("#loginalert").stop().fadeIn('slow').animate({ opacity: 1.0 }, 3000)
$('#invalid').hide();
$('#btnhide').on('click', function(e){
//console.log('here');
e.preventDefault();
$('#loginalert').hide();
});
}
}
if (!valid) {
$('#invalid').fadeIn('slow');
$('#loginalert').hide();
}
});
}); });
username 1 and #username 2 are the text boxes - is there any way to get user name 2 to display in stars ****** when the user enters the password - this question is not that necessary but if i could also get that working that would be good.
thanks guys hope someone can help :)
is there any way to get user name 2 to display in stars ****** when
the user enters the password
You can use an input box with text property set as password. But that password masking character will be . instead of *. Not exactly sure, whether it will be a different character in some browsers.
<input type="password" id="txtPassword" />
text box to appear blank after .click function
You can set the .val() property of the jQuery objects of two those two textboxes.
$('#userName, #username2').val('');
Use <input type="password"> to show typing as stars.
Clear inputs by setting their value to be empty: $('#userName').val('');
And perhaps consider breaking your code down into a couple smaller functions so it's easier to follow.
document.getElementById("#myTextbox").value="";
This should get your textbox and set the value of it to "", which is blank.
Edit: JSFiddle
Another Method:
You can also add the script directly inside the button without using/creating a function.
<input id="inputId" type="name" />
<button onclick="document.querySelector('#inputId').value='';"> Clear </button>
Using querySelector:
<input id="inputId" type="name" />
<button onclick="click()"> Clear </button>
<script>
function click() {
document.querySelector('#inputId').value="";
}
</script>

Send selected data back to original window

I have a file called bpSearch. Inside bpSearch, I have a MODAL window, called addNewModal. Within addNewModal, I have 2 INPUT fields called partnerName and partnerCode. I have a button that once clicked, opens into another MODAL window, called searchPartnerModal.
Here is the a portion of the FORM inside addNewModal:
<form action="bpSearch.php" method="get">
<input type="text" readonly id="partnerName" name="partnerName" />
<input type="text" readonly id="partnerCode" name="partnerCode" />
Go
</form>
When the user clicks GO, it opens searchPartnerModal.
searchPartnerModal is where the user will enter either a code or a name (doesn't have to be both). But upon hitting SEARCH, I use an AJAX call that returns JSON that I parse and eventually return in a UL field called pNames. We're still inside searchPartnerModal.
Here is the FORM inside searchPartnerModal:
<form action="bpSearch.php" method="get">
<input type="text" id="pNameSearch" name="pNameSearch" />
<input type="text" id="pCodeSearch" name="pCodeSearch" />
<input type="button" class="btn" id="pSearch" name="pSearch" value="search" />
</form>
When the user enters a name, I use jquery to send it over to a PHP script that will then return the data in a UL tag.
Here is the jquery that will search if the user enters a name:
$('#pSearch').on('click', function()
{
var partnername = $('#pNameSearch').val();
if($.trim(partnername) != '')
{
$.post('api/pNameSearch.php', {partnername: partnername}, function(data)
{
var obj = JSON.parse(data);
$('#pNames').empty();
var htmlToInsert = obj.map(function (item)
{
return '<li><a id="getPInfo" href="javascript:;"
onclick="getPInfo()" data-selname="'+item.FULL_NAME+'"
data-selcode="'+item.PARTNER_CODE+'">'
+ item.FULL_NAME + ' - '
+ item.PARTNER_CODE + '</a></li>';
}).join('');
$('#pNames').html(htmlToInsert);
});
};
});
With this code, I am able to send the name to search the database table for a valid name. The data is returned via JSON and is parsed and displayed inside the UL tag (called pNames) as LI tags, each with an A tag with their own data-attributes, called data-selname and data-selcode.
Now what I need to do is once the user clicks on one of the returned data links inside pNames, I need to send it back to the previous modal window, addNewModal.
This is where I'm stuck.
If you look inside the Jquery above, after I parsed the JSON, you will see that I created another Javascript function inside the A tag of each returned piece of data, called getPInfo().
Here is what I got so far for the function getPInfo() :
function getPInfo()
{
var selname = ($('#getPInfo').attr('data-selname'));
var selcode = ($('#getPInfo').attr('data-selcode'));
}
At this point, I can alert both variables (selname and selcode) and get them to display in an alert window.
What I want to do is send both of those variables back to addNewModal in the respective INPUT fields, called partnerName and partnerCode.
So selname will go to partnerName and selcode will go to partnerCode.
I didn't display the PHP script that returned the data.
Change the anchor id=getPInfo to class=getPInfo since you have multiple anchors. Next, handle the click event of the anchor and extract the data attributes and set the corresponding form elements in the addNewModal form. Following should work based on the markup i see so far.
$(function(){
$('body').on('click', 'a.getPInfo', function (e) {
var $a = $(e.srcElement || e.target);
$('#partnerName').val($a.attr('data-selname'));
$('#partnerCode').val($a.attr('data-selcode'));
$('#searchPartnerModal').modal('hide'); //assuming bootstrap modal
});
});

pass var to function() js with jquery

Just looking for the best practise way of doing this.
I have a table listing information and in the last column is a button with "Edit/View". When the user clicks on the button a div area appears with more information which can be edited
Code below with some fragments of jstl
<script type="text/javascript">
//Click on Edit/View on table
$('.viewCustomer').click(function()
{
.......
});
</script>
<tr class="odd">
<td>${customerBean.comName}</td>
<td>${customerBean.comCode}</td>
<td class="noRightPad"> <input type="submit" name="createBut" value="View/Edit" class="viewCustomer" /> </td>
</tr>
So my question would be:
(1) how do i pass a variable to function $('.viewCustomer').click(function()
(2) is this the best way of going about to do this. Is there a more efficient/secure/cleaner of doing this?
Cheers
Alexis
The click function will not be called by you. It is called when the button is clicked, and as such has the event object passed to it:
$('.viewCustomer').click(function(evt){
.......
});
What exactly are you wanting to pass? You can access the DOM element that you are clicking using this and $(this), so maybe it possible to reference what you want from here.
EDIT For comment
if the user clicked on the button that
was in the 4th row of the table and in
that row the another colum had
customer id 1234 i want to pass the
variable 1234.
NOTE: None of the below has been tested, but ought to suffice
Let's assume your 'customer id' column has a classname of 'customerid'. So your HTML might be:
<tr class="odd">
<td>${customerBean.comName}</td>
<td class="customerid">${customerBean.comCode}</td>
<td class="noRightPad"> <input type="submit" name="createBut" value="View/Edit" class="viewCustomer" /> </td>
</tr>
The jQuery might look something like:
$('.viewCustomer').click(function(){
var $buttonCell = $(this).parent(); //the <td> containing the button
var $buttonRow = $buttonCell.parent(); //the <tr> containing the button and your customer id
var $customerIdCell = $buttonRow.find("td.customerid");
var customerId = $customerIdCell.text();
});
The above is proken down into lines to show you how stuff is being retrieved. Using 'chaining' we can express it more concisely:
$('.viewCustomer').click(function(){
var customerId = $(this).parent().parent().find("td.customerid").text();
}
You can also search for the customerid cell as a 'sibling' of the button cell for an even more concise approach (and one less function call).
$('.viewCustomer').click(function(){
var customerId = $(this).parent().siblings("td.customerid").text();
}

Categories