How to edit and update <td> value when double click Jquery - javascript

I have written my code such that when user double clicks on a <td> element I am:
appending am <input> of type="text"
adding a value to it and update it if the user clicks on enter
Here is the my problem:
If user double clicks on <td> and clicks on another <td> without pressing enter, I need the initial <td>'s <input> to be reset to previous value.
// Selecting the table <th> odd elements
$("#div table td").dblclick(function(){
var currentEle = $(this);
var value = $(this).html();
updateVal(currentEle, value);
});
function updateVal(currentEle, value)
{
$(currentEle).html('<input class="thVal" type="text" value="'+value+'" />');
$(".thVal").focus();
$(".thVal").keyup(function(event){
if(event.keyCode == 13){
$(currentEle).html($(".thVal").val().trim());
}
});
$('body').not(".thVal").click(function(){
if(('.thVal').length != 0)
{
$(currentEle).html($(".thVal").val().trim());
}
});
}
Please help me.
I don't want to use jeditable datatable.

Here in your case you need .stopPropagation(): http://jsfiddle.net/jFycy/
$(function () {
$("#div table td").dblclick(function (e) {
e.stopPropagation(); //<-------stop the bubbling of the event here
var currentEle = $(this);
var value = $(this).html();
updateVal(currentEle, value);
});
});
function updateVal(currentEle, value) {
$(currentEle).html('<input class="thVal" type="text" value="' + value + '" />');
$(".thVal").focus();
$(".thVal").keyup(function (event) {
if (event.keyCode == 13) {
$(currentEle).html($(".thVal").val().trim());
}
});
$(document).click(function () { // you can use $('html')
$(currentEle).html($(".thVal").val().trim());
});
}
Instead doing click on body do the event on document or html which is the parent elem of all others elems.

Fixed the last answer. by checking who triggered the event i can prevent the double click issue on the input.
Also, with the .off('click') you dont have the problem where every td you updated before changes with the last one.
$(function () {
$(".inner").dblclick(function (e) {
if($(event.target).attr('class')!="thVal")
{
e.stopPropagation();
var currentEle = $(this);
var value = $(this).html();
updateVal(currentEle, value);
}
});
});
function updateVal(currentEle, value) {
$(document).off('click');
$(currentEle).html('<input class="thVal" type="text" value="' + value + '" />');
$(".thVal").focus();
$(".thVal").keyup(function (event) {
if (event.keyCode == 13) {
$(currentEle).html($(".thVal").val());
}
});
$(document).click(function () {
if($(event.target).attr('class')!="thVal")
{
$(currentEle).html($(".thVal").val());
$(document).off('click');
}
});
}

I know its an old topic... but the answer that posted here didnt worked well because of the click event on the input, I took the answer and modified it
$(".daily-signals > tbody > tr > td").dblclick(function (e) {
e.stopPropagation(); //<-------stop the bubbling of the event here
var currentEle = $(this);
var value = $(this).html();
console.log('fire!');
updateVal(currentEle, value);
});
function updateVal(currentEle, value) {
$(currentEle).html('<input class="thVal" type="text" value="' + value + '" />');
var thVal = $(".thVal");
thVal.focus();
thVal.keyup(function (event) {
if (event.keyCode == 13) {
$(currentEle).html(thVal.val());
save(thVal.val());
}
});
thVal.focusout(function () {
$(currentEle).html(thVal.val().trim());
return save(thVal.val()); // <---- Added missing semi-colon
});
}
function save(value) {
console.log(value);
}
the save function will make the ajax request

Related

Adding a br tag on Enter

How do I add a <br /> tag each time enter is pressed inside a keyup function? I have no clue as to how this should be done.
.on("keyup", ".club", function() {
//detect enter key to add br tags
});
Try this:
.on("keyup", ".club", function(e) {
if (e.keyCode === 13) {
var $this = $(this); // Caching
$this.val($this.val() + '<br />');
// OR
$this.val($this.val() + '\n\r');
}
});

how do I get the `id` from a `tr` I leave and a `tr` I'm entering as a global variable

My problem is that I can't get my handlers to update global variables so I can work with them.
I'm making a script that is supposed to "see" when you change a line and add the line you leave to a database.
To do this I need to get the id from both trs and compare them. This is the problem though. I cant make my handlers deliver the data I need.
This is the table that I create dynamically.
<tr id="r'.$value['id'].'">
<td><input type="text" name="from_date" value="'.$value['db_field1'].'" class="autoupdate r'.$value['id'].'"></td>
<td><input type="text" name="from_date" value="'.$value['db_field2'].'" class="autoupdate r'.$value['id'].' required"></td>
<td><input type="text" name="from_date" value="'.$value['db_field3'].'" class="autoupdate r'.$value['id'].' required"></td>
</tr>
Here is my jquery.
$('tr td input.autoupdate').on('blur',function(event){
event.stopPropagation();
event.preventDefault();
rid = $(this).closest('tr').attr('id');
return rid;
});
$('tr td input.autoupdate').on('focus',function(e){
event.stopPropagation();
event.preventDefault();
newid = $(this).closest('tr').attr('id');
});
if ( rid !== newid ) {
console.log('old id: '+rid);
console.log('new id: '+newid);
} else {
console.log('same row');
}
I have defined rid and newid outside $(document).ready(function().
I think this is what you are looking for:
var rid='',newid='';
$('tr td input.autoupdate').on('blur', function (event) {
event.stopPropagation();
event.preventDefault();
rid = $(this).closest('tr').attr('id');
});
$('tr td input.autoupdate').on('focus', function (event) {
event.stopPropagation();
event.preventDefault();
newid = $(this).closest('tr').attr('id');
check();
});
function check(){
if (rid !== newid) {
console.log('old id: ' + rid);
console.log('new id: ' + newid);
} else {
console.log('same row');
}
}
CHECK THE FIDDLE
Instead you can use 'mouseenter' and 'mouseleave' events,
var rid='',newid='';
$('tr').on('mouseenter', function (event) {
event.stopPropagation();
event.preventDefault();
newid = $(this).attr('id');
console.log('mouse leave', newid);
check();
});
$('tr').on('mouseleave', function (e) {
event.stopPropagation();
event.preventDefault();
rid = $(this).attr('id');
console.log('mouse enter', rid);
check();
});
function check(){
if (rid !== newid) {
console.log('old id: ' + rid);
console.log('new id: ' + newid);
} else {
console.log('same row');
}
}

jquery form check before submit with select name array

I'm having a hard time with this quick validation i want in place...but i think it's not validating properly because of my select name arrays and i'm not sure how to go about this.
How it should work:
- If stat holiday box is checked for that day && if any Lieu hours are selected for that day give alert error and stop form submission.
My jsfiddle: http://jsfiddle.net/4bgYj/3/
my jquery:
$(document).ready(function() {
$(document).on('submit', 'form', function(e) {
var lieuhrs = $(".lieutimehours").val();
$('.lieutimehours').each(function(i, obj) {
if ($("#statholidaycheck").is(":checked") && lieuhrs > 0) {
alert("cannot process: " + lieuhrs);
return false;
}
}
});
});
Let me give you a more user-friendly approach for your problem:
If stat is selected simply disable the form input for lieu hours.
With this you won't have to check anything before submitting the form and the user can't accidentally select a value in lieu hours.
It still needs to be updated to your markup, but the idea is basically:
var stat = $('.stat');
stat.change(function() {
var e = $(this);
var f = e.parent().find('.lieu');
if (e.is(':checked')) {
f.prop('disabled', true);
} else {
f.prop('disabled', false);
}
});
Demo
Try before buy
First, you're missing a );...
$(document).ready(function() {
$(document).on('submit', 'form', function(e) {
var lieuhrs = $(".lieutimehours").val();
$('.lieutimehours').each(function(i, obj) {
if ($("#statholidaycheck").is(":checked") && lieuhrs > 0) {
alert("cannot process: " + lieuhrs);
return false;
}
}); // missing ); here. <--------------
});
});
Try it after adding that and you'll find it works for the first checkbox. But select a different checkbox and it will fail. In HTML, you will want to use unique ids to reference an element. What I would do is change your HTML to put a css class on the TR tag, and then look at the contained elements.
<tr class='line'>
<td> <input type='checkbox' class='isHoliday'/> </td>
<td> <select class='lieuHours'>options...</select> </td>
</tr>
and in your script...
$(document).ready(function() {
$(document).on('submit', 'form', function(e) {
$('.lines').each(function(i, obj) {
var lieuHours = $(this).find(".lieuHours").val();
if ($(this).find(".isHoliday:checked") && lieuHours > 0) {
alert("cannot process: " + lieuhrs);
return false;
}
}); // missing ); here. <--------------
});
});
You didn't approach the issue properly, the selectors should not be global but specific to the loop you are doing:
$(document).ready(function() {
$(document).on('submit', 'form', function(e) {
$('.lieutimehours').each(function(i, obj) {
var lieuhrs = $(this).val();
if ($(this).closest('tr').find('#statholidaycheck').is(":checked") && parseFloat(lieuhrs) > 0) {
alert('works');
return false;
}else{
alert('fail')
}
});
});
});

jQuery Arguments Not Working

Having trouble with 2 things. Both of these arguments are ONLY working for the first box area generated on page load. But any subsequent ones created after aren't affected by these options. What am I doing wrong, and how can I fix it?
//CHECK IF TYPE/PAGE(S) IS SELECTED OR NOT
$(".dropdown").change(function () {
if($(this).val() == "0") $(this).addClass("empty");
else $(this).removeClass("empty").children('.placeholder').remove();
});
//CHECKS TO MAKE SURE ONLY ONE CHECKBOX IS SELECTED
var $onlyOne = $('.onlyOne');
$onlyOne.click(function () {
$onlyOne.filter(':checked').not(this).removeAttr('checked');
});
The entire code for my JS is:
$(function () {
var i = 1;
//ADD ROW
$('body').on('click', '.addPTbutton', function () {
var box = '<table class="manage-pt" id="' + i + '"><tr class="pt-entry"><td class="pt-toggle-group"><input class="pt-button togPTbutton" id="0" type="button" value="▾"><input class="pt-button addPTbutton" id="0" type="button" value="+"><input class="pt-button delPTbutton" id="' + i + '" type="button" value="-"></td><td class="pt-values"><div><input class="vendor grayout" placeholder="*Vendor Name" type="text"><select class="move-me-right-10 dropdown"><option value="0" class="placeholder" selected="selected">*Select Type</option><option value="analytics">Analytics</option><option value="chat">Chat</option><option value="remarketing">Remarketing</option><option value="other">HTML/CSS/JS</option></select><i class="icon-sort"></i><i class="icon-lock"></i></div><div><textarea class="ptCode" name="ptCode" placeholder="*Pixel Tag Code"></textarea></div><div class="page-select"><select class="dropdown"><option value="0" class="placeholder" selected="selected">*Select Page(s)</option><option value="AllPages">All Pages</option><option value="HomePage">HomePage</option><option value="VehicleDetailsPage">VehicleDetailsPage</option><option value="VehicleSearchResults">VehicleSearchResults</option><option value="ContactUsForm">ContactUsForm </option></select></div><div class="area-checkboxes"><p class="wheretosave">*Where?</p><input name="head" type="checkbox"><label for="head">Head</label><input name="body" type="checkbox"><label for="body">Body</label></div><hr/></td></tr></table>';
i++;
$("#p_scents").append(box);
return false;
});
//DELETE ROW
$('body').on('click', '.delPTbutton', function () {
var boxnum = $(".manage-pt").length;
if (boxnum <= '1') {
alert('Cannot Delete Last Remaining Row');
} else {
$(this).parents().eq(3).remove();
}
return false;
});
//TOGGLE BUTTON
$('body').on('click', '.togPTbutton', function () {
var hiddenarea = $(this).parent().next().children().next();
if ($(hiddenarea).is(':hidden')) {
//PT-VALUES OPENED
$(this).val('▾');
$(this).parent().next().children(0).children(0).attr('readonly', false);
//$(this).parent().next().children(0).children(1).prop('disabled', false);
} else {
//PT-VALUES HIDDEN
$(this).val('▸');
$(this).parent().next().children(0).children(0).attr('readonly', true);
//$(this).parent().next().children(0).children(1).prop('disabled', 'disabled');
}
//TOGGLE VISIBILITY OF HIDDEN AREA
hiddenarea.toggle();
});
//CHECK IF TYPE/PAGE(S) IS SELECTED OR NOT
$(".dropdown").change(function () {
if($(this).val() == "0") $(this).addClass("empty");
else $(this).removeClass("empty").children('.placeholder').remove();
});
$(".dropdown").change();
//CHECKS FOR MORE THAN ONE 1 MANAGE-PT BEFORE ENABLES SORTABLE
$('body').on('mouseenter', '.icon-sort', function () {
if ($(".manage-pt").size() > 1) {
$('#p_scents').sortable({
disabled: false,
placeHolder: '.placeHolderHighlight',
handle: '.icon-sort',
});
} else $('#p_scents').sortable({
disabled: true,
});
});
//CHECKS TO MAKE SURE ONLY ONE CHECKBOX IS SELECTED
var $onlyOne = $('.onlyOne');
$onlyOne.click(function () {
$onlyOne.filter(':checked').not(this).removeAttr('checked');
});
//LOCK BUTTON ON/OFF LOCKS FORM
$('body').on('click', '.icon-lock', function () {
$(this).toggleClass('locked');
var lockedarea = $(this).parents(0).eq(2);
$(lockedarea).find('input[type=text],input[type=checkbox],textarea,select').prop('disabled', function (_, val) {
return !val;
});
});
});
I assume you're using AJAX. You should be handling event delegation differently for dynamically generated DOM elements.
Ideally, you shouldn't be using body or document. Try using the nearest parent selector which is present all the time(non AJAX).
//CHECK IF TYPE/PAGE(S) IS SELECTED OR NOT
$("body").on("change", ".dropdown", function () {
if($(this).val() == "0") $(this).addClass("empty");
else $(this).removeClass("empty").children('.placeholder').remove();
});
//CHECKS TO MAKE SURE ONLY ONE CHECKBOX IS SELECTED
$("body").on("click",'.onlyOne', function () {
$onlyOne.filter(':checked').not(this).removeAttr('checked');
});

How do I implement a keyup function with a dynamically create input element with JQuery?

I can not figure out why the following code does not work.
JSFIDDLE LINK
$(document).ready(function () {
addInput();
});
var limit = 30;
function addInput() {
var numberOfRows = $("#shipping tr").size();
var id = numberOfRows;
if (numberOfRows == limit) {
alert("You have reached the limit of adding " + limit + " inputs");
} else {
$('#shipping').append('<tr id="rate' + id + '"></tr>');
$('tr#rate' + id).append('<td></td>');
$('tr#rate' + id).append('<td><input type="text" name="rate" /></td>');
}
$('input[name=rate]').on('keyup', 'input', function () {
alert('YAY');
return false;
});
}
I am trying to assign a keyup function to the inputs that I add dynamically.
Expected output: YAY! inside a popup box
Please help!
Attach an keyup event handler to shipping table, and the event will bubble up from the input[name="rate"] to shipping table:
$('#shipping').on('keyup', 'input[name="rate"]', function () {
alert('YAY');
return false;
});
DEMO
You need to add delegation to document because its added to the document.
Example
$(document).on('keyup', 'input[name="rate"]', function () {
alert('YAY ');
});
Working Demo

Categories