josi josi - 1 year ago 93
Javascript Question

jQuery works in console not in script 'syntax error, unexpected h4'

I am getting this error

Parse error: syntax error, unexpected 'h4' (T_STRING) in //// on line 76

The line of code I am using is this:

jQuery('h4:contains("Billing Details")').text("Destination Details").addClass("destinationheading")

If I remove it from the script and enter it manually into the console it works fine. What's causing this? If it makes any difference this is in wordpress' functions file.

The function is inside of a php function which is echoing out the javascript.

The PHP function:

add_action( 'woocommerce_admin_order_data_after_billing_address', 'my_custom_checkout_field_display_admin_order_meta', 10, 1 );

function my_custom_checkout_field_display_admin_order_meta($order){

echo '<p><strong>'.__('Origin First Name').':</strong> ' . get_post_meta( $order->id, 'Origin First Name', true ) . '</p>';
echo '<script>jQuery(function(){ jQuery('h4:contains("Billing Details")').text("Destination Details").addClass("destinationheading") }) </script>';


Answer Source

You are trying to do triple-nested quotes - first single-quotes in PHP, then single&double in JS. Because of this, you end PHP string. Try escaping quote character with \''s and \"'s.

Your script is at the moment interpreted like this:

echo '...jQuery(' h4:contains("Billing Details") ').text(...)';

so PHP treats h4:contains("Billing Details") as it's own code. Escape characters instead - use this line:

echo "<script>jQuery(function(){ jQuery('h4:contains(\"Billing Details\")').text(\"Destination Details\").addClass(\"destinationheading\") }) </script>";
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download