Jquery - Select the div within the same container class div as this? - javascript

I'm cycling through data in a foreach loop. On each loop a container class contains the following:
foreach($resultarray AS $value){
$filename = substr($value['img_file_name'],9);
$cat_id = $value['cat_id'];
echo '<article class="post">';
echo '<div class="post_title">' . $value['post_title'] . '</div>';
echo '<div class="post_info">' .
'Category: ' . $cat_name = get_cat_name($cat_id) .'<br />'.
'Year: ' . $value['post_year'] .'<br />'.
$value['post_desc'] .'<br />'.
'</div>';
echo '<div class="link-to-post">Click to view</div>';
echo '<img class="post-thumb" src="img/thumb_/'.$filename.'" alt="MJbox Michael Jackson memorabilia thumbnail" />';
echo '<img class="cover-img" src="img/post-bg-1.png" alt="test" />';
echo '<form name="form"><input type="text" class="postid" value="'.$value['post_id'].'" /></form>';
echo '</article>';
}
I have the following div made visible with Jquery when the "lintopost" link/image is clicked.
<div id="main-post">
<div id="gotpostid">some text</div>
</div>
Currently I am using the collowing Jquery to handle when the #main-post div appears and when to get the data for that post to put inside the div.
$(".cover-img").click(function(){
$("#main-post").fadeIn(1000);
$.post("inc/fullpost.php", {postid: $('.postid').val()},
function(output){
$("#gotpostid").html(output).show();
}).fail(function(x,y,z){
$("#gotpostid").html(x + "<br />" + y + "<br />" + z)
});
});
The problem I'm having at the moment is that the value of the input "postid" is not being selected properly. How can I select it so that it gets the value form this input field and not just from the first .postid it comes across which makes the id the same for every iteration.
I hope I explained myself well enough.

1) I suggest you to use .on('click', function() {when you're going to add new elements on markup.
2) After clicking on image use .find() and .parent() to get exactly the input.

Related

Displaying products with a specific category jQuery

I have products that I'm getting through an API and I tried creating a catalog with jQuery. I'm using two different requests to get two different product categories. I created my catalog on multiple pages thanks to the slice() function on jQuery like so :
var $el = $("#wrap > div");
var pageSize = 9;
var page = 1;
$el.slice(0, pageSize).css({display: 'block'});
$el.slice(pageSize, $el.length).css({display: 'none'});
function addSlice(num){
return num + pageSize;
}
function subtractSlice(num){
return num - pageSize;
}
var slice = [0, pageSize];
This is how I am displaying the products :
echo '<div id="wrap" class="wrap">';
foreach ($beds['moreProducts']['productWindow'] as $items)
{
echo '<div class="bed_images" id="bed">';
echo '<img data-enlargeable class="images" src=' . $items['mainImageUrl'] . '?f=xxs' . '/>';
echo '<h2 class="img_title">' . $items['name'] . '</h2>';
echo '<p class="img_price">' . $items['priceNumeral'] . ' ^b ' . '</p>';
echo '<p class="img_description">' . $items['typeName'] . '</p>';
echo '</div>';
}
foreach ($sofas['moreProducts']['productWindow'] as $items)
{
echo '<div class="sofa_images" id="sofa">';
echo '<img data-enlargeable class="images" src=' . $items['mainImageUrl'] . '?f=xxs' . '/>';
echo '<h2 class="img_title">' . $items['name'] . '</h2>';
echo '<p class="img_price">' . $items['priceNumeral'] . ' ^b ' . '</p>';
echo '<p class="img_description">' . $items['typeName'] . '</p>';
echo '</div>';
}
I created a selection selector with two options to display either one or the other. I first of all tried with the .hide method but it only hides the 9 items displayed, i then tried the .remove method which seemed like working but it let me empty pages until i reach the pages on which i had my items (for example i had pages 2-23 that were empty) So i'm kinda desperate to know how can i manage to only dislay the selected category ?

jQuery change input value on div mouseover

I'm trying to change an input value using jQuery mouse over.
Scenario: I got 5 div having different colors and user names. When mouseover a div the input text change (and for color input the background color) data according to database values, when change div the text displays new data.
using PHP I echo the part of the script to handle the mouseover function
<?php
$myId = '1';
$uname = 'user1';
$ucolor = 'FFFFFF';
echo "<script>
$('$myId').mouseover( function () {
$('#uname').val('" . $uname . "'),
$('#ucolor').val('" . $ucolor ."'),
$('#ucolor').css('background-color', '" . $ucolor . "')
})
</script>";
This work if i change mouseover() to hover(), but display only the first element, if i do a mouse over the second element data doesn't change.
Try this:
Put your script after body tag:
<body>
<div class="hh" id="1"></div>
<input type="text" id="uname" />
<input type="text" id="ucolor" />
<div class="hh" id="2"></div>
</body>
<?php
$myId = '1';
$uname = 'user1';
$ucolor = 'FFFFFF';
echo "<script>
$('#$myId').mouseover( function () { // add # here
$('#uname').val('" . $uname . "'),
$('#ucolor').val('" . $ucolor ."'),
$('#ucolor').css('background-color', '" . $ucolor . "')
})
</script>";
$myId = '2';
$uname = 'user2';
$ucolor = 'FFF555';
echo "<script>
$('#$myId').mouseover( function () { console.log('fdgfdg')
$('#uname').val('" . $uname . "'),
$('#ucolor').val('" . $ucolor ."'),
$('#ucolor').css('background-color', '" . $ucolor . "')
})
</script>";
?>
In general the div or any DOM must have a unique ID value. Try using class selector(.) instead of ID selector(#).

The php value from the database is not being passed when the button is clicked

So I got most of my php and jquery working but I am currently stuggling on one thing which is how do I pass a db value in a while loop on button click to the jquery? At present nothing is being printed
<?php
...
if(mysqli_num_rows($result)){
while($row = mysqli_fetch_assoc($result)){
print
"<div class='item col-xs-4 col-lg-4'>".
"<div class='row'>".
"<div class='col-xs-10'>".
"<p class='list-group-item-text'>".
"<input type='text' class='form-control' id='usr'>".
"<button id='button' class='btn btn-success'>Calculate</button>".
"</div>".
"</div>".
"</div>";
}
}
?>
<script type="text/javascript">
$(document).on("click", "#button", function(){
var name = '<?php echo($row['name']); ?>';
alert(name);
});
</script>
Say there are like seven of these boxes and the user clicks on the fourth one - how do I get that row name, like pass that to the jquery?
Ok, we need to change a few things. Every element in the HTML DOM needs a unique id. If more than one element has the same id, the machines get very confused. This is understandable, since you're saying hey pay attention to the button with the id #button! And it's like, which one? There are 7. We can add a unique id to each button during the loop by using the id from the current row the loop is fetching from the db. NB that in HTML, element ids cannot begin with a number. That's why I used button-45,etc.
We can also change the listener to listen to a class of buttons instead of a specific button - that way if any button on the page with the right class gets clicked, the listener hears it. Using jQuery you can also add data directly to the element, and retrieve is using .data(). I've provided two variables in the javascript so you can see the results of each approach.
<?php
...
if(mysqli_num_rows($result)){
$i = 0;
while($row = mysqli_fetch_assoc($result)){
print
"<div class='item col-xs-4 col-lg-4'>".
"<div class='row'>".
"<div class='col-xs-10'>".
"<p class='list-group-item-text'>".
"<input type='text' class='form-control' id='usr-".$row['id']."'>".
"<button id='button-".$row['id']."' data-id='".$row['id']."' class='btn btn-success btn_calc'>Calculate</button>".
"</div>".
"</div>".
"</div>";
}
$i++;
}
?>
<script type="text/javascript">
$(document).on("click", ".btn_calc", function(){
var id_only = $(this).data('id'); //this gets us the id
//you can log values to the console, then right-click and inspect to see the results:
console.log("id_only = ",id_only);
//this gets the text into a variable
var text = $('#usr-'+id_only).val();
console.log("text = ", text);
//alert(text);
});
</script>
try the following
if(mysqli_num_rows($result)){
$i = 0;
while($row = mysqli_fetch_assoc($result)){
print
"<div class='item col-xs-4 col-lg-4'>".
"<div class='row'>".
"<div class='col-xs-10'>".
"<p class='list-group-item-text'>".
"<input type='text' class='form-control' id='usr_" . $i . "'>".
"<button id='button_" . $i . "' class='btn btn-success'>Calculate</button>".
"</div>".
"</div>".
"</div>";
$i ++;
}
}
You're problem is that you are trying to pass data in STRING FORMAT.
In your script you pass the $row out of while loop so it doesn't pass anything useful for you. If you have more than one button you can't use ID ATTRIBUTE but you have to use CLASS. Set a data-id attribute so you can pass the value from the database and set an ID to the input so you can take its value also. Try this:
<?php
if(mysqli_num_rows($result)){
while($row = mysqli_fetch_assoc($result)){
print
"<div class='item col-xs`-4 col-lg-4'>".
"<div class='row'>".
"<div class='col-xs-10'>".
"<p class='list-group-item-text'>".
"<input type='text' class='form-control' id='input-" . $row["id"] . "'>".
"<button data-id='". $row["id"] . "' class='mybutton btn btn-success'>Calculate</button>".
"</div>".
"</div>".
"</div>";
}
}
?>
<script type="text/javascript">
$(document).ready(function(){
$(".mybutton").on("click", function(){
var myid = $(this).attr('data-id');
var myinput = $('#input-'+myid).val();
alert("MY ID IS: " + myid);
alert("MY INPUT VALUE IS: " + myinput);
});
});
</script>

DOM does not match PHP output

I have the following PHP script:
function drawDepts(mysqli $con, $defaultDept) {
$deptQuery = "SELECT * FROM depts";
$deptResult = $con->query($deptQuery);
global $request;
echo "<select id='targetDept' width='200' style='width:200px;' onchange='updateRequest(".$request['id'].", 'targetDept', $('#targetDept').val()'>";
while ($deptRow = $deptResult->fetch_array(MYSQL_ASSOC)) {
echo "<option value='" . $deptRow['id'] . "' ";
if ($deptRow['id'] == $defaultDept) {
echo "selected='selected'";
}
echo ">" . $deptRow['name'] . "</option>";
}
echo "</select>";
}
This basically just creates a select box with options from a DB. The onchange allows the user to update the DB without re-loading the page (ajax).
The weird part is the DOM shows this (IE 11):
<select id="targetDept" style="width: 200px;" onchange="updateRequest(212, " $('#targetdept').val())'="" targetdept',="" width="200">
Specifically, why are there " , ="" and width="200px"
echoing the javascript function as text works just fine... It seems that IE is screwing up the onchange tag.
You have a syntax error on your onchange with ' and " use \ to escape the ' used within your onChange with the ''s
echo "<select id='targetDept' width='200' style='width:200px;' onchange='updateRequest(".$request['id'].", \"targetDept\", $(\"#targetDept\").val())'>";

Making .next() element slideToggle correctly with jquery?

At the moment, The code below only works for one container. I am looking to make only the description associated with that click slideToggle.
jquery:
$("#closedImage").click(function(){
$('#closedImage').css("display", "none");
$('#openImage').css("display", "block");
$(this).parent().next(".jobDescription").slideToggle("slow");
});
$("#openImage").click(function(){
$('#openImage').css("display", "none");
$('#closedImage').css("display", "block");
$(this).parent().next(".jobDescription").slideToggle("slow");
});
php/html - contents within foreach loop:
echo "<div id=\"theJob\">";
echo "<a href=\"/job/view/".$job['id']."/".$job['url']."\">";
echo "<div id=\"leftContain\" class=\"floatLeft\">";
echo "<h2 class=\"green\">".$job['role']."</h2>";
echo "<div class=\"blue floatLeft\"><h3>".$job['company']." in ".$job['location']."</h3></div><br><br>";
echo "</div>";
echo "</a>";
echo "<div id=\"rightContain\" class=\"floatLeft\">";
echo "<div id=\"closedImage\"><img src=\"/images/side.png\"></div>";
echo "<div id=\"openImage\"><img src=\"/images/down.png\"></div>";
echo "</div>";
echo "<div class=\"jobDescription floatLeft\">";
echo $job['description'];
echo "</div>";
echo "</div>";
Thanks in advance.
You're using a foreach with ids not classes. The selectors in your jquery will only return the first id it comes across, the rest will be ignored.
IDs should never appear more than once on a page and is invalid markup.
Change the IDs to classes and it should fix your issue :)
Hope this helps.
It seems like you are duplicating the ids closedImage and openImage etc in your containers. instead turn them to/add classnames and try .
$(".closedImage").click(function(){
var $this = $(this);
$this.hide().siblings('.openImage').show();; //hide and show are shortcuts to display none / block
$this.parent().next(".jobDescription").slideToggle("slow");
});
$(".openImage").click(function(){
var $this = $(this);
$this.hide().siblings('.closedImage').show();;
$this.parent().next(".jobDescription").slideToggle("slow");
});
Use ids sparingly and turn them into classes. Duplicate ids make your html invalid and selectors to fail as they will select the first one appearing in DOM

Categories