jquery multiple id selector - php

I have the following code.
<html>
<head>
<title>Insert and Show Records using jQuery Ajax and PHP</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script>
$(function(){
//insert record
$('#tagid').click(function(){
//var idis = $('#tagid').val();
var idis = document.getElementById("tagid").name;
alert(idis);
//syntax - $.post('filename', {data}, function(response){});
$.post('test2.php',{action: "insert", tagidis:idis},function(res){
$('#result').html(res);
});
});
});
</script>
</head>
<body>
<?php
$key = 1;
echo "<input type=\"checkbox\" name=\"".$key."\" id=\"tagid\"";
echo " style=\"width: 20px; height: 20px;\">";
$key = $key+1;
echo "<input type=\"checkbox\" name=\"".$key."\" id=\"tagid\" style=\"width: 20px; height: 20px;\">";
?>
<p>Result:</p>
<div id="result"></div>
</body>
</html>
When I execute it, where $key =1, it does the alert and shows 1.
But when I select the second checkbox, it does not show the alert.
How in jquery do I have it listening for ALL the checkboxes with the id "tagid" instead of just the first?

you should add a class to the inputs and use a class selector like $(".myClass")

id attribute is unique.
From the JQuery Documentation:
Each id value must be used only once within a document. If more than one element has been assigned the same ID, queries that use that ID will only select the first matched element in the DOM.
This is why it only works for you for the first one.
You should use class selectors instead.

Related

change page HTML after change dropdown

I have 2 pages and the main page. the total 3 pages.
I want to access the first and second pages after changing the dropdown list.
I try this code by Jquery in my HTML called main.html.
<html>
<head>
<link rel="stylesheet" href="style.css">
<script src="https://code.jquery.com/jquery-git1.min.js"></script>
<script>
$(document).on('change','.fx',function(){
document.getElementById('content').src = "firstpage.html";
document.getElementById('content').style.display = "block";
});
</script>
<style>
iframe{
height:700px;
width:700px;
display:none;
}
</style>
</head>
<body>
<select name="fx" class="fx">
<option value="empty"></option>
<option value="firstPage">1</option>
<option value="secondPage">2</option>
</select>
<iframe src="firstpage.html" id="content" >
</iframe>
</body>
</html>
I want to use the if statement.
If select 1 load firstPage.html
If select 2 load secondtPage.html
Any Edition of this code.
Please note that values and file names are case sensitive, so 'firstpage' and 'firstPage' are not the same!
Try this jQuery code:
$(document).on ("change", "select.fx[name='fx']", function () {
var $select = $(this);
if ($select.val () == "firstPage") {
$("#content").attr ("src", "firstpage.html");
$("#content").show ();
}
else if ($select.val () == "secondPage") {
$("#content").attr ("src", "secondpage.html");
$("#content").show ();
}
else {
$("#content").hide ();
alert ("Page not found!");
}
});
Don't do things like this as it may be unsafe:
$("#content").attr ("src", $(this).val() + ".html");
Whenever the change handler is called, it gets passed an event with relevant information about the event itself. It includes a event.target.value property which you can use to get the option that was clicked. You can just add '.html' to the value and set the src of your iframe accordingly.
<script>
$(document).on("change", ".fx", function (event) {
document.getElementById("content").src = event.target.value + ".html";
document.getElementById("content").style.display = "block";
});
</script>

apply jquery slidetoggle to results coming from a while in php

The following piece of code in php, uses a while statement to output variable $the_job_id. For each of the output I want to apply jquery slidetoggle. The problem is that in my code slidetoggle works only for the first output of my while. Not working for the rest. Any idea how i should modify my code in order slidetoggle to work for each of my while outputs?
This is my php code:
<?php
$result = mysql_query("select * from `user_job` where `job_id` IN ($all_saved_job_id) ");
while($run_job = mysql_fetch_array($result)){
$the_job_id = $run_job['job_id'];
echo"<div id='flip'> PRESS TO SLIDE </div>";
echo" <div id='panel'> $the_job_id </div>";
}// end while
?>
this is my script :
<script>
$(document).ready(function(){
$("#flip").click(function(){
$("#panel").slideToggle("slow");
});
});
</script>
this is my css :
<style>
#flip{
cursor:pointer;
margin-left:100px;
}
#panel{
padding:0px;
display:none;
}
</style>
id must be unique, otherwise you'll always get the first element in the page with duplicated id, so you need to use class instead:
echo"<div class='flip'> PRESS TO SLIDE </div>";
echo" <div class='panel'> $the_job_id </div>";
then you can use . to target elements by class name:
$(document).ready(function(){
$(".flip").click(function(){
$(this).next().slideToggle("slow");
});
});
Please note that you also need to change your CSS selector using . instead of # accordingly.

PHP While Loop and jQuery

I have created a while loop that selects random images from from my server and posts it. Now I want to add some jquery code and allow me to click on one of the images and run the slideUp() function in jQuery. Here is my problem. I can click on the first image produced in the while loop but when I click on the second image nothing happens. The slideUp() function does not work. I don't know what to do. Here is the code below.
<script src="http://code.jquery.com/jquery-latest.js"></script>
<?php
$num_dresses = dress_count ();
$i=0;
while ($i < 2){
?>
<style>
div:hover { border:2px solid #021a40; cursor:pointer;}
</style>
<script>
$("div").click(function () {
$(this).slideUp();
});
</script>
<?php
$rand_id = rand(1, $num_dresses);
$dress_feed_data = clothing_data($rand_id, 'file_name', 'user_defined_name', 'user_defined_place' , 'user_who_uploaded', 'match_1');
$new_file_name = $dress_feed_data['file_name'];
if (file_exists('fashion_images/' . $new_file_name)){
echo str_replace("|", " ", $dress_feed_data['user_defined_name']);
?>
<br>
<div>
<img src=" fashion_images/<?php echo $new_file_name;?> " width="50" height="50" />
<div>
<br><br>
<?php
echo str_replace("|", " ", $dress_feed_data['user_defined_place']);
?>
<br><br>
<?php
}
$i++;
}
?>
You are binding the click handler to the elements before the elemnts are inserted into DOM,
Probably when the first call is made no elements called div are there so the binding goes to void, then the first element gets inserted.
Now the binding for second element is made, now it gets attached to first one as it matches $('div') . So you got only forst one working.
The clean way is to take the click binding out of while loop, so that it happens only once, and call it on DOM ready event
<script>
$(document).ready(function(){
$("div").click(function(){
$(this).slideUp();
});
});
</script>
And if you want to make a live binding, which applies to all dynamically added images as well use delegation:
<script>
$(document).ready(function(){
$('body').on('click',"div",function(){
$(this).slideUp();
});
});
</script>
If you are posting the above images with html to a host/parent page, just add the above delegation logic to parent page, and post only the images.
Try this :
<style>
div:hover { margin:10px 0; border:2px solid #021a40; cursor:pointer;}
</style>
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script>
$(function(){
$("div.randomImage").click(function() {
$(this).slideUp();
});
});
</script>
<?php
$num_dresses = dress_count();
$i=0;
while ($i < 2) {
?>
<?php
$rand_id = rand(1, $num_dresses);
$dress_feed_data = clothing_data($rand_id, 'file_name', 'user_defined_name', 'user_defined_place' , 'user_who_uploaded', 'match_1');
$new_file_name = $dress_feed_data['file_name'];
if (file_exists('fashion_images/' . $new_file_name)) {
echo str_replace("|", " ", $dress_feed_data['user_defined_name']);
?>
<div class="randomImage">
<img src="fashion_images/<?php echo $new_file_name;?>" width="50" height="50" />
</div>
<?php
echo str_replace("|", " ", $dress_feed_data['user_defined_place']);
}
$i++;
}
?>
Notes:
Stylesheet and script moved outside the php while loop. Repetition is unnecessary and undesired.
jQuery statement now inside a $(function(){...}) structure to ensure it runs when the ducument is ready, ie. after the served HTML has been interpreted by the browser to create DOM elements.
class="randomImage" added to the <div>
Second <div> changed to </div>
For readability of source and served page, the PHP and HTML are indented independently.
I've not tried to verify the PHP.

Google search like text box

am want to create a text box like google search text box...
What i have tried is When entered a character, using AJAX the words starting with that word will be displayed in a div its working fine but i want that it should work exactly like google search box.. Now the arrow keys are not working only by clicking the text will be selected
MY CODE
<style>
#resultDiv {
width:154px;
position:absolute;
left:121px;
top:30px;
}
p {
padding:0px;
margin:0px;
}
#resultDiv p:hover {
background-color:#999;
}
</style>
<script type="text/javascript">
$(document).ready(function(e) {
$('#resultDiv p').live('click',function(){
var value = $(this).text();
$('#word').val(value);
});
});
</script>
</head>
<body>
<form action="" method="post">
<label>Enter Your Word </label><input type="text" id="word"/>
<div id="resultDiv"></div>
</form>
<script>
// prepare the form when the DOM is ready
$(document).ready(function() {
$('#word').keyup(function(e) {
$.ajax({
type: "POST",
url: "googleDropSearch.php",
data: "word="+this.value,
success: function(msg){
$('#resultDiv').html(msg);
$('#resultDiv').css('border-left','1px solid #ccc').css('border-right','1px solid #ccc').css('border-bottom','1px solid #ccc');
}
});
});
});
</script>
</body>
</html>
ACTION PAGE
<?php
$connection = mysql_connect('localhost','root','') or die("ERROR".mysql_error());
$connection = mysql_select_db('ajax',$connection) or die("ERROR".mysql_error());
if(!empty($_POST)):
if(isset($_POST['word']) && $_POST['word'] != ''):
/****************
Sanitize the data
***************/
$key =$_POST['word'];
$query = mysql_query("SELECT county FROM fl_counties WHERE county LIKE '$key%';");
$rows = mysql_num_rows($query);
if($rows != 0):
while($result = mysql_fetch_array($query)):
echo "<p>".$result[0]."</p>";
endwhile;
endif;//rows > 0
endif;//county not sent
endif;
?>
There is one useful plugin available in jquery.
Jquery Autocomplete
There is simple demo available you just have to pass an array to it.
Hope this would work for you.

How to Submit and Display on the same page using jQuery and MySQL?

Goal:
Create a Q&A Script (using PHP, JavaScript and jQuery) that enables users to ask questions and submit answers to said questions.
If the user submitted a new answer, that answer would be inserted into the database and the div containing the answers would be refreshed automatically to include/view that newly submitted answer.
Problem:
After submitting the answer, the submission process is not working.
Here is my code:
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script language="JavaScript">
$(document).ready(function ()
{
/*Function # 4:
Hide the AnswerForm and show Answers where the div will be automatically refreshed upon answer submission. <>>>> REVIEW!!! */
function addAnswer(i,qID)
{
//alert("newanswer-q"+i);
//$("newanswer-q"+i).style.display("none");
//$("Answers-q"+i).style.display("block");
changeDiv("Answers-q"+i, "block");
//step # 1: define posted data to insert into database
var name = $("input#name").val();;
var answer = $("input#answer").val();;
alert(name+","+answer);
//step # 2: submit form to be processed by CHANGE.PHP to insert into DB
$.ajax({
type:"POST",
url:"change.php",
data: "questionID="+qID+"&count="+i+"&name="+name+"&answer="+answer,
success: function(data)
{
if(data==0)
{
alert("YEEEEEEEEEESSSS!!!!!! :DDDDDD");
$("#Answer-q"+i).html("Finally!");
}
else
{
$("#Answer-q"+i).html("?!?!");
}
}
});
//Step # 3: refresh Answers div
//changeDiv('Answers-q'+i, 'block');
$("#Answers-q"+i).load("printAnswers.php");
}//end addAnswer
$("#refreshAnswers").click(function(evt){
$("#refreshAnswers").load("printAnswers.php");
evt.preventDefault();
});
}
</script>
<style type="text/css">
.answers
{
background-color: red;
position: relative;
display: block;
left: 1in;
}
.answerform
{
background-color: yellow;
position: relative;
display: block;
left: 1in;
}
.error
{
color: red;
display:none;
}
</style>
</head>
<body>
<?php
mysql_connect("#", "#", "#") or die(mysql_error());
mysql_select_db("test") or die(mysql_error());
$q1 = "SELECT *
FROM questions";
$allQ = mysql_query($q1);
while($q = mysql_fetch_array($allQ))
{
$i = $q['qID'];
echo '<div id="questions" style="background-color: blue;">';
echo 'Question: '.$q['Question'].'<br><br>';
echo 'posted by '.$q['userName'].'<br><br>';
echo 'posted on '.$q['addDate'].'<br><br>';
echo '</div>';?>
<input type="button" id="viewAnswers" name="viewAnswers" value="View Answers" onClick="changeDiv('Answers-q<?=$i?>', 'block');">
<input type="button" id="addAnswer" name="addAnswer" value="Answer Question" onClick="changeDiv('newanswer-q<?=$i?>', 'block');">
<div id="Answers-q<?=$i?>" class="answers">
<? include("printAnswers.php"); // display all answers to question # i
?>
</div>
<? echo '<div id="newanswer-q'.$i.'" class="answerform">';
include("addAnswerForm.php"); // display add new answer to question # i
echo '</div>';
} ?>
<br>-------------------------<br>
Go back to index.php
</body>
</html>
Change.php
<?php
mysql_connect('#', '#', '#') or die(mysql_error());
mysql_select_db('test') or die(mysql_error());
// Get values from form
$name=$_POST['name'];
$answer=$_POST['answer'];
$qID = $_POST['qID'];
// Insert data into mysql
$sql="INSERT INTO answers(Answer, userName, qID)
VALUES('$answer', '$name','$qID')";
$result=mysql_query($sql);
?>
I have been stuck on this for a couple of hours now with no luck thanks to my beginner-level skills in both PHP and jQuery.
Can anyone throw me a lifeline or something?
What's the value of data? Try console.log(data) in your success function. Seems to me change.php doesn't produce any output, so why should data equal zero ?
Your data appears to be sent via "GET" request.
Change te AJAX data object to this:
data : {
questionID : qid,
count : i,
name : name,
answer : answer
}
If you pass it as a string the way you did, it gets appended to the URL (becoming a GET request), if you pass it as an object it gets posted.

Categories