use jQuery to get text from current div - php

I have a small search engine querying the database for a list of names. The engine returns a maximum of 5 names. There is a button next to each each person's name. When the button is clicked, my jQuery code is supposed to add only that person's name to a comma separated list. Currently, it is adding every name that the engine pulls up. Im assuming I need to utilize the this command somehow. I feels as if my div isn't properly being selected.
The Question: how do you access the text of a paragraph that exists in the same class as the button?
The paragraph and button are enclosed by a class. The paragraph has a class. The button has a class.
//jQuery function to add the name to my list of names
$(document).ready(function(){
var addList = $('.addList');
$(".addCustomer").on( "click", function() {
customerToAdd = $('.addIndividual > .searched_name').text(); //here is where the problem lies. it comma separates every name
addList.val($('.addList').val() + customerToAdd + ', ');
search.val('');
});
});
And here is my html enclosed in php. This holds the fields that are used by the jQuery above.
while($state = mysqli_fetch_assoc($states)) {
$customerid = $state['id'];
$customername = $state['name'];
echo "
<div class='addIndividual' >
<p style='float:left;' class='searched_name'>".$customername."
</p>
<button type='button' value=".$customername." class='btn btn-default addCustomer'>Assign List to a Class</button>
</div>
<hr>";
}

You need to change
$('.addIndividual > .searched_name').text();
to
$(this).val();
OR if not the same as in the customer paragraph (it does seem that it is now):
$(this).closest(".addIndividual").find('.searched_name').text();
or if the paragraph stays next to the button for sure:
$(this).prev().text();

It looks like you already have the customer's name in the value attribute of the button. You can just grab it with: $(this).val().
You should also change your button to use class="addCustomer" instead of id="addCustomer". ID's are for unique elements, while a class is for multiple elements. In your case, you have a button for each customer.

Instead of $(".addCustomer").on( ... create a function like this:
function addCustomer(index){
$('.addIndividual .searched_name_'+index).text();
// continue the script ...
}
Your while loop will now look like this:
<p style='float:left;'class='searched_name_".$customerid."'>".$customername."</p>

Related

Acces mysql value in html to send to php file through jquery

I want to get the value of id so that I can delete the data from mysql based on the id number
This is a project for events, the main idea here is I want to get the id number of the event based on the clicked button, so that I can update/delete the event based on the id number.
Code for displaying details
<?php $sql= "SELECT event_name, event_date, event_id FROM events WHERE event_status=0";
$result= mysqli_query($conn, $sql);?>
while($row = mysqli_fetch_assoc($result))
{
echo '
<div class="pending-card">
<div class="pending-image">
</div>';
echo " <div class='pending-title'>
<h1>{$row["event_name"]}</h1>
</div>";
echo " <div class='pending-des'>
<p>{$row["event_date"]}</p>
<button class='choice-pending'><a href='detail.php'>Read More...</a></button>
<input style='display: none;' type='text' id='test-pend' value='{$row["event_id"]}'>
</div>
</div>
";
}
Jquery code
Here I tried to check if this works by making an alert, but after i press the button, the id number that came out is not correspond with the button i click
$(document).ready(function(){
$('.choice-pending').click(function(){
alert("Value: " + $('#test-pend').val());
});
});
Can anyone tell me where did I go wrong
Example, the event i pressed is suppose to be 34, but the alert shows 26 which is the first event id in the code for displaying details
You can use data-* attribute in your element.
Based on https://www.w3schools.com/tags/att_global_data.asp
The data-* attributes is used to store custom data private to the page
or application.
The data-* attributes gives us the ability to embed custom data
attributes on all HTML elements.
The stored (custom) data can then be used in the page's JavaScript to
create a more engaging user experience (without any Ajax calls or
server-side database queries).
The data-* attributes consist of two parts:
The attribute name should not contain any uppercase letters, and must
be at least one character long after the prefix "data-" The attribute
value can be any string Note: Custom attributes prefixed with "data-"
will be completely ignored by the user agent.
<button class="choice-pending" data-event-id="<?= $row['event_id']; ?>">Read More...</button>
Then in your script you can access the clicked button:
$(".choice-pending").click(function() {
if($(this).attr('data-event-id') !== undefined) {
// You can do ajax call here to your detail.php
// Or you can simply create a hidden field inside your form, assigned the data-event-id value to it, then $("form").submit();
} else {
/** Error message here, maybe? */
}
});
First remove your anchor tag inside button and use only anchor or button and print your html with assign some dynamic class or id into each to make them unique like this.
<div class='pending-des'>
<p>{$row["event_date"]}</p>
<a class='choice-pending-{$row["event_id"]}' href='detail.php'>Read More...</a>
<input style='display: none;' type='text' id='test-pend-{$row["event_id"]}' value='{$row["event_id"]}'>
</div>
Now bind click event on it-
$(document).ready(function(){
$('.pending-des').each(function(){
$(this).on('click', 'a[class^=choice-pending-]', function(){
alert($(this).find('input[id^=test-pend-]').val());
});
});
});

Get value from database after clicking on image

I have a query that gets the latest 10 rows in a table and loops 10 times to echo HTML that includes some of the information taken from the table, to something similar like below (pseudo code):
query = <GET 10 LATEST ROWS FROM TABLE>
$name = <ONE VALUE FROM TABLE>;
$name2 = <ANOTHER VALUE FROM TABLE>;
echo '<div class="style1">' . $name . '</div> <img src="image.png" /> <div class="style2">' . $name2 . '</div>';
What I'm having trouble with is that, if a user clicks the image, I need to run some Ajax to show another piece of HTML based on the variable $name.
The problem is that, since I'm echoing 10 rows from the table, how can I get the value of that one variable when the image is clicked?
Please help!
give each div an id based on the value of $name. and you use $name for your ajax call to get to next step.
Wrap the grouping you need.
PHP:
<div class="style-container">
<div class="style1"><?=$name;?></div>
<img src="image.png">
<div class="style2"><?$=name2;?></div>
</div>
Then you can use JS to loop through by container and get the name, no matter what the values inside may be, with or without quotes and other special characters.
JS:
$('.style-container').each( function( i, el ) {
var $el = $(el),
name = $el.find( '.style1' ).text();
$el.find( 'img' ).on( 'click', function() {
$.ajax({
url : 'whatever.php',
data : { name : name }
});
});
});
Note I would only do this if using the markup is your only option. You may want to echo out a json_encode of data inside a JS tag. Then you can iterate and use a templating engine like mustache to print out the markup. Then you could use AJAX to open a URL based on the data rather than the markup.

Create button that inserts typed value from adjacent input into URL?

I have a form that contains multiple inputs, and each input has its own respective button. I'm looking to have each button insert the adjacent input's typed value into a new browser tab and opens that address on click of the button.
Let’s say I type 121680573 into the text field, and when I click the button next to the field, this address should be opened in a new tab:
a810-bisweb.nyc.gov/bisweb/JobsQueryByNumberServlet?passjobnumber=121680573&passdocnumber=&go10=+GO+&requestid=0
The typed value would have to be inserted into that specific position after the = sign.
Thus far this is the only code I've come up with to accomplish this task (I created an alert for the sake of this example being I don't know how to accomplish the insertion of text). #bis represents the button:
$(document).ready() {
var bis_button = $('.bis_button');
bis_button.click(function() {
alert(bis_button.val());
});
});
The inputs and buttons are arranged like this in a WordPress page. Each input is assigned an ID by the WordPress plugin that's creating the page:
<div id="frm_field_[id]_container" class="frm_form_field form-field [required_class][error_class]">
<label class="frm_primary_label">[field_name]
<span class="frm_required">[required_label]</span>
</label>
[input]
[if description]<div class="frm_description">[description]</div>[/if description]
[if error]<div class="frm_error">[error]</div>[/if error]
<div class="bis_button">View in BIS</div>
</div>
I've attached an image that shows the fields and their respective buttons.:
$(document).ready(function() {
$(".bis_button").click(function() {
var inputValue = $(this).parent('.frm_form_field').find('input').val();
window.open('a810-bisweb.nyc.gov/bisweb/JobsQueryByNumberServlet?passjobnumber='+inputValue+'&passdocnumber=&go10=+GO+&requestid=0');
})
});
You should be able to do this:
bis.click(function() {
var prefix = "a810-bisweb.nyc.gov/bisweb/JobsQueryByNumberServlet?passjobnumber=";
var suffix = "&passdocnumber=&go10=+GO+&requestid=0"
var url = prefix + $(this).siblings("input[type='text']").val() + suffix;
window.open(url,'_blank');
});

An error with in the execution of an ajax

I have been a really big fan of stackoverflow(which led me to ask the question here and not anywhere else), anyway, without further ado...
While creating a shop system, I planned to implement an ajax which buys the item on the fly. Now This is how the loop for retrieving items looks like:
<?php
$shop_query = mysql_query("SELECT * FROM sector0_item WHERE 1");
$numrows = mysql_num_rows($shop_query);
While ($shop_fetch = mysql_fetch_array($shop_query)){
?>
<div id="shop_main">
<div class = 'item_img'>
<a><img src = "http://images.wikia.com/dofus/images/4/4e/Discovery_Potion.png" height = '100px'/></a>
</div>
<div class="item_buy">
<a><center>Price: <?php echo number_format($shop_fetch['item_price']);?></center><br /></a>
<a>Quantity: <input type = 'text' size = '9' id = 'itemquantity'/><br /></a>
<a><p>Point requirement: <?php echo number_format($shop_fetch['item_pt_req']);?></p></a>
<a><input type = 'button' id = 'buy' value = 'buy'/></a><span id = 'buy_status'></span>
</div>
<a><h3><?php echo $shop_fetch['item_name'];?></h3></a>
<a><p><?php echo $shop_fetch['item_desc'];?></p></a>
<a>Item Type: <font color = 'green'><?php echo $shop_fetch['item_class'];?></font></a>
</div>
<br />
<?php
}
?>
However, my ajax seems to act really weird. My implementation was to show a loading gif image.
Script:
<script type = 'text/javascript'>
$('#buy').click (function(){
var quantity = $('#itemquantity').val();
$('#buy_status').html('<img src = "http://www.antibodyresource.com/theme/js/ajax-loader.gif" height = 20px;/>');
});
</script>
The problem is, Only one button shows the circle when clicked. Does the position of the script cause this? Any help is appreciated.
You can only have one item with a given id. When you have multiple elements with the same id, it is indeterminate which one will be returned, but it will usually be the first item only.
If you want multiple buy buttons and want to assign them all the same jQuery event handler, then use a common class name instead of an id.
If you are loading content dynamically and you want event handlers to work for that content, then you need to use delegated event handling.
In jQuery, that is generally done with either .on() or .delegate(). The basic idea is that you pick a static parent object that is not dynamically loaded (perhaps the parent of show_main) and bind the event to that object and then pass the selector of the dynamic element like this (note, I've changed from an id to a class to identify the buy button):
$(staticParentSelector).on('click', '.buyButton', function() {
$(this).closest(".item_buy").find(".buy_status").html('<img src = "http://www.antibodyresource.com/theme/js/ajax-loader.gif" height = 20px;/>');
})
Two things:
It's hard to tell from the sample, but is there an iterator that creates a list of available items? If so, you shouldn't be using IDs which are meant to be unique. If there's really only one #buy then you're fine, though.
When content is updated with Ajax, you're going to lose bindings. Assuming the item related to the #buy button gets replaced with other items, you're better off with a delegated event:
// not in an inline script, but just once, ideally in your main JS file
$(document).ready(function() {
$('#wrapper').on('click', '#buy', (function(){
var quantity = $('#itemquantity').val();
$('#buy_status').html('<img src = "http://www.antibodyresource.com/theme/js/ajax-loader.gif" height = 20px;/>');
});
})
Where #wrapper is some ancestor higher up in the DOM tree that is never destroyed by the Ajax event.
id is unique value - on html page each id must have unique value. Use class instead.
You need to put your code inside $(document).ready(). So its:
$(document).ready( function() {
$('#buy').click( function(){
// do something here
});
});
Also, you may want to list to jfriend00's advice on IDs.

Create form dynamically in table

Using some code to create a form dynamically which I got here: http://www.trans4mind.com/personal_development/JavaScript2/createSelectDynamically.htm
This works great. However I have a regular html table I generate with html/php to get data out of a DB. I want to replace that data with a form so when users click the edit button the original entry is replaced with a form (either textbox or pull down menu). The user makes a selection and the new table comes back with the appropriate edit.
So for example one part of the data has this in the table:
<td><?php echo $result[0] ?></td>
Using the link about to create a form dynamically I change this to:
<td id="paraID"><form id="form1" name="form1" method="post" action enctype="text/plain" alt=""><?php echo $result[0] ?></form></td>
Also note the onclick event for the edit button:
This is hard to explain but hoping someone can help me with this interaction. I need some way to say:
if (user clicks edit button)
then
replace html table with form for each entry (for example, the table returns a name called foo and a textbox will appear with foo in it but now they can edit to change the name).
If you can start out with an id for the td then it will make things easier. Then you will need an edit button somewhere. Notice: It might be nice to replace "result_0" with the name for the value/field:
<td id="result_0_parent"><?php echo $result[0] ?><input type="button" onClick="editField('result_0','select')" value="Edit" /></td>
Then in your javascript you will have the editField function defined so that it sets the content of the td to be the dynamic form. Looking at makeForm function in the example javascript, you see this happening with appendChild(myform); The function editField will be like the makeForm function except you will pass in the field_id and field_type as parameters:
function editField(field_id, field_type)
I suggest you change the line that defines mypara to define mytd or better yet, field_parent instead since in your case it will not be a paragraph element, but a td (or possibly some other type of element):
field_parent = document.getElementById(field_id+"_parent");
The example code create a select (dropdown), but I am guessing you want to create other field input types so I recommended having field_type as a second parameter to the function. This means that it would make more sense for your implementation to use myfield instead of myselect and then use the field_type parameter to decide what myfield will be.
Replace the line in the makeForm / editField function:
myselect.setAttribute("id","selectID");
with
myfield.setAttribute("id",field_id);
One more thing: To set the initial value of the input field to be the displayed content, you will need to copy the "innerHTML" of the "parent" element. So place something like this right after defining field_parent:
initial_value = field_parent.innerHTML;
and I think you can figure out the rest. If not, I can elaborate a little more.
This works great. However I have a regular html table I generate with
html/php to get data out of a DB. I want to replace that data with a
form so when users click the edit button the original entry is
replaced with a form (either textbox or pull down menu). The user
makes a selection and the new table comes back with the appropriate
edit.
This is a script that allows with a double click on values to edit them and has a button to send them back. Maybe it would be of some help to use it (or use parts of it).
<?PHP
if(count($_POST)>0)
{
echo 'You gave:<br><per>';
print_r($_POST);
echo '<a href=http://localhost/temp/run.php>Start over</a>';
exit;
}
?>
<html>
<head>
<script type="text/javascript">
/**formEditor Class
*/
function formEditorCls( )
{
/**
Constructor simulator
*/
this.lastFieldEditedId = null;
/** Change span with input box, hide the eddit button and store theses IDS
*/
this.edit=
function (field)
{
//if there was a field edited previously
if(this.lastFieldEditedId != null)
this.save();
//get the inner element of the div, it can be span or input text
var childElem = document.getElementById(field).getElementsByTagName('*')[0];
//then replace the span element with a input element
document.getElementById(field).innerHTML="<input type=text name=n_"+field+
" id=id_"+field+" value="+childElem.innerText+">";
//store what was the last field edited
this.lastFieldEditedId =field;
}//func
this.save=
function ()
{
dbq="\"";sq='\'';
//get the last value
var lastValue = document.getElementById(this.lastFieldEditedId).
getElementsByTagName('*')[0].value;
//store it as span
document.getElementById(this.lastFieldEditedId).innerHTML="<span ondblclick="+dbq+
"formEditor.edit("+sq+this.lastFieldEditedId+sq+");"+dbq+" >"+lastValue+"</span>" ;
//now must reset the class field attribute
this.lastFieldEditedId=null;
}//func
this.submit=
function (path)
{
this.save();//if ay field was edited put new values in span elements
var form = document.createElement("form");//create a new form
form.setAttribute("method", "post");
form.setAttribute("action", path);
var myDiv = document.getElementById( "fieldsDiv" );//get the div that contains the fields
var inputArr = myDiv.getElementsByTagName( "SPAN" );//get all span elements in an array
//for each span element
for (var i = 0; i < inputArr.length; i++)
{
var hiddenField = document.createElement("input");//create an input elemet
hiddenField.setAttribute("type", "hidden");
hiddenField.setAttribute("name", i);
hiddenField.setAttribute("value", inputArr[i].innerText);
form.appendChild(hiddenField);//append the input element
}
document.body.appendChild(form);//append the form
form.submit();//submit the form
}//func
}//class
formEditor = new formEditorCls( );
</script>
</head>
<body onclick="rt();">
Double click any value to change it..<br><br>
<div id="fieldsDiv">
Name:<font id="nameField">
<span ondblclick="formEditor.edit('nameField');" >Mark</span>
</font><br>
Surname:<font id="surnameField" >
<span ondblclick="formEditor.edit('surnameField');">Smith</span>
</font><br>
</div>
<input type=submit name="submit"
onclick="formEditor.submit('http://localhost/temp/run.php');" value="Submit">
</body>
</html>

Categories