I have the following javascript to format the numbers in a string.
<?php if(count($businessesArray) > 0) { foreach($businessesArray as $business) { ?>
<div id="number2"><?php echo $business["name"]; ?></div></p>
<script type="text/javascript">
$('#number2').html(($('#number2').html()).replace(/[0-9]/gi, '<big>$&</big>')) ;
</script>
<?php } } else { ?>
There is not any business added yet.
<?php } ?>
http://jsfiddle.net/wLd5E/5/
but if apply to a value in a loop it format the first record only.
Where am I wrong?
Regards:
html elements have to have a unique ID. here you use id="number2" for all the DIV elements, this way your javascript always formats the first one.
try using unique ID in the foreach to give the DIV and the JQuery selector.
you can also just use a class on these DIV elements, and then you can format the content with one line of javascript using a JQuery selector for that class, it will do the trick for all elements of that class.
Related
This question already has answers here:
trimming a string within a div
(2 answers)
How can I get the data attribute from a php variable?
(2 answers)
Closed 2 years ago.
I am attempting to call a comments section through a modal, for this purpose I need to pass a unique id along with #display_comment . It works when I hard code is such as #display_comment1, #display_comment2. I need to know how to pass the value as a variable.
I am using dom-target to pass it as variable in myData1, but it wont work. The console shows #display_comment & 1 on the next line.
<div id="dom-target" style="display: none;">
<?php
echo htmlspecialchars($test['id']);
?>
</div>
var div = document.getElementById("dom-target");
var myData1 = div.textContent;
load_comment();
function load_comment()
{
$.ajax({
url:"fetch_comment.php",
method:"POST",
success:function(data)
{
$('#display_comment'+myData1).html(data);
}
})
}
The DIV includes lots of whitespace around the ID. You need to remove that with trim().
var myData1 = div.textContent.trim();
What #barmar wrote is correct. Although I would suggest a much better approach for this. Whenever you wanna "fetch" some html data to javascript (here the data is set by PHP), you can use the data attribute in html like this:
<div id="dom-target" style="display: none;" data-id="<?php echo htmlspecialchars($test['id']);?>">
<?php
echo htmlspecialchars($test['id']);
?>
</div>
See that I've set the data attribute to the div above with the id.
Now when you wanna get this id in jQuery, you can do it with $("#dom-target").data("id"); like
var myData1 = $("#dom-target").data("id");
This gives you a much better and cleaner way to fetch data from html to javascript.
I know that similar questions have been asked on Stack Overflow many times, but I am having problems with triple nested quotes in html/php. I have looked at numerous questions, but none of the solutions that I have found are working for me. Here is what I am trying to do (this is found in a php file):
echo"<div id = 'feed-element'>
<button class='username-button' type='button'>#".$currentUsername."</button>
<button class='hashtag-one-button' type='button'>".$hashtag_one."</button>
<button class='hashtag-two-button' type='button'>".$hashtag_two."</button>
<button class='play-button' id='play-button".$i."' type='button' onclick='changeImage(this.id,\'".$track_url."\')'></button>
<button class='email-button' type='button'>Contact: ".$email."</button>
</div>";
The specific line that is causing me problems is the third to last line:
<button class='play-button' id='play-button".$i."' type='button' onclick='changeImage(this.id,\'".$track_url."\')'></button>
Anyways, when I run this code I get an Uncaught Syntax: invalid or unexpected token error. What am I doing wrong?
Why not use php heredoc and skip the hassle of escaping quotes? i.e.:
echo <<< EOF
<div id = 'feed-element'>
<button class='username-button' type='button'>#{$currentUsername}</button>
<button class='hashtag-one-button' type='button'>{$hashtag_one}</button>
<button class='hashtag-two-button' type='button'>{$hashtag_two}</button>
<button class='play-button' id='play-button{$i}' type='button' onclick='changeImage(this.id,{$track_url})'></button>
<button class='email-button' type='button'>Contact: {$email}</button>
</div>
EOF;
Note:
The curly braces are optional but may help code readability.
For your error-causing code, you need to escape double quotes, not single:
<button class='play-button' id='play-button".$i."' type='button' onclick='changeImage(this.id,\"".$track_url."\")'></button>
Because you are using double quotes, you don't need to concatenate. Just insert the variable and away you go!
echo"<div id='feed-element'>
<button class='username-button' type='button'>#$currentUsername</button>
<button class='hashtag-one-button' type='button'>$hashtag_one</button>
<button class='hashtag-two-button' type='button'>$hashtag_two</button>
<button class='play-button' id='play-button$i' type='button' onclick='changeImage(this.id,\' $track_url\ ')'></button>
<button class='email-button' type='button'>Contact: $email</button>
</div>";
For using quotes to any level in PHP/HTML, use forst level as either single or double quote. After that you have two options. 1. Use double quotes 2. Use single quotes with backslash before the quote. For example, echo "This is 'In quotes'"; or echo "This is \"In quotes\"";
In order to have multiple type of quotes on a line of code use .
Example :
echo 'It\'s me, hey';
You'e all crazy. Just end the php block and write whatever then start it up again.
Example
I want to dynamically create 3 different div elements, each one with two parameters: $ID and $TEXT which represent the dom element ID and the innerHTML.
Now to make it truely complex, I want to dynamically insert these elements into a Javascript Function, so that they will load when I call the JS function.
Here's how to do that: You simply end the PHP tag and then enter your desired content as if the PHP tag never existed, and it will parse it as if it was specified within PHP without having to escape anything
<?php
/* define regular function to generate dynamic element with PHP */
function create_my_div($ID, $TEXT) {
/* end the PHP tag and start just regularly entering code
?>
<div id='<?=$ID;?>'>
<?php print_r(htmlspecialchars($TEXT)); ?>
</div>
<?php
/* we started up the PHP tag again, followed by a } to end the function
}
?>
Now anytime we call create_my_div("someID", "some text"); with PHP it will create our DIV element.
Lets say we wanted to populate a javascript function's DIV elements server-side and put them into the Javascript Function create_my_divs()
We first would need to have a way to ensure that our DIV elements are properly escaped as mentioned in the other answers, which can be done with this PHP code:
<?php
function escapeJavaScriptText($string)
{
return str_replace("\n", '\n', str_replace('"', '\"', addcslashes(str_replace("\r", '', (string)$string), "\0..\37'\\")));
}
?>
And then finally, all we have to do is this on our web page:
<script type="text/javascript">
/* target element is where the DIVS will be created in */
function create_my_divs(target_element) {
target_element.innerHTML += "<?=escapeJavascriptText(create_my_div("DIV1", "THIS IS DIV1"));?>";
target_element.innerHTML += "<?=escapeJavascriptText(create_my_div("DIV2", "THIS IS DIV2"));?>";
target_element.innerHTML += "<?=escapeJavascriptText(create_my_div("DIV3", "THIS IS DIV3"));?>";
}
</script>
This method will allow you to include javascript code or whatever without worrying about triple nesting
Here's another use case for this method:
Dynamically adding Javascript code:
<?php
function loop_start($varName) {
?>
for (var i=0; i<<?php print_r($varName);?>.length; i++) {
<?php
}
?>
Now your Javascript code could look like this:
<script>
<?php
loop_start("myArray");
?>
console.log(myArray[i]);
}
</script>
Which would result in the following to be rendered:
<script>
for (var i=0; i<myArray.length; i++) {
console.log(myArray[i]);
}
</script>
Conclusion
Stop worrying about trying to triple escape or double escape, or even escape at all.
With the tricks outlined in this answer, you can avoid escaping all together.
(Escape the confusion if you will)
I can avoid some div elements using conditions, like
<% if (true) %>{
<div> </div>
<%}%>
can I do this on JavaScript side?
You can do it like this.
if(true){
document.getElementById("div1").style.visibility = "hidden";
}
Fiddle Demo
You can use an if/else statement to avoid specific conditions.
if (something === true ){
//target or add specific div
}else {
//bypass or remove/hide specific div
}
JS can't be used inline the way you wish in your example, but if you really need to do inline Div manipulation, you can use PHP if your server supports it. IN the following example, the div id "content" will only be added to the DOM if "somecondition" is met. Otherwise, it remains hidden (not added to the DOM).
<body>
<?php if (somecondition){ ?>
<div id="content">
Foo
</div>
<?php } ?>
</body>
I need to generate a unique ID via js or PHP. Obviously this is pretty easy, but the part I can't figure out is that I need to generate a unique id for a <p> element, and then reference that unique id in some inline js below.
Here's the code to make this more clear:
<p id="UNIQUE-ID" class="toolbox"><a class="tooltip" onmouseover="tooltip.pop(this, '##UNIQUE-ID');"></a>
Basically, in both places where it says "UNIQUE-ID", I need an identical unique id generated. There will be an unknown number of these kind of <p> and <a> pairs generated dynamically.
Any help is greatly appreciated.
You've said that the <p> and <a> pairs are generated dynamically, and also asked for a unique ID "...via js or PHP..." So I'm going to assume the dynamic generation is via PHP, in some kind of loop.
If so, just remember the value in a variable in your loop and output it in the two required locations, e.g.:
<?php
while (someCondition) {
$id = /* ...generate the ID...*/;
?>
<p id="<?=$id?>" class="toolbox"><a class="tooltip" onmouseover="tooltip.pop(this, '##<?=$id?>');"></a>
<?php
}
?>
(Obviously that's using shorttags, which many people recommend against. But it gets the idea across. If you don't use shorttags, you can easily change that to use echo instead.)
I am just giving the structure.Just change it according to your requirement
<?php
for($i=0;condition;$i++)
{
?>
<p id="par_<?php echo $i;?>" <a id="id_<?php echo $i;?>" href=""></a>
<?php
}
?>
I seem to be having problems converting some php Regex code into Javascript Regex code. The php version works flawlessly, and it was one of our fellow users, jim tollan, that wrote the php code that inspired me to write it in javascript because I need it done on the client-side. The code pulls out content between html tags based on the specified tag attribute (id, class, etc..) and the value of that attribute.
Here is the original code by jim tollan:
<?php
function get_tag( $attr, $value, $xml ) {
$attr = preg_quote($attr);
$value = preg_quote($value);
$tag_regex = '/<div[^>]*'.$attr.'="'.$value.'">(.*?)<\\/div>/si';
preg_match($tag_regex,
$xml,
$matches);
return $matches[1];
}
$yourentirehtml = file_get_contents("test.html");
$extract = get_tag('id', 'content', $yourentirehtml);
echo $extract;
?>
And here is the javascript code I've written and embedded in html file:
<script type="text/javascript">
function get_tag(attr, value, xml) {
var attr = preg_quote(attr);
var value = preg_quote(value);
var tag_regex = new RegExp('/<input[^>]*'+attr+'="'+value+'">(.*?)<\\/label>/si');
// preg_match
xml.match(tag_regex);
}
var yourentirehtml = file_get_contents("test.html");
var extract = get_tag('id', 'custom-63', yourentirehtml);
alert(extract);
</script>
I used the functions defined at phpjs.org to define both preg_quote and file_get_contents
Here is the test.html file that I'm using:
<html>
<head>
</head>
<body>
<div id="content">
<!--content-->
<p>some content</p>
<!--content-->
</div>
<label>
<input type="radio" name="testingMethod" id="custom-63">
" Radio Button Text "
</label>
</body>
</html>
When I run the php file, it works, but when I run the javascript code, the alert box shows
undefined
I want to know if my implementation of the expression in var tag_regex is correct, and if it is, is there anything in my code that is preventing me from the yielding the results I want?
I solved this problem by scrapping the idea of using regex, and I decided to go with using the DOM. It can be done rather simply by doing this:
<script type="text/javascript">
var x=document.getElementsByTagName("label")[];
// put the index of the element within the square brackets if you have more than one with the same name
// 0 is the first index
// you can also use getElementsById or getElementsByTagName
var result = x.innerText;
// you can also do x.cell[].innerText if you have more than one item within the element you found above
// 0 is the first index, and any index number should be put within the square brackets
</script>