Reputation: 53
I need to add a property to the input[name=$key]
after a control inside a PHP file
Code:
if ( !isset( $field_obj[ $key ] ) )
{
?>
<script> $('input[name=$key]').prop("data-toggle", "popover");</script>
<?php
but $key
is declared in PHP section and i can't use it inside the script section.
So how can I do it?
Upvotes: 0
Views: 178
Reputation: 3021
Try to echo $key
:
<?php
if ( !isset( $field_obj[ $key ] ) ) {
?>
<script>
$('input[name=<?= $key ?>').prop("data-toggle", "popover");
</script>
<?php
}
?>
Upvotes: -1
Reputation: 166
<?php
if ( !isset( $field_obj[ $key ] ) ) {
?>
<script>
$('input[name="<?php echo $key ?>" ]').prop("data-toggle", "popover");
</script>
<?php
}
?>
Upvotes: -1
Reputation: 5032
The bad practice that everyone keeps going on about is the practice of generating your Javascript code.
Best practice would be to have all of your JS code as static as possible, loaded in a separate .js file.
In order to get this bit of code to trigger when the PHP variable is set, you would do something like this:
In your main JS code file, you would have a block like this which runs when the page is loaded:
for(var key in window.pageConfig.keys) {
$('input[name='+key+']').prop("data-toggle", "popover");
}
This code would be loaded exactly the same every time the page loads. However, your PHP code would generate a small chunk of JS code that populates the window.pageConfig
object with the relevant data.
Your PHP code might look something like this:
$jsonKeys = json_encode(['keys'=>array_keys($field_obj)]);
print "<script>var pageConfig = {$jsonKeys};</script>";
This would produce the pageConfig
object in Javascript which the rest of your code could then use to work out which keys to process.
Note, I've made some assumptions in this PHP code; eg I'm assuming you want to run the jQuery code for every field_obj
. If that assumption is wrong, then feel free to change the code to suit, but hopefully the example I've given you will take you along the right path.
They key point here is to minimise the amount of JS code that your PHP code generates; certainly avoid generating anything other than JS data objects in PHP; the rest of your JS code should be static.
Upvotes: 0
Reputation: 1167
<script> $('input[name=<?php echo $key ?>]').prop("data-toggle", "popover"); </script>
but this is a bad practic..
Upvotes: 3
Reputation: 719
Not recommended but try this,
<?php
if ( !isset( $field_obj[ $key ] ) ) {
?>
<script> $('input[name=<?php echo $key ?> ]').prop("data-toggle", "popover"); </script>
<?php
}
?>
Upvotes: 1