jQuery to run after PHP load - php

I'm working on a site using the Big Commerce platform. The cart page is built in snippets called by PHP. I don't have access to the PHP files. What I need to do is get the value of a span tag(at a given index) and retrieve the value, I use this value to determine what my minQTY text field should be. I want my code to run after the page has been loaded. However my script isn't working on the page.
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).load(function(){
$("a.CustomizeItemLink");
$changeIndex = $("a.CustomizeItemLink").index('a.CustomizeItemLink');
$change = $("a.CustomizeItemLink").length;
$productTestArray = ['/american-boxwood-buxus/', '/lavander-crape-myrtle-lagerstroemia-fs/']
$productLength = $productTestArray.length;
for(i=0, j=0; i<=$change, j<=$productLength; i++, j++){
$productTest = "http://www.tnnursery.net";
$productTestValue = $("td.blah a").get(i);
$productTest = "http://www.blah.net" + $productTestArray[j];
$MD = $productTestValue;
$MS = $productTest;
$minQTYArray = ['100','100','75','50','25','20','15'];
$cartSpanValue = $(".productAttributes td span:eq("+i+")").text();
$rdTestArray2 = ['6-12','12-18',"1-2'","2-3'","3-4'","4-5'","5-6'"];
$arr2Test = jQuery.inArray($cartSpanValue, $rdTestArray2);
$minQTYValue = $minQTYArray[$arr2Test];
$cartQtyValue = $(".qtyInput:eq("+i+")").val();
if($MD != $MS){
}
else{
if($cartQtyValue >= $minQTYValue){
}
else{
if ($arr2Test == -1){
$cartQtyValue = $(".qtyInput:eq(" + i + ")").val('100');
}
else{
$cartQtyValue = $(".qtyInput:eq(" + i + ")").val($minQTYValue);
alert($cartQtyValue);
}
}
}
}
});
});
});
</script>
</td>
<td class="ProductName" colspan="1">
Item Name1<table class="productAttributes" cellpadding="0" cellspacing="2">
<tr>
<td>
<label>Plant​ Size​s:</label>
</td>
<td>
<span>12-18​"</span>
</td>
Change
28500
()
<div style="display: none" class="WrappingOptions">
Gift Wrapping:
Add
<span style="display: none">
(Change or Remove)
</span>
<br />
<span style="display: none">
Gift Message:
</span>
</div>
</td>
<td align="center" class="CartItemQuantity">
<span style="padding: 0; margin: 0;"><input type="text" size="2" name="qty[4eea86d587825]" id="text_qty_4eea86d587825" class="qtyInput quantityInput" value="50"/></span>
<div style="">
Remove
</div>
</td>
My question is how do I set my jQuery to run after the PHP has been loaded into the page?

First, you should restore the $(document).ready(function(){});
Second, the php runs on the server side, and thus before the page itself is loaded. You shouldn't have any worry that your javascript will run before the PHP.
Lastly, I think the reason your code isn't running may be due to syntax errors. If you've copied your code in directly then you have multiple endings to your opening function. I'm not sure if this was intentional or not but you have three sets of closing for the load function when its unnecessary.
Also, this line :
$productTestArray = ['/american-boxwood-buxus/', '/lavander-crape-myrtle-lagerstroemia-fs/']
Does not have a semi-colon ending the statement. Make these changes and see if your code begins to function properly.
EDIT: Also, in your For loop you define i and j. Why is that? I believe they will always be the same number the way you have it setup. Am I missing something?

Try replacing $(document).load with $(window).load.

$(document).ready(function(){
//your code here
});

Related

AJAX Respond Not Catched by PHP file

We are on progress creating web page for live search and update file in bulk using JQUERY AJAX method. The files consist of index.php (for display to user and Javascript), and multiple_update.php (for fetch and update file in bulk). Initial reference we got is from here from webslesson website, but it does not have any reference for searching the record, hence we search for help for our journey.
Below is our index.php file
<div class="content-wrapper">
<div class="content-heading">
<div>STO Monitoring<small>Tables, one step forward.</small></div>
<div class="ml-auto"><input type="text" id="search" placeholder="Search" /></div>
<div id="display"></div>
<div class="ml-auto">
<button class="btn btn-primary btn-lg" type="button" data-toggle="modal" data-target="#myModalSmall"><i class="fas fa-plus-square"></i> Add Record</button>
</div>
</div>
<form method="post" id="update_form">
<div class="card">
<div class="card-body">
<table class="display" id="example" style="width:100%">
<thead>
<tr>
<th width="3%"></th>
<th width="5%">No</th>
<th width="15%">STO</th>
<th width="20%">PN</th>
<th width="8%">Qty</th>
<th width="10%">From</th>
<th width="10%">Dest</th>
<th width="15%">Status</th>
<th width="14%">Remark</th>
</tr>
</thead>
<tbody></tbody>
</table>
<div align="left">
<input type="submit" name="multiple_update" id="multiple_update" class="btn btn-info" value="Multiple Update" />
</div>
</div>
</div>
</form>
</div>
.....
Below is script inside our index.php, the one we suspect need troubleshoot at the moment.
<script>
function fill(Value) {
$('#search').val(Value);
if (name == "") {
$("#display").html("");
}
}
$(document).ready(function(){
function fetch_data()
{
$("#search").keyup(function() {
var name = $('#search').val();
if (name == "") {
//Assigning empty value to "display" div in "search.php" file.
$("#display").html("empty");
} else {
$.ajax({
url:"multiple_select.php",
method:"POST",
dataType:"json",
data: {
//Assigning value of "name" into "search" variable.
search: name
},
success:function(data)
{
var html = '';
for(var count = 0; count < data.length; count++) {
html += '<tr>';
html += '<td><input type="checkbox" id="'+data[count].num+'" data-num="'+data[count].num+'" data-sto="'+data[count].sto+'" data-pn="'+data[count].pn+'" data-qty="'+data[count].qty+'" data-supplant="'+data[count].supplant+'" data-dest="'+data[count].dest+'" data-stat="'+data[count].stat+'" data-remark="'+data[count].remark+'" class="check_box" /></td>';
html += '<td>'+(count+1)+'</td>';
html += '<td>'+data[count].sto+'</td>';
html += '<td>'+data[count].pn+'</td>';
html += '<td>'+data[count].qty+'</td>';
html += '<td><span class="btn btn-oval btn-primary">'+data[count].supplant+'</span></td>';
html += '<td><span class="btn btn-oval btn-warning">'+data[count].dest+'</span></td>';
html += '<td>'+data[count].stat+'</td>';
html += '<td>'+data[count].remark+'</td></tr>';
}
$('tbody').html(html);
}
});
}
});
}
fetch_data();
$(document).on('click', '.check_box', function(){
.....
</script>
We modify the AJAX to see if the input can be catched by the network, below is code for multiple_update.php
<?php
include('multiple_connection.php');
$name = $_POST['search'];
echo $name;
$query = "SELECT * FROM matreq_list, sto_list WHERE matreq_list.sto = sto_list.sto AND sto_list.sto LIKE '%$name%' LIMIT 5;
$statement = $connect->prepare($query);
if($statement->execute()) {
while($row = $statement->fetch(PDO::FETCH_ASSOC)) {
$data[] = $row;
}
echo json_encode($data);
}
?>
We want to make every search is captured via AJAX, and respond from network will be live-reflected in our index file. Below is our expected final result (this result is without "LIKE" in mysql statement to show the result only) :
And we confirm AJAX can handle our input, below is the image :
--UPDATE-- Below is error messages :
Error messages
However, after we fired the input, nothing cames up in our index.php file. Network shows good respond, but the HTML is not responding the way we expected it to do. Please kindly advise us sir, what is wrong with our method and what should we fix?
Thank you and appreciate your kind help in our case
=====UPDATE=====
2020-07-02 : As mentioned by mr Nadir Baoun, tried to change the order of jquery.js and put it above the bootstrap.js, and somehow my table now able to search some part or whole part of the data.
Before :
.....
<script src="vendor/datatables.net/js/jquery.dataTables.js"></script>
<script src="vendor/datatables.net-bs4/js/dataTables.bootstrap4.js"></script>
<script src="vendor/datatables.net-responsive-bs/js/responsive.bootstrap.js"></script>
<script src="vendor/jquery/dist/jquery3.5.1.js"></script>
<script src="vendor/datatables.net/dist/js/jquery.dataTables.min.js"></script>
After ordered : I move the jquery to the top of all codes.
and below is network screenshot :
After change order of javascript
Surprisingly, this work well :D
The HTML isnt responding the way you want is because you have JavaScript errors thus your response code wont function accordingly.
First thing include your jquery file before bootstrap.
This should solve the " cannot read property fn of undefined " error.
Please update your post with debug messages in the success param of your ajax request after doing what i have mentionned above
After thoroughly reading on various articles with a guide from Mr Nadir Baoun, my problem is now fixed by changing the order of the script, putting the jquery script before the bootstrap script.
Similar answers also posted in stackoverflow website :
script order for jquery with bootstrap
Thank you :)

how to display image on a form select box change

I'm trying to created a select box in my form and display the image that is selected in the select box next to it. I know it requires jquery or something and I have no clue when it comes to that. If anyone can help or point me in the right direction that would be awesome!!!
<table width="100%">
<tr>
<td>
<select id="icon" name="icon" class="form-control select2">
<?php foreach ($icons as $icon) { ?>
<option value="<?php echo $icon['link']; ?>">
<?php echo $icon['name']; ?>
</option>
<?php } ?>
</select>
</td>
<td align="center" id="iconPreview">
Image Here
</td>
</tr>
</table>
i found this jquery snippet but it doesn't display anything on change...
JQuery:
<script>
$(document).ready(function() {
$("#icon").change(function() {
$("#iconPreview").empty();
if ( $("#icon").val()!="" ){
$("#iconPreview").append("<img src=\"" + $("#icon").val() + "\" />");
}
else{
$("#iconPreview").append("displays image here");
}
});
});
</script>
You'll need to add jQuery if you want to use jQuery in the head, so in your document in the <head> add this line:
<script src="http://code.jquery.com/jquery-1.12.0.min.js"></script>
Then give the TD you want the image in a class:
<td class="imageHere" align="center" id="seleced_image">
Then, at the bottom of your page (or a .js page if you want to link it) add this:
<script>
$(function(){
$('#icon').change(function(){
var image = $('#icon').val();
$('#seleced_image').html("<img src='" + image + "' alt='description' />");
});
});
</script>
This jQuery is saying "Everytime the #icon dropdown changes, load the image into the <td>
This is the simplest way to do it without learning any jQuery. Otherwise, I suggest you learn jQuery or better yet, javascript.
Changes made:
Its better to work with IDs than classes on cases like this.

Change content of hidden div depending on which link is clicked

I'm building a website where the admin can make settings for the website. I would like the admin settings page to have a similar "feel" as the rest of the website, which has some nice looking jQuery features.
On the admin site there's a hidden div, which is shown when one of six links has been clicked. I'd like the content of the hidden div to change content before showing itself. I'm not sure how to do this. I could have a div box for every link on the page. But this becomes pretty cumbersome since I'd need to repeat my css and jquery for every link. I imagine that this, somehow, can be done with some javascript/jquery code that determines which link that was click and then decides which php function to call inside the hidden div. Then the php could "echo" out the content of the div, which then could be shown.
How could one do this?
My HTML/jQuery code is as follows:
--- The html links ---
<table id="settings">
<tr>
<td>
<img src="images/folder.gif" alt="" height="100"/>
</td>
<td>
<img src="images/folder.gif" alt="" height="100"/>
</td>
<td>
<img src="images/folder.gif" alt="" height="100"/>
</td>
----- The Hidden div -----
<div id="dashboard_box">
<div class="dashboard_inside">
<form action="#" method="post">
<p style="font-size:20px; font-weight: bold;">Change color</p>
</br>
<fieldset>
<? load_content1();?>
</fieldset>
</form>
</div>
</div>
---- jquery code (working)----
var mouse_is_inside = false;
$(document).ready(function() {
$(".action").click(function() {
var loginBox = $("#dashboard_box");
if (loginBox.is(":visible"))
loginBox.fadeOut("fast");
else
loginBox.fadeIn("fast");
return false;
});
$("#dashboard_box").hover(function(){
mouse_is_inside=true;
}, function(){
mouse_is_inside=false;
});
$("body").click(function(){
if(! mouse_is_inside) $("#dashboard_box").fadeOut("fast");
});
});
You probably want to use ajax to load the content from the server. Take a look at jquery's .load() method: http://api.jquery.com/load/
You could include a data attribute per link:
<a class="action" data-content="content.php?method=load_content1"></a>
<a class="action" data-content="content.php?method=load_content2"></a>
js would look something like this:
$(".action").on('click', function() {
$("#dashboard_box fieldset").load($(this).data('content'), function() {
var loginBox = $("#dashboard_box");
if (loginBox.is(":visible"))
loginBox.fadeOut("fast");
else
loginBox.fadeIn("fast");
}
return false;
});
Then, in your content.php file you could check the method parameter in the url to determine what content to return.
My php is a little rusty, but something like this:
<?
call_user_func($_GET['method']); // i'm not sure how safe this is. you may want to be more explicit
?>
You can just add data attribute in each of your link's
<a href="#" data-url="content1.php" ..
Then on click of any of the a you can get the php to be called.
$('a').on('click',function(){
var phpFunctionToCall = $(this).data('url');
});
You probably need to make ajax call to load content into your fieldset As this <? load_content1();?> run's on server and javascript have no control over it.
Thanks for all the help. this is what I ended up doing.
--- HTML ---
<a class="action" data-content="content.php?method=load_content2"></a>
---Jquery---
var mouse_is_inside = false;
$(document).ready(function() {
$(".action").click(function() {
var phpFunctionToCall = $(this).data('content');
$('#indhold').load(phpFunctionToCall);
var loginBox = $("#dashboard_box");
if (loginBox.is(":visible"))
loginBox.fadeOut("fast");
else
loginBox.fadeIn("fast");
return false;
});
$("#dashboard_box").hover(function(){
mouse_is_inside=true;
}, function(){
mouse_is_inside=false;
});
$("body").click(function(){
if(! mouse_is_inside) $("#dashboard_box").fadeOut("fast");
});
});
--- PHP (shortened)---
function load_settings_panel($settingOnRequest) {
return $settingOnRequest;
}
$result = call_user_func('load_settings_panel', $_GET['method']);
echo($result);

$.get in jquery not executing while on html page through javascript

I've been trying to create a simple download counter for my site, in the following way: To use jquery to retrieve the value of a txt which indicates download times, then to use jquery to call ajax to execute a PHP file, which would in turn overwrite such txt file (incrementing it on the php file) then store it, then reading back the value with jquery. Before I forget, and to avoid any misinformation, here is the whole HTML code for the page:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<html>
<head>
<title>GreenDream: SMS Sender</title>
<link rel=StyleSheet type="text/css" href="http://www.gfcf14greendream.com/CSS/greendream.css" />
<link rel="SHORTCUT ICON" href="http://www.gfcf14greendream.com/images/dreamicon.ico">
<script type="text/javascript" src="http://www.gfcf14greendream.com/JS/greendream.js"></script>
</head>
<body onload="startTime(); handleTextFile()">
<div id="background">
<img src="http://www.gfcf14greendream.com/images/greentwi.png" class="stretch" alt="" />
</div>
<br />
<table align="center">
<tr>
<td>
<img src="http://www.gfcf14greendream.com/images/dream.png" align="middle">
</td>
<td>
<div id='pbutton' style="width:113px; height:41px; margin:0px;white-space:nowrap; word-spacing:0;"><a class="button" href="http://www.gfcf14greendream.com/programs.html">Programs</a></div>
</td>
<td>
<div id='gbutton' style="width:93px; height: 41px; margin:0px;white-space:nowrap; word-spacing:0;"><a class="button" href="http://www.gfcf14greendream.com/games.html">Games</a></div>
</td>
<td>
<div id='tbutton' style="width:108px; height: 41px; margin:0px;white-space:nowrap; word-spacing:0;"><a class="button" href="http://www.gfcf14greendream.com/tutorials.html">Tutorials</a></div>
</td>
<td>
<div id='bbutton' style="width:74px; height: 41px; margin:0px;white-space:nowrap; word-spacing:0;"><a class="button" href="http://blog.gfcf14greendream.com/">Blog</a></div>
</td>
<td>
<div id='mbutton' style="width:114px; height: 41px; margin:0px;white-space:nowrap; word-spacing:0;"><a class="button" href="http://www.gfcf14greendream.com/aboutme.html">About Me</a></div>
</td>
<td style="padding-left:50px">
<div id='daytitle'></div>
<div id='clock'></div>
</td>
</tr>
</table>
<br />
<div style="text-align: center; color:#00FF00; font-size: 20px">The following is a Visual C++ program that was designed specifically to send text messages to a phone... Free of charge!!</div>
<br />
<div style="text-align: center; color:#FFFF00; font-size: 20px">THE GOOD: If you have a prepaid phone, then you can send text messages to a phone without wasting your minutes...</div>
<br />
<div style="text-align: center; color:#FF8000; font-size: 20px">THE BAD : Since I haven't been able to put a Skype or Google Voice library for use with C++, this application depends on using what's known as an SMS gateway, different for every phone carrier... meaning you must know your recipient's carrier to be able to send a message!</div>
<br />
<div style="text-align: center; color:#FF0000; font-size: 20px">THE UGLY: This program doesn't work on computers connected to safe networks (such as college/university networks) ... at least not yet!</div>
<br />
<div style="text-align: center; color:#00FF00; font-size: 20px">You will probably need the Visual C++ Redistributable Package (or the .NET framework or both, but most likely just the package) to run this program, if you don't have it installed on your pc yet</div>
<br />
<br />
<div style="text-align: center; color:#0000C8; font-size: 20px">Click here to download the Visual C++ Redistributable Package</div>
<div style="text-align: center; color:#0000C8; font-size: 20px">Click here to download the .NET Framework 4</div>
<br />
<br />
<div style="text-align: center; color:#00FF00; font-size: 20px"><a class="button" id="downbutton" style="width:115px;margin:0px;white-space:nowrap; word-spacing:0;" href="http://www.gfcf14greendream.com/Programs/SMSSender/SMS Sender.exe">Click here to download SMS Sender</a></div>
<br />
<div id='counter' style="text-align: center;"></div>
<br />
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script type="text/javascript">
function handleTextFile()
{
document.getElementById('counter').style.color = "rgb(0, 255, 0)";
document.getElementById('counter').style.fontWeight = 'bold';
var downcounter = 0;
$.get("http://www.gfcf14greendream.com/counters/smssender.txt", function(data){
downcounter = data;
if (downcounter == 1) $("#counter").text("SMS Sender has been downloaded " + downcounter + " time...");
else $("#counter").text("SMS Sender has been downloaded " + downcounter + " times...");
});
$("#downbutton").click( function(){
$.get("http://www.gfcf14greendream.com/PHP/smssender.php", function(data){
$.get("http://www.gfcf14greendream.com/counters/smssender.txt", function(data){
downcounter = data;
if (downcounter == 1) $("#counter").text("SMS Sender has been downloaded " + downcounter + " time...");
else $("#counter").text("SMS Sender has been downloaded " + downcounter + " times...");
});
});
});
}
</script>
</body>
</html>
Upon running the page, I use this code (a piece from above) to read a txt file and get download count (this works):
var downcounter = 0;
$.get("http://www.gfcf14greendream.com/counters/smssender.txt", function(data){
downcounter = data;
if (downcounter == 1) $("#counter").text("SMS Sender has been downloaded " + downcounter + " time...");
else $("#counter").text("SMS Sender has been downloaded " + downcounter + " times...");
});
Then when the downbutton variable is clicked, this code should execute:
$("#downbutton").click( function(){
$.get("http://www.gfcf14greendream.com/PHP/smssender.php", function(data){
$.get("http://www.gfcf14greendream.com/counters/smssender.txt", function(data){
downcounter = data;
if (downcounter == 1) $("#counter").text("SMS Sender has been downloaded " + downcounter + " time...");
else $("#counter").text("SMS Sender has been downloaded " + downcounter + " times...");
});
});
});
, which should read a php file, whose code is:
<?php
$counter = intval(file_get_contents('/homepages/37/d434704165/htdocs/counters/smssender.txt'));
$counter++;
file_put_contents('/homepages/37/d434704165/htdocs/counters/smssender.txt', $counter);
?>
And running the php would overwrite the txt file "smssender" and thus increase the number of downloads. I noticed that manually entering the address of the php file on my site actually works, and the download increment takes place. Yet when JQuery executes the code, no increment takes place. I'm guessing it's on this line, but what would be the error here? :
$.get("http://www.gfcf14greendream.com/counters/smssender.txt", function(data){
Thank you very much for any help or suggestion!!
I think it would be a lot simpler to just use the PHP page by itself. You can use GET variables to determine whether you need to increment the download counter. For instance, do something like this in your PHP file:
<?php
$total = (int)file_get_contents($_SERVER['DOCUMENT_ROOT'] . '/counters/smssender.txt');
if (isset($_GET['i'])) {
$total++;
// now update the file for future use
file_put_contents($_SERVER['DOCUMENT_ROOT'] . '/counters/smssender.txt', $total);
}
echo $total;
?>
Then you can call the PHP page by itself in the ajax so that you don't have to worry about both calls being executed simultaneously and causing errors. You could now just make a call to "smssender.php" when you want to retrieve the current number of downloads. In addition, you could call "smssender.php?i" when you want to retrieve the current number of downloads and increment the file contents.
If you wanted to only increment the file's contents and not echo the output, you could add another if statement, but I don't know if that's what you're trying to do. If so, please let me know and I can show you code for that as well. I hope that helps, if not, just let me know.
UPDATE: Just change your code to this:
Javascript File:
$.get("/PHP/smssender.php", function(data) {
$("#counter").text(data);
});
$("#downbutton").click( function() {
$.get("/PHP/smssender.php?i", function(data) {
$("#counter").text(data);
});
});
PHP File:
<?php
$total = (int)file_get_contents($_SERVER['DOCUMENT_ROOT'] . '/counters/smssender.txt');
if (isset($_GET['i'])) {
$total++;
// now update the file for future use
file_put_contents($_SERVER['DOCUMENT_ROOT'] . '/counters/smssender.txt', $total);
}
$suffix = ($total == 1) ? 'time' : 'times';
echo 'SMS Sender has been downloaded ' . $total . ' ' . $suffix . '...';
?>
Now, you can simplify your Javascript/jQuery by A LOT. This code will have the exact same behavior as the code you had, without any errors. Now, I will explain the changes I have made. First, you only have to call a single PHP file with the $.get() method, regardless if you are just retrieving the current number of downloads or whether you are incrementing the total.
Secondly, the text handling is done in the PHP file. You no longer determine if it has been downloaded 1 or more times in Javascript, instead the PHP file handles this because it's a lot faster than retrieving the data and making a calculation afterwards.
Lastly, I made the download button only call $.get() once so that you don't have to worry about errors resulting from an attempt to retrieve two different pages simultaneously. Try replacing your code with the new code I posted above and let me know how it works out for you.

How to add a content into the correct textarea by clicking on an "Add" button

When you open the application can you please click on the "Add Question" twice so it adds 2 table rows.
Now you will see in the application that above the horizontal line there is a textarea and a plus button, and below the horizontal line shows 2 table rows, both rows displaying its own textarea and plus button.
Now my question is that I want these 2 outcomes to happen but I do need help from somebody who is good at using Jquery/Javascript in order to solve this situation:
Situation 1. If the user clicks on the plus button ABOVE the horizontal line, then it displays a modal window which contains a search bar, Please type in search bar "AAA". You will now see a list of results. Now what I want is that if the user selects a row by clicking on the "Add" button, then I want the "QuestionContnet" within that row to be displayed in the textarea above the horizontal line. At the moment the Add button just closes the modal window but doesn't add anything into the textarea.
Situation 2: This deals with the user clicking on a plus button within one of the table rows BELOW the horizontal line. I want the same thing to happen except the "QuestionContent" added is displayed in the textarea within the same row the user has clicked the plus button, no where else.
How can both situations be solved so that it adds the QuestionContent into the correct textareas depending on which plus button is clicked? I am using an Iframe to display the content within the modal window.
UPDATE:
If you look at the application, it is now displaying "[Object] [object]" in textaea when I click "Add" button. Not the "Question".
Below is the code for the application:
<head>
<script type="text/javascript">
var plusbutton_clicked;
function insertQuestion(form) {
var $tbody = $('#qandatbl > tbody');
var $tr = $("<tr class='optionAndAnswer' align='center'></tr>");
var $plusrow = $("<td class='plusrow'></td>");
var $question = $("<td class='question'></td>");
$('.questionTextArea').each( function() {
var $this = $(this);
var $questionText = $("<textarea class='textAreaQuestion'></textarea>").attr('name',$this.attr('name')+"[]")
.attr('value',$this.val());
$question.append($questionText);
});
$('.plusimage').each( function() {
var $this = $(this);
var $plusimagerow = $("<a onclick='return plusbutton();'><img src='Images/plussign.jpg' width='30' height='30' alt='Look Up Previous Question' class='imageplus'/></a>").attr('name',$this.attr('name')+"[]")
.attr('value',$this.val());
$plusrow.append($plusimagerow);
});
$tr.append($plusrow);
$tr.append($question);
$tbody.append($tr);
form.questionText.value = "";
$('.questionTextArea').val('');
}
function plusbutton() {
// Display an external page using an iframe
var src = "previousquestions.php";
$.modal('<iframe src="' + src + '" style="border:0;width:100%;height:100%;">');
return false;
}
function closewindow() {
$.modal.close();
return false;
}
$('.plusimage').live('click', function() {
plusbutton($(this));
});
function plusbutton(plus_id) {
// Set global info
plusbutton_clicked = plus_id;
// Display an external page using an iframe
var src = "previousquestions.php";
$.modal('<iframe src="' + src + '" style="border:0;width:100%;height:100%;">');
return false;
}
function addwindow(questionText) {
if(window.console) console.log();
var txt = $(this).val(questionText);
if($(plusbutton_clicked).attr('id')=='mainPlusbutton') {
$('#mainTextarea').val(txt);
} else {
$(plusbutton_clicked).parent('td').next('td.question').find('textarea.textAreaQuestion').val(txt);
}
$.modal.close();
return false;
}
</script>
</head>
<body>
<form id="QandA" action="<?php echo htmlentities($action); ?>" method="post">
<div id="detailsBlock">
<table id="question">
<tr>
<td rowspan="3">Question:</td>
<td rowspan="3">
<textarea class="questionTextArea" id="mainTextarea" rows="5" cols="40" name="questionText"></textarea>
</td>
</tr>
</table>
<table id="plus" align="center">
<tr>
<th>
<a onclick="return plusbutton();">
<img src="Images/plussign.jpg" width="30" height="30" alt="Look Up Previous Question" class="plusimage" id="mainPlusbutton" name="plusbuttonrow"/>
</a>
<span id="plussignmsg">(Click Plus Sign to look <br/> up Previous Questions)</span>
</th>
</tr>
</table>
<table id="questionBtn" align="center">
<tr>
<th>
<input id="addQuestionBtn" name="addQuestion" type="button" value="Add Question" onClick="insertQuestion(this.form)" />
</th>
</tr>
</table>
</div>
<hr/>
<div id="details">
<table id="qandatbl" align="center">
<thead>
<tr>
<th class="plusrow"></th>
<th class="question">Question</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</div>
</form>
</body>
The details stored in the modal window comes from a seperate script known as "previousquestions.php", Below is the code where it shows the result of the "QuestionContent" field only displayed and it's "Add" button after the user has compiled a search:
<?php
$output = "";
while ($questionrow = mysql_fetch_assoc($questionresult)) {
$output .= "
<table>
<tr>
<td class='addtd'><button type='button' class='add' onclick='parent.addwindow();'>Add</button></td>
</tr>";
}
$output .= " </table>";
echo $output;
?>
Thank you
Application here
The first issue is this ->
<button id="add">
You cannot reuse an ID over and over, or, the page will iterate to the last element with that ID and NEVER run anything on any previous elements.
Quick fix:
<button class="add">
Simple enough.
We need to get the question text, from the first column, there are so many methods to do this with jQuery selectors it's mind blowing.
Situation 1
Let's take a peek at one option ->
$(document).on('click', '.add', function(){
//now that we've declared the click function, let's jump up to our parent element, and grab the text in the first cell.
var theQuestion = $("td:first-child", $(this).parent()).text();
//Now that we've figured out how to traverse the DOM to get the data we want, we need to move that data elsewhere.
$('.questionTextArea').val(firstCell);
});
Simple enough, right? That should solve the first problem you had.
Note: Textareas use value to set the data, whereas other elements will use .text()
Situation 2
Alright, now we need to figure out how to add a unique identifier to the "+" row when we click, and check for that "unique identifier" when appending the data, let's do it.
You have a <td> with a class of plusrow, sounds good, let's make a click function out of it, and give it a cool new class to reference.
$(document).on('click', '.plusrow', function(){
//adding a unique class for the purpose of the click.
$(this).addClass('activePlusRow');
});
So now the "+" we clicked has a new class -- activePlusRow, let's go back to our initial click handler for the add button, and give it some new conditional statements.
$(document).on('click', '.add', function(){
//lets get our Question Text...
var theQuestion = $("td:first-child", $(this).parent()).text();
//the row is present, let's then make sure that the proper cell gets your data.
if($('.activePlusRow').length > 0){
$('.activePlusRow').next('.textAreaQuestion').val(theQuestion);
$('.activePlusRow').removeClass('activePlusRow');
}
});
Alright, as you can see of the above, we test to see if the activePlusRow class exists, if it does, then we iterate to the next textarea with a class of textAreaQuestion and change the value of it, to theQuestion from the .add button we clicked.
Let me know if you've any questions.
I think best way to target chosen question to specified textarea is to parameterise your plusbutton function:
function plusbutton(plus_id) {
// Set global info
plusbutton_clicked = plus_id;
// Display an external page using an iframe
var src = "previousquestions.php";
$.modal('<iframe src="' + src + '" style="border:0;width:100%;height:100%;">');
return false;
}
Of course you have to declare global var plusbutton_clicked; before insertQuestion function so other functions could change/use this information. You have to call this function with unique parameter for each plusbutton (you generate it dynamically, so this is up to you how you want to do it)
Then you can simply use it in your $(document).on('click', '.add', function(){}); - when user clicks 'add' button you have your plusbutton id so you can navigate with jQuery to corresponding textarea and place text there.
I'm thinking next() isn't the right function, since it only searches for the immediately following sibling... Try this:
$(document).on('click', '.add', function(){
console.log("clicked");
//lets get our Question Text...
var theQuestion = $("td:first-child", $(this).parent()).text();
//the row is present, let's then make sure that the proper cell gets oru data.
if($('.activePlusRow').length > 0){
$('.activePlusRow').next('.question').find('textarea.textAreaQuestion').val(theQuestion);
$('.activePlusRow').removeClass('activePlusRow');
}
$.modal.close();
return true;
});

Categories