I have an onclick event called in a PHP foreach loop for several items whose author name I need to click. Only one name was getting generated, so I know that I must have a unique id for each HTML element. I already have a variable $objkey for a counter used in the loop so I appended it to the id.
<?php
//This is the item that appears in the loop.
//Currently, clicking on each one that is generated only generates the first author name
//The correct author as passed by PHP displays in the loop.
//$closest is the value of the author's name.
echo 'Click name to add <span><button id="closest' . $objkey . '" onClick="setAuthor()">' . $closest . '</button></span><br />';
?>
I have done a print_r('$objkey); and the appropriate value for the counter is getting passed along.
I want the value of this button element $closest to be passed to an input field. I have appended the variable to both the input's id and name elements (not sure if that helps) (UPDATE: There is an input field for each of the authors that needs to get the value):
<?php
echo '<input id="author_name' . $objkey . '" type="text" name="author_name' . $objkey . '" value="' . $author . '" />';
?>
Where I'm stuck is with my function:
<script type="text/javascript">function setAuthor() {
var author = document.getElementById("closest").innerHTML;
window.alert(author);
document.forms["myform"].elements["author_name"].value = author; }</script>
How do I create a variable in the function for the unique ids so that each looped item generates distinct names?
One way to do it is to pass this to the the setAuthor function:
<?php
//This is the item that appears in the loop.
//Currently, clicking on each one that is generated only generates the first author name
//The correct author as passed by PHP displays in the loop.
//$closest is the value of the author's name.
echo "Click name to add <button id='closest_{$objkey}' onClick='setAuthor(this)'>{$closest}</button><br/>";
?>
With this approach, you can access the element within setAuthor:
<script type="text/javascript">
function setAuthor(el) {
var author = el.innerHTML,
id = el.id.replace(/^closest_/, '');
if (console) {
console.log(author);
}
document.forms["myform"].elements["author_name_" + id].value = author;
}
</script>
However, you shouldn't set onclick inline and for each element. You should use an event registration function.
Related
I am trying to figure out how to update an URL that I am using to parse the XML (using simplexml_load_file()).
There is a button that has a $productid that is assigned to it by the user when they add their shortcode [show_cart_button productid=#].
//code for the button input that gets called
function print_add_cart_button($productid, $atts = array()) {
//some other form code for the button
$replacement .= '<input type="hidden" name"cart_product" value"' . $productid . '"/>';
return $replacement;
}
This is the function I am using to display and call the product information:
function show_shopping_cart_handler($atts) {
if (isset($_POST['cart_product'])) {
$id = "&PRODUCTID=" . $_POST['cart_product'];
// uses the input name from the button
}
$url = "https://secure.bmtmicro.com/cart?CID=2/WP" . $id;
$xml = simplexml_load_file($url) or die("error.");
foreach ($xml->producttable->row as $product) {
$output .= '<span>' . $product->productname . '</span>';
}
return $output;
}
The way the URL will work properly is to have a &PRODUCTID=(product#) added to the end of the URL. For example, if you click two different buttons, the URL should look like this: https://secure.bmtmicro.com/cart?CID=2/WP&PRODUCTID=1&PRODUCTID=2 (obviously 1 and 2 will need to display the buttons $productid number).
As you should be able to see from my code above, every time a button gets clicked, it just rewrites the URL and displays that one product, instead of adding a new one to the list. I tried to set the simplexml_load_file() into a foreach(), but that would not display any products when the button was clicked. Does anyone know a way I could get that URL to update/work properly?
Everytime
if (isset($_POST['cart_product'])) {
$id = "&PRODUCTID=" . $_POST['cart_product'];
// uses the input name from the button
}
Is called, it's overwriting $id. You need to get any existing values for the url.
You'll have to get all of the current values ($_GET['cart_productions']), throw them into an array, grab the new post, add it to the array and add all of them to them the url using http_build_query().
So here is my problem.I want the id of the href which is taken dynamically to be printed in the url.
My code of category.php:
CATEGORY.PHP
while($row = mysql_fetch_assoc($result))
{
echo '<a id="' . $row['topic_id'] . '" href="category.php?id=' .
$_SESSION['id'] . '&check1=//what should i put here?">;
}
all i want is for check1 to have the id of each link seperately so if i have 3 links(depends on the database) the 2nd link will have id=2 and i want to print id=2 the next time category.php is loaded.
BUT
Notice that all id are first printed and then someone will choose one of these links.
You're already doing it in other places.
It's called concatenation - All that PHP does is output dynamically generated HTML. This means that within the quotes of your echo construct you can concatenate anywhere.
All you have to do is add it to the URL as you did with ID:
while ($row = mysql_fetch_assoc($result)) {
echo '<a id="'. $row['topic_id'] .'" href="category.php?id='. $_SESSION['id'] .'&check1='. $row['topic_id'] .'"></a>'
}
your $row['topic_id'] should be different with every iteration. the $row variable gets set to a new
This will output the same $row['topic_id'] as the id attribute of the link but it will also append it as a $_GET parameter in your category.php.
If you do not know what gets passed on in the $_GET array you could always do a print_r($_GET) anywhere in the script since $_GET always gets set (even without query params, it'll just be empty).
It could be that it is unclear to me what you're asking, it could also be that you want the actual primary key id field in which case you'll just have to swap out the last bit:
&check1=$row['topic_id']
with whatever your ID field is named, probably something along the lines of:
&check1=$row['id']
where id would be the actual id of the row in the database table.
I've seen a solution here that I, quite frankly, don't understand.
On the administration side of a website I'm working on, an administrator can edit blog posts. When the administrator goes to the page to edit the blog post, it also displays all of the comments on that post. Instead of adding a new table for each new blog post which contains comments, I simply created one table which holds all the information for the blog post, including a column for the comments.
Comments and comment-content is delimited. I.E. internally, a blog post comment column would look similar to this...
Name:Content:Email>Name2:Content2:Email
Etc.
This is how I display the comments on the admin page:
$post_query = "SELECT * FROM `$blog_table` WHERE id=$identifier";
$post_result = $connection->query($post_query);
$post = $post_result->fetch_assoc();
$comments_value = $post["comments"];
$original_comments_array = explode(">", $comments_value);
$comments_array = [];
foreach($original_comments_array as $comment) {
$individual_comment_array = explode(":", $comment);
$comments_array[] = $individual_comment_array;
}
foreach($comments_array as $index=>$comment) {
if ($comment_deletions_array[$index] === $index) {
$checked = "checked";
}
echo '<div class="content-border comment-margin"><span class="comment-name">';
echo $comment[0];
echo '</span><br /><p class="comment-content">';
echo $comment[1];
echo '<br /></p>';
echo $comment[2];
echo '<br /><br /><input name="comment_deletions[]" type="checkbox" value="' . $index . '" ' . $checked . '/> Delete This Comment';
echo '</div>';
}
As you may have noticed from the code above, each comment renders with its own checkbox input, the value of which is determined by the index.
Each checkbox shares the same name. I get all the values of the checkboxes like this:
$comment_deletions_array = $_POST["comment_deletions"];
In the snippet I provided earlier, there is an if statement within the foreach loop which determines if the comment was marked for deletion, and if so checks the check box. (This function is to replace the user's input if there was an error.)
The problem is that the indexes do not line up. If there is a checkbox which is not checked, it does not return false or null or anything of the sort to the $comment_deletions_array rather the array is just populated by value of the next input which WAS checked.
Is there a way I can return a value if the checkbox is not checked in order to maintain the correct index?
I have a SQL database that PHP is getting the contents of. It gets the info from each row of a table and displays it on a web page. There is also an anchor and a hidden div containing more details from that row of the SQL table. When the use clicks the anchor the jQuery needs to detect it and show the hidden div. The problem I have is that each anchor and hidden div have a dynamic id of:
'ev_a_' . $row['id']
'ev_' . $row['id']
the jQuery I assume needs to look something like this:
$('#ev_a_')[].click(function(){
$('#ev_')[].show();
}
I'm not entirely sure how this works and I've never used dynamic ids before in jQuery. Any suggestions?
I should point out the PHP/SQL code is:
while($row = mysql_fetch_array($q_result)){
echo "<br/><b>" . $row['a'] . "</b><br/>" . $row['b'] . ", " . $row['c'] . "<br/>" . $row['d'] . "<br/><a class='ev_event_a'>More Details</a><br/><div class='ev_event'>" . $row['e'] . "</div>";
}
I would use a class instead for these links instead and set the ID in a data attribute. Depending on your needs you don't even need the ID as you can show the next element if it is already part of the DOM.
A simple example (ID not used...):
Toggle details
<div class="initially_hidden">
...
</div>
....
Toggle details
<div class="initially_hidden">
...
</div>
....
and the javascript:
$('.show_more').on('click', function(e) {
e.preventDefault();
$(this).next().slideToggle();
// if you need the ID, you can get it via $(this).data('id')
});
I'm building a form - a section of which dynamically generates and increments input field's individual ids when the user hits the 'replicate' button. For instance, an input field made for a first name has an id of 'firstname1', when it replicates it becomes 'firstname2' etc etc.
My problem is in the php 'confirmation' page I'm trying to build. I want to echo out every input field generated and filled without hardcoding a bunch of echoes. I was told to use arrays instead of individual variable names - i kind of understand the concept but am falling way short.
I tried to create an array to capture the value of every new input so I can just $_POST the array, then loop and echo each value, but I don't really understand what needs to change and where to implement it.
The following code replicates the entire container div, it's input fields, and increments it's class number:
$(#replicate').click(function(){
var $cloned = $('.container1').clone();
$cloned.find('input').val('');
$cloned.appendTo($('.emptyContainer'));
var container = $(".emptyContainer div").length;
var containerNumber = container + 1;
var containerClass = 'container' + containerNumber;
$(".emptyContainer .container1").attr("class", containerClass);
Then the input ids increment in the same fashion:
var fnameID = 'firstname' + containerNumber;
$('.emptyContainer #firstname1').attr({id: fnameID, name: fnameID});
There are more inputs that would include things like last name, phone, email etc.
Another user suggested:
foreach($_POST as $fieldName=>$fieldValue){
echo $fieldName." = ".$fieldValue."<br/>";
}
While that worked to get me everything on the php page it was all in one large block, which would make the later styling a bit troubling.
How do I grab the input values for each new input, store them in an array, and post them to the php side in such a way that all related information stays in it's related areas when the user hits submit?
You can try following method, as this method works best for me in case of dynamic rows.
code is not much readable since i directly pasted from the project but still hope it would be helpful
$('.add-option').live('click',function(){
if(rowCtr < ucount){
var tr = '<tr class="input-'+counter+'"><td><select id="itb_users" class="itb_users" name="project[itb_users]['+counter+']" >'
tr += '<option value=0>Select</option>'
<?php foreach ($itb_users as $item){ ?>
tr += '<option grade="<?php echo $item->grade; ?>" value="<?php echo $item->id; ?>"><?php echo $item->first_name; ?></option>';
<?php } ?>
tr += '</select>'
tr += '</td>'
tr += '<td> </td>'
tr += '<td><input class="_hour" id="project[input-hour]['+counter+']" name="hours['+counter+']" type="text" class="field" style="width:30px"/></td>'
tr += '<td><img class="add-option" src="'+'<?php img_src('add.png'); ?>'+'" /> <img class="remove-option" src="'+'<?php img_src('remove.png'); ?>'+'" /></td>'
tr += '</tr>';
counter++;
rowCtr++;
.......
on submitting the php will receive a variable project with related records.