I am trying to pass a value with jquery to the SKU input field from woocommerce that is generated dynamically when you click on the quick edit button in wp-admin/edit.php?post_type=product
, but for some reason is not pasting the value the field.
function generateRandomString($length = 10) {
$characters = '0123456789ABCDEFGHIJKMNOPQRSTUVWXYZ';
$randomString = '';
for ($i = 0; $i < $length; $i++) {
$randomString .= $characters[rand(0, strlen($characters) - 1)];
}
return $randomString;
}
function quick_edit_sku($product) {
$string = generateRandomString(); // outputs a random string correctly
?>
<script>
jQuery(document).ready(function($) {
$('.editinline').on('click', function(event) {
var sku_val = $("input[name=_sku]").val(); // checks if there is a value
var random = '<?php echo $string ?>';
if (sku_val === '') { // if SKU field is empty than apply random string. Though this doesn't work quite well, only on the second time I click quick edit it returned correct
console.log(random);
$("input[name=_sku]").val(random);
} else {
console.log('Already has value SKU value');
}
});
});
</script>
<?php }
add_filter( 'admin_footer', 'quick_edit_sku' );
Button + Firebug
http://postimg.org/image/oqdpkhqov/
The problem is that the js is fired to soon, when you click “Quick Edit” wordpress sends an Ajax request to fetch the HTML for the quick edit options, so
input[name=_sku]
doesn’t actually exist on the initial click. simply adding asetTimeout
function before adding the value will work:Also, your check
if (sku_val === '') { ... }
fails.Using
if (!sku_val) { ... }
will however work.(Tested on WP 4.1.1)