How to get jquery value from for loop in php? - javascript

I am trying to alert the text of a div which is in a for loop when it is clicked. There are many divs with same id, i want to get 3 if i click the 3rd or 2 when 2nd is clicked. How can i make it with the following code or what must i add to it? Thank you.
<? for($i=0; $i<5; $i­­++) { ?>
<div id="abc"><? echo $i ?></div>
<? } ?>
<script>
$(function() {
$("#abc").click(function() {
var thevar= $("#abc").text();
alert (thevar);
}
</script>

Just try to use a class instead of using id inside that loop,
<? for($i=0; $i<5; $i­­++) { ?>
<div class="abc"><? echo $i ?></div>
<? } ?>
<script>
$(function() {
$(".abc").click(function()
{
var thevar= $(this).text();
alert (thevar);
});
});
</script>

You should have unique ids on page. due to this $("#abc").text() always returns value for first element in matched selector. Rather use abc as class. and to refer element in current context, use $(this):
var thevar=$(this).text();

You have syntax error in your code. Missing }); . Id should be unique .
<? for($i = 0;$i<5;$i++) { ?>
<div class="abc"><? echo $i ?></div> //change
<? } ?>
<script src="http://code.jquery.com/jquery-latest.min.js"
type="text/javascript"></script>
<script>
$(function() {
$(".abc").click(function()
{
var thevar= $(this).text(); //change
alert (thevar);
});//was missing
});//was missing
</script>

Related

Retrieve The PHP variable Value of a HTMl Element Using Jquery inside a Loop

I have a strange problem. I am getting the table values using PHP MySQL using a while loop and stored them in a array. Then I am displaying it one after another in a single page.
$sql = "select * from newsfeed order by id DESC";
$result = $db->query($sql);
$posts_array = array(); // Storing the result to an Custom Array
$index = 0;
if($result->num_rows > 0)
{
while($row = $result->fetch_assoc()) {
$posts_array[$index] = $row;
$index++;
}
}
I have successfully set the $post_id of the posts on to the HTML elements using the following code.
<?php
$array_size = sizeof($posts_array);
for($i = 0; $i < $array_size; $i++){
?>
<div class='wrapper' id='wrapper'>
<div class='user'>
<!-- Some Code -->
<?php
$post_id = $posts_array[$i][id];
?>
<input type='image' name='like' id='like' width='40' height='40' src='like_btn.png' value='<?php echo ($post_id);'?> />
<?php } ?>
Now I want to take that value using Jquery and do some Database Work. I have accessed the value using the following code:
<script type="text/javascript">
function justsomething() {
alert($(this).val());
}
</script>
The problem is I am only getting the last post's id as alert() for every post rather than getting different id's .
Please help me. I am confused whether the PHP script is loading every time I click and call the justsomething() function.
Note: I can display the $post_id of every post alone without any problem.
Beacuse the id should be unique to one html element try changing your code to this :
<?php $array_size = sizeof($posts_array); for($i = 0; $i < $array_size; $i++){ ?>
<input type='image' name='like_<?php echo $i ?>' id='like_<?php echo $i ?>' width='40' height='40' src='like_btn.png' value='<?php echo $post_id;?>' onclick='justsomething(this);' />
<?php } ?>
<script>
function justsomething(el) {
var img = el;
alert(img.value);
}
</script>
here is an example
function justsomething(el) {
var img = el;
alert(img.value);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type='image' name='like_1' id='like_1' width='40' height='40' src='like_btn.png' value='15454' onclick='justsomething(this);' />
It works for loop, I hope You can make use of it
$("input[id=like]").each(function(i){
alert($(this).val());
});
It will alert values from every <input id="like"...
Try this code:
onclick='justsomething(this)'
function justsomething(obj) {
alert($(obj).val());
}

onClick echo PHP code to div (AJAX)

So what I'm trying to do is the following:
first: When the button add-location is clicked this loads a php file using AJAX.
jQuery
$('.add-location').click(function() {
var locationName = $(this).data('location');
$.post('http://www.example.com/reload-location-2.php?addparam',
{locationName: locationName}, function(data) {
$("textarea#location").html(data);
})
});
PHP FILE
<?php start_session();
$locationName = array_key_exists('locationName',
$_POST) ? (string) $_POST['locationName'] : '';
if(isset($_GET['delparam'])){
unset($_SESSION['locations'][$locationName]);
}
if(isset($_GET['addparam'])){
$_SESSION['locations'][$locationName] = $locationName;
}
?>
<?php foreach ($_SESSION['locations'] as $location): ?>
<?php echo htmlspecialchars($location); echo "\n"; ?>
<?php endforeach;?>
This all works like a charm! No worries here. No what I'm trying to do is when the button add-location is clicked this echo's the following code to a div called textarea#thema.
<?php foreach ($_SESSION['products'] as $product): ?>
<?php echo htmlspecialchars($product); echo "\n"; ?>
<?php endforeach;?>
OR, if that's easier when the page is loaded -> echo that code to the textarea#thema div.
I do not understand AJAX that much but I'm getting there. But I think the last option maybe the easiest solution?
Could anyone help me figure this one out?
What I tried
Right now, When the button add-location is clicked I reload a previous jQuery script:
$('.add-location').click(function() {
var productName = $(this).data('product');
$.post('http://example.com/reload-2.php?addparam',
{productName: productName}, function(data) {
$("textarea#thema").html(data);
})
});
This works, but it adds an extra <p>-tag leaving me with a line break in the code.
I also changed the .html(data); to .val(data); for the textareas. Also I made a new PHP file with just this code:
<?php foreach ($_SESSION['products'] as $product): ?>
<?php echo htmlspecialchars($product); echo "\n"; ?>
<?php endforeach;?>
And this jQuery code:
$('.add-location').click(function() {
var productName = $(this).data('product');
$.post('http://www.example.com/reload-3.php',
{productName: productName}, function(data) {
$("textarea#thema").val(data);
})
});
But still no go... And I don't think this is the way to go?? I hope I gave enough information.
You should use .val() function to fill textarea, not .html().

how to get next element by java script

I would like to get next element:
<script>
function editMediaInfo(mediaID){
var x = document.getElementById(mediaID);
alert(x.nextElementSibling.id);
}
</script>
<?php
$x = 1;
echo "<ol>";
while($x <= 5)
{
echo "<li id={$x}> item {$x} </li>";
$x++;
?>
<button onclick="editMediaInfo('<?php echo $x; ?>')">Click</button>
<?php
}
echo "</ol>";
?>
When i click it gives me an alert without nothing. I would like to get the id of the next element.
It appears you are using an incorrect Javascript function. Use nextSibling function. Replace nextElementSibling with nextSibling. I provided a sample below.
<script>
function editMediaInfo(mediaID){
var x = document.getElementById(mediaID);
alert(x.nextSibling.id);
}
</script>
Where I found and tried the solution was here. I would recommend using this site for help on Javascript in the future.
Simply Use :
document.getElementById(mediaID).nextElementSibling.nextElementSibling.id

In PHP code on clicking a link javascript function call

<?PHP
$result = mysql_query($query);
$finalval=0;
while($row = mysql_fetch_array($result))
{
$finalval=$finalval."<a onClick='showContent("please display")'
href='#' >". $row['Title'] ."</a> <br>" ;
}
echo $finalval;
?>
<script language="javascript" type="text/javascript" >
function showContent(value)
{
alert value;
}
</script>
Guys please help me out and please please tell me in a php code on clicking link how to call javascript/ajax function..Thank you so much
try alert(value) instead of alert value
Try this one ,opening double quotes within double quotes you need to escape them \
$finalval=$finalval."<a onClick='showContent(\"please display\")'
href='#' >". $row['Title'] ."</a> <br>" ;
}
<?PHP
$result = mysql_query($query);
$finalval = 0;
while ($row = mysql_fetch_array($result)) {
$finalval = $finalval."<a class='show-content' data-value='please display' href='#' >". $row['Title'] ."</a> <br>" ;
}
echo $finalval;
?>
With javascript querySelectorAll get all a links with class selector then handle them
<script language="javascript" type="text/javascript" >
var element = document.querySelectorAll(".show-content");
for (var link in element) {
element[link].onclick = function() {
showContent(this.getAttribute('data-value'));
};
}
function showContent(value){
alert(value);
}
</script>
with jQuery it is pretty stright forward,
<script language="javascript" type="text/javascript" >
$(document).ready(function(){
$("a.content").on('click', function(){
alert($(this).data('value'));
// or make a specific function call
});
});
</script>
Hope this will help you, and do not forget to escape the special charactors as mentioned by M Khalid Junaid

retrieve value of input

I have this:
<?php $i=0;?>
<?php foreach($x as $y): ?>
<input type="hidden" id="theid<?php echo $i;?>" value="<?php echo $someVariable;?>"/>
<?php $i = $i + 1; ?>
<?php endforeach; ?>
I need to get the value of each "theid" like this:
<script type="text/javascript">
function somefunction(element, optionTitle) {
var num = document.getElementById('theid').value;
...
</script>
How can i do that considering the fact that "theid" has the $i added?
Thanks.
If you have multiple input fields and you want to do the same action on several, you could use getElementsByClassName instead of getElementById:
PHP
<input type="hidden" class="theclassname" id="theid<?php echo $i;?>" value="<?php echo $someVariable;?>"/>
JS:
<script type="text/javascript">
function somefunction(element, optionTitle) {
var myEles = document.getElementsByClassName('theclassname');
// loop over myEles and act on each one
for (var i=0; i < myEles.length; i++) {
alert("Input with id: " + myEles[i].id + " has value: " + myEles[i].value);
}
}
</script>
I would recommend using jQuery, jQuery selectors support wildcards:
$('input[id^=theid]')
See http://api.jquery.com/category/selectors/ for further reading on this topic.
If you are using jQuery would be easy like this:
$('input[id^="theid"]').each(function () {
console.log($(this).val()); //value of each theid
});
Here is a jsBin.

Categories

Resources