Link to home
Start Free TrialLog in
Avatar of Crazy Horse
Crazy HorseFlag for South Africa

asked on

update field on focusout

I seem to have 2 problems here. Firstly, the updating... text shows on the first row of the table always, instead of showing on the row where I am actually editing the textfield.

Secondly, the edit works the first time around but if I go back to the page and edit again, then go back to the page ,it has copied the record above it for some reason. I don't understand why.

$(document).ready(function(){
			
			$(document).on('focus', '.data[name="category"]',function() {
				var tr = $(this).closest('tr');
				var id = $(this).attr('id');
				var category = $(this).val();
				
				$(document).on('focusout', '.data[name="category"]', function(){
					var newName = $(this).val();
					if(newName!=category){
						$.ajax({
							
							url: "updatecat.php",
							type: "POST",
							data: {
								id: id,
								newName: newName
							},
							beforeSend: function() {
								$('#status').html("updating...");
							},
						});
						
					} 
					 

				});
				   
			}); 
				
		}); 

Open in new window




if($_POST['newName'] && $_POST['id']) {
	
	$stmt = $link->prepare("UPDATE `voucher_categories` SET `category_name` = ? WHERE `cat_id` = ? LIMIT 1");
	$stmt->bind_param("si", $_POST['newName'], $_POST['id']);
	$stmt->execute();
	$stmt->close();
	}

Open in new window

Avatar of Ray Paseur
Ray Paseur
Flag of United States of America image

Please post the HTML markup associated with this question, thanks.

As a general rule, when you have a jQuery question, it helps if we can see HTML, CSS, and JavaScript at the same time.
Avatar of Crazy Horse

ASKER

Apologies,

html:

<tr>
<td id="status"><input id="{$pid}" class="data" type="category" name="category" value="{$categoryName}"></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td><a> <i class="pe-7s-trash" id='$pid'></i> </a></td>
</tr>

Open in new window


The css is just to hide the borders around the textfields:

input[type=category] {
	border: none;
	width: 300px;
	background: none;
}

Open in new window


      
		$(document).ready(function(){
			
			$(document).on('focus', '.data[name="category"]',function() {
				var tr = $(this).closest('tr');
				var id = $(this).attr('id');
				var category = $(this).val();
				
				$(document).on('focusout', '.data[name="category"]', function(){
					var newName = $(this).val();
					if(newName!=category){
						$.ajax({
							
							url: "updatecat.php",
							type: "POST",
							data: {
								id: id,
								newName: newName
							},
							beforeSend: function() {
								$('#status').html("updating...");
							},
							
							  success: function(result) {
							 swal("Updated!", "Category successfully updated.", "success");
							  },
						});
						
					} 
					 

				}); 
				   
			}); 
				
		}); 

Open in new window

Feels like we are still working with fragments of an application here.  Example:
$('#status').html("updating...");

Open in new window

This line of code tells jQuery to find the div with id="status" and replace its HTML with "updating..." but there is no <div id="status" /> tag in the HTML.

Maybe if you can just tell us in plain language what you're trying to do, we could help find an example that demonstrates the design.
Or, check that... Maybe the <td id=status" is what jQuery will find.

In any case, unless the value in newName does not equal the value in category, the AJAX request will not run.
ASKER CERTIFIED SOLUTION
Avatar of Ray Paseur
Ray Paseur
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
status in the html I posted in my previous post in this line:

<td id="status"><input id="{$pid}" class="data" type="category" name="category" value="{$categoryName}"></td>

Open in new window



What I am trying to do is list a set of records which I am doing with php looping through records in the database. I am using heredoc to display them:

$showcat = <<<EOD
		
<tr>
<td id="status"><input id="{$pid}" class="data" type="category" name="category" value="{$categoryName}"></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td><a> <i class="pe-7s-trash" id='$pid'></i> </a></td>
</tr>
		
EOD;
echo $showcat;

Open in new window


All the records are in text fields but I am hiding the borders with css so that they don't look like text fields. If I click on any text of the displayed records I can obviously type something else in or edit the text because they are in fact text fields. When i click outside of the text field or press tab on my keyboard the record should update. The word "updating..." must also show when you perform this action. The sweet alert then shows up once completed and that particular record should be updated in the database.
Thanks for the console log. Something strange is happening. If I edit a record and hit tab on the keyboard it works okay as long as it's the last record and it can't tab into another field. It also works if I click out of all the fields somewhere else on the page. If I click on any other field though after altering text in a field, console log shows that the record I initially tried to update copies the data from whatever field I click into next, and then gets stuck in some sort of loop as every time I close the alert, it does it again and again and again.
Avatar of leakim971
you create a new onfocus each time you focus the object, it's not good.
change your logic, for example save initial/last value of your textbox and compare it when focusout/blur
Else, the easy fix would be to use jQuery.one instead jQuery.on for your focusout part :
$(document).ready(function(){

	$(document).on('focus', '.data[name="category"]',function() {
		var tr = $(this).closest('tr');
		var id = $(this).attr('id');
		var category = $(this).val();

		$(document).one('focusout', '.data[name="category"]', function(){ // We use jQuery.one instea jQuery on
			var newName = $(this).val();
			if(newName!=category){
				$.ajax({
					url: "updatecat.php",
					type: "POST",
					data: {
						id: id,
						newName: newName
					},
					beforeSend: function() {
						$('#status').html("updating...");
					},
					complete: function() {
						$('#status').html(""); // fire after success or error, what do you think ?
					},
					success: function(result) {
						swal("Updated!", "Category successfully updated.", "success");
					}
					error: function() {
						swal("Error!", "Category NOT updated!!!!", "error"); // also three lines to save time :D
					}
				});
			} 
		}); 
	}); 

}); 

Open in new window

Okay, great! Using one instead of on helped with my problem but only if I changed it on my code. If I copy and paste your code nothing works. The database record is not updated, the status message doesn't show and sweet alert never fires. My code is working now expect that the updating text still always shows in the first record row instead of the row I am actually updating.

      
	$(document).ready(function(){

    $(document).on('focus', '.data[name="category"]',function() {
        var tr = $(this).closest('tr');
        var id = $(this).attr('id');
        console.log(id);
        var category = $(this).val();
        console.log(category);

        $(document).one('focusout', '.data[name="category"]', function(){
            var newName = $(this).val();
            console.log(newName);
            if(newName != category){
                $.ajax({
                    url: "updatecat.php",
                    type: "POST",
                    data: {
                        id: id,
                        newName: newName
                    },
                    beforeSend: function() {
                        $('#status').html("updating...");
                    },
                    success: function(result) {
                       swal("Updated!", "Category successfully updated.", "success");
                    }
                });
            }
        });
    });
});

Open in new window

cool, for a sure typo in mine as I write it on the fly...
So, the million dollar question is...

How do I get this to show on the actual row I am updating?

 $('#status').html("updating...");

Open in new window

SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Seems like the tab key would trigger Out-of-focus for the current position and In-to-focus for the next position, right?

How many fields have id="status" after you've created the record display with HEREDOC.  If it's more than one, the outcome is probably unpredictable.
Okay, it's working now! :)

Not sure how to split the points though because you were both really helpful.
I believe Sir Paseur pointed the issue from the beggining (the fact you're overwritting the textbox) so why not 50/50 ?