How to get looped input value specifically using Jquery - php

del_id = $('.button').attr('rel');
alert(del_id)
PHP:
while ($row=mysqli_fetch_assoc($rs)) {
?>
<div class="itemsin" >
<span data-toggle="confirmation" rel="<?php echo $row['id']?>" class="button" id="rmlb">Click to Remove </span>
</div>
<?php
}
}
?>
I tried this but it's alerting only the first value out printed by loop please give me a suggestion

First of all, please post corrected and formatted code in future.
Here is what you need:
Collected all PHP output data in an JS array or object
Create a loop in JS to print all array values.
You need to be carefull with alerting each value because it will give a you a popup box for each array item and the annoying popup will never finish. I suggest outpoint them in console to see the result.
Your JS Code:
del_id = document.querySelectorAll (".button");
for(var i = 0; i < del_id.length; i++){
attrValue = $(this).attr('rel');
console.log(attrValue);
//You can also alert it if you wish to:
//alert(attrValue);
}

Related

PHP/JSON Array display values based on dropdown selection

Having a difficult time trying to suss this out. I've searched through, but I'm not sure if the phrase I'm using to search is correct or not.
I have a JSON file that I'm using to bring in an array of data from an outside source. Using PHP, I decode the contents. I've created a dropdown box that will display the keys, but what I'm looking to do now is dynamically populate a printout with the different values that the keys are attached to based on what the select box has selected.
<?php
// JSON string
$json = file_get_contents("showrace.json");
$races = json_decode($json, true);
?>
<select id="raceSelect">
<option value="select one" selected>Select One</option>
<?php foreach($races as $key => $value) { ?>
<option value="<?php echo $key ?>"><?php echo $value['race'] ?></option>
<?php } ?>
</select>
<div id="template">
Str Plus: # Dex Plus: # Wis Plus: # Int Plus: #<br>
</div>
And here is a sample of what the JSON file looks like:
{
"Ithorian":{"price":0,"wis":3,"str":2,"lck":0,"int":2,"frc":0,"dex":-2,"con":2,"cha":-3,"app":"No","hp":1200,"ac":0,"race":"Ithorian","lang":"ithorian"},
"Weequay":{"price":1000,"wis":-2,"str":3,"lck":0,"int":-2,"frc":0,"dex":0,"con":2,"cha":-3,"app":"No","hp":1350,"ac":0,"race":"Weequay","lang":"weequay"}
}
In the first snippet, the #'s in the template div will be outputs for the JSON values such as "str" and "dex" and such. While I was able to find out how to set the select to draw in the keys from the JSON, I am baffled at how to populate the template portion with the corresponding values, based off of the selected item.
Thanks in advance!
This may help you get started, as it is not fully fleshed out for everything. But it covers some basics you could use.
First off you would want an onchange handler in your jquery. This will fire off everytime someone changes their choice with the :
$("#raceSelect").change(function(e){
// magic will go here (see further below)
});
// or
$("form").on("change","#raceSelect",function(e){
// magic will go here (see further below)
});
Next up you would want to have access to all that json data in your jquery area to use for displaying those values based on what they chose:
<script>
// define this in your php page output near the top
// or within your jquery .ready block
var jsonData = <?PHP echo $json;?>;
</script>
Now you are ready to do some of the magic with the onchange. Accessing the right array in the jsonData, with the id chosen, you can swap out spans and divs to your hearts content. A combined example is as follows:
<?PHP
// your php script
$json = file_get_contents("showrace.json");
$races = json_decode($json, true);
?>
<!-- your form here as you have it in your example -->
<div id="template">
Str Plus: <span id="dat_str">#</span> Dex Plus: # Wis Plus: # Int Plus: #<br>
</div>
<script>
$( document ).ready(function() {
// this is your jquery .ready block
var jsonData = <?PHP echo $json;?>;
$("form").on("change","#raceSelect",function(e){
var race = $(this).val();
$("#dat_str").html( jsonData[race].str );
// you can set the dex, and wiz, etc as well
// following the same format to assign
});
});
</script>
Disclaimer: I hand typed this out, and didn't vett or test it. Its purely an example of pieces that should hopefully help you out.
you can do it using JS
var raceSelect = $('#raceSelect').find(":selected").text();
and check out this link on how te select from json
then print what you want
select from json

pass variable inside a php loop and jquery

hi guys i need another idea how to make this happend i got a loop on my script that shows id for each member and i want to pass a variable for each member this is an example
<?php
$loopvalue = $playerCount;
$i=1;
while ($i <= $loopvalue) {
$uid = $data['players'][$i-1]['avatar']['userId'];
?>
<input class="user_id_imput" type="hidden" name="id" value="<?php echo $uid;?>" />
<?php echo $userName;?></span>
<?php
$i++;
};
?>
and using jquery to show the variable with this
$(".Send_user_id").click(function() {
var uid = $(".user_id_imput").val();
console.log('id: ' + uid );
});
normaly i do this when not using a loop bu in this case i cant think of a diferent way to do it
using this will give me the id of the first result for all the results any idea how i can pass the id var for each result?
thanks for you help
Assuming that your <a> tag and <input> tags are back to back; you can use following approach:
$(".Send_user_id").click(function() {
var uid = $(this).prev(".user_id_imput").val();
console.log('id: ' + uid );
});
$.prev() Get the immediately preceding sibling
thanks for the help you gave me an idea instead of using the input using data-id to pass the variable
so the result code will be
php
<a data-id="<?php echo $uid;?>" href="#" class="Send_user_id"><?php echo $userName;?></a></span>
jquery
$(".Send_user_id").click(function() {
var uid = $(this).attr('data-id');
console.log('id: ' + uid );
});

Php while loop with js variables

The plan:
Basically I have a set of clothing items stored in a table each containing "item_name" "item_id" and "item_shortcode" I want to have a link per clothing item, when the user clicks the link the item needs to be added to an array (the selected array)
I'm trying to create a javascript object based off the data I've gathered from the mySQL database, then pass that data to a function when a div is clicked to my method.
this is an example:
<?php
while($row = mysql_fetch_array($results)){
?>
<script>
var item = new Object();
item.itemName = <?php echo json_encode($row['item_name']); ?>;
</script>
<?php
echo "<div id=\"".$row['item_name']."\" class=\"choice\" onclick=\"SetSelectedChoice(item);\">";
//echo $row['item_name'];
echo "</div>";
}
}
?>
EDIT: this is just an example I'll be populating my object with lots of data, not just item_name
problem is the last object seems to be assigned to every div in while loop.
Anyone point out where I am going wrong?
Well, i honestly don't know if i really got you, but if i see it right, then you simply overwrite the item-object in every run of the while-loop.
After the last loop (after this comes the output) the variable "item" is set to the last result of the loop, so clicking on any div will return "item" - the last item of the loop.
As a solution, try to save the rows name in the div as a parameter, like
echo "<div id=\"".$row['item_name']."\" class=\"choice\" onclick=\"SetSelectedChoice(\'".$row['item_name']."\');\">";
You're redefining item on every iteration. Why not do something like this:
As per edit, you can create an item array and populate it in the loop:
<script type="text/javascript">
var objects = new Array();
</script>
<?php while($row = mysql_fetch_array($results)): ?>
<script type="text/javascript">
var item = new Object();
item.itemName = '<?php echo json_encode($row['item_name']); ?>';
objects.push(item);
</script>
<div id="<?php echo $row['item_id']; ?>" class="choice">
<?php echo $row['item_name']; ?>
</div>
<?php endwhile; ?>
then in js OUTSIDE of your loop:
$('.choice').on('click', function(){
SetSelectedChoice($(this).html());
});
function SetSelectedChoice(name)
{
for(var i = 0; i < objects.length; i ++)
{
if(objects[i].itemName == name)
{
//do something
}
}
}
NOTE: I wouldn't really recommend this kind of weird loop for comparing names. I just don't know what else you are doing with passing the name to this function. I would pass the item id or the index value and directly access an item in the array instead of a loop. Make sense?
Basically, stop using onclick. The whole world is leaning more on listeners. Secondly, no need to create an object at all. You don't seem to be using it and even if you did, you didn't put single quotes around the name like you should for strings. Thirdly, please break out of php to write html. It's just cleaner and easier. Morely, assign the item's id to the id parameter. It gets really ugly to have names and spaces in the ids of elements. And you don't really seem to need one since you don't use it in your example. None the less, I put it in there in case you wanted to access it like $(this).attr('id') in the on click listener.
But if I missed the point, perhaps you can clarify and I may update to better fit your needs

Bind event of a specific element to a specific target

i am using while loop to output data in
<p><?php echo $title;?></p></font></a><button id=show>show()</button> <button id=hide>hide()</button>
my show hide function is
$("#show").click(function () {
$("p").show('fast');
});
$("#hide").click(function () {
$("p").hide('fast');
});
$("#reset").click(function(){
location.reload();
});
now when i am clicking show hide only the first show hide loop is working and it shows/hides all the data not just the one i clicked
Change the code to use this, like so:
$(this).prev('p').show('fast');
You will need to do this in each JQuery .click section.
Edit:
Another good point which has been mentioned, you are using an ID for your element which won't allow this to work on more than one. Your new markup should look like:
<p><?php echo $title;?></p></font></a><button class="show">show()</button>
and the JQuery:
$(".show").click(function () {
$(this).prev('p').show('fast');
});
Welcome to SO. Nice to see that you have formated your first question nicely.
Few things you might want to change.
As you are going through a loop, make sure you use a counter inside the loop and add the counter to the id. This will make the id a unique identifier. Also wrap them inside a div.
$counter = 0;
forloop {
$counter++;
<div>
<p><?php echo $title;?></p></font></a><button id="show<?php echo $counter; ?>">show()</button>
</div>
}
So now your id will be unique.
Now you can write your jquery in the below way.
$("button").click(function () {
$(this).attr('id'); //not required but incase you need the id of the button which was clicked.
$(this).parent().find("p").show('fast');
});
$("button").click(function () {
$(this).parent().find("p").hide('fast');
});
Two things: 1. I think you can only have one element with one id, such as #show. If you want to reference more buttons, you should use a class, such as this: show() (as I understand the buttons are output in a loop, there will be more of them).
Second: inside your javascript code, you do $("p")... - this references all elements on the page. I think you should use $(this) and start from there, check out this article, it explains a lot: http://remysharp.com/2007/04/12/jquerys-this-demystified/
There are many ways to go at this. Here's one:
First, add the loop number to the IDs (let's say it's $i)
<p id="TITLE_<?php echo $i; ?>" style="display:none;"><?php echo $title;?></p>
<input type="button" class="show" data-number="<?php echo $i; ?>"/>
<input type="button" class="hide" data-number="<?php echo $i; ?>" />
Your functions will then be:
$(".show").click(function () {
$("TITLE_" + $(this).data('number')).show('fast');
});
$(".hide").click(function () {
$("TITLE_" + $(this).data('number')).hide('fast');
});
Of course there are ways to do it via JQUERY without the use of the $i.
Edit: To have the tags hidden on page load, either use the style=display:none as I have added in the tag above, or you can use JQuery as follows:
$(document).ready( function() {
$("p[id^=TITLE_]").hide();
// this will retrieve all <p> tags with ID that starts
// with TITLE_ and hide them
});

Javascript getElementById from php foreach loop

So I have a php foreach loop as follows,
$i = 1;
foreach($rows as $record){
<div id='ytplayer".$i++."'>
</div>");
}
and then I have javascript which uses the getElementById and it needs to get the div everytime it is looped, which would essentially be an array, but how would I do that, I know what I have below wont work, but something like this, since I know this is pretty close to how you would get this to work in php
document.getElementById('ytplayer[i]');
Here you go!
http://jsfiddle.net/epinapala/5yUAx/
Assuming that your PHP writes the following divs(one,two etc are added for example sake...)
<div id='ytplayer1'>one</div>
<div id='ytplayer2'>two</div>
<div id='ytplayer3'>three</div>
<div id='ytplayer4'>four</div>
for(var i=1; i<5; i++){
var x=document.getElementById('ytplayer'+i);
alert(x.innerHTML);
}
document.getElementById('ytplayer'+i);

Categories