ajax-calls into an ajax-call - php

I've got this problem that I can't solve. Partly because I can't explain it with the right terms. I'm new to this so sorry for this clumsy question.
Below you can see an overview of my goal. I want to search some stuff from a database (with ajax) and display the results in a div below the search. This I can get this to work. But now, I want to be able to click on a result and get it in a div on top of the page.
I learned it is normal that ajax can not handle this sort of actions and it is not possible to run jquery or other ajax-calls into an ajax-call.
I also read things about jquery live() to work around this problem.
Still it is not clear to me how to make things work.
Is it possible to put me on the right track? Are there tutorials I missed?
thank you!
step one
<div id="top">here comes an image</div>
<textfield> for the ajax search string + a button </textfield>
<div id="search">target of the ajax-search</div>
step two: after a search we get this
<div id="top">here comes an image</div>
<textfield> for the ajax search string + a button </textfield>
<div id="search">result 01 with link to a php-file: a
result 02 with link to a php-file: b ... </div>
step tree: after click on result 01 or 02 ...
<div id="top">content of php-file: a</div>
<textfield> for the ajax search string + a button </textfield>
<div id="search">result 01 with link to a php-file: a
result 02 with link to a php-file: b ... </div>
ok, here comes part of the (relevant) code
search_page.php
<div id=top"></div>
<div class="client_search_field">
<form id="ui_element" class="sb_wrapper" action="" method="post" name="search_ID" ONSubmit="xmlhttpPost('search_stream_client_v02.php', 'ui_element', 'txtHint', '<img src=\'images/wait.gif\'>'); return false;">
<p> <span class="sb_down"></span>
<input name="search_string" type="text" class="sb_input" id="search_string" value="<?php echo $_POST['search_string']; ?>"/>
<button type="submit" class="submitmag" id="search_submit" > </button>
</p>
</div>
<span id="txtHint"></span>
search_stream_client_v02.php
<?php
$sql .= "SELECT *";
$sql .= ", MATCH(description, keywords) AGAINST ('".$_POST['search_string']."') AS score FROM archief WHERE MATCH(description, keywords) AGAINST('".$_POST['search_string']."' IN BOOLEAN MODE)";
$sql .= " AND showa = '1' ";
$sql .= $q_sort." ".$q_order." LIMIT 0,".$q_num_result;
$result04 = mysql_query($sql) or die(mysql_error());
while ($row04 = mysql_fetch_assoc($result04)){
$hint .= "<div class=\"tb-kader\">";
$hint .= "<span id=\"".$row['thumbnail']."\">";
$hint .= "<a href=\"".$row04['link']."\" class=\"fra tooltip lazy\" id=\"".$row04['ID']."\" TITLE=\"header=[".$row04['headline']."] body=[".$row04['description']."]\">";
$hint .= "<img src=\"$row04[thumbnail]\" border=\"0\" alt=\"".$row04['headline']."\"/></a>";
$hint .= "<div class=\"tb-kader-price\">".$pic_list_solo_final[$items03]['prijs']." €</div></span>";
$hint .= "</div>";
}
echo $hint;
?>
so, at the end the
<a href=\"".$row04['link']></a>
should open in the
<div id="top"></div>
thank you guys for your effort!!
EDIT
This one is not working:
$('#search').delegate(".fra", "click", function() {
$("#top").attr("src","href");
});

$('#search').delegate(".fra", "click", function() {
$("#top").attr("src","href");
});
What this does is just setting the scr attribute of #top to "href". That's not what you want ;) What you need is, I think:
$('#search').delegate(".fra", "click", function() {
var link = $(this),
url = link.attr("href");
$.ajax({
url: url,
dataType: "html",
success: function(data) {
$("#top").html(data);
}
})
});

so you want to do something like:
$('.search-result-class').live('click', function() {
//this binds to the click of each result. So you can do an ajax call here and on the success callback you could then load the result into the div
});

Or you can use .delegate, like this:
html
<div id="search">
result 01 with link to a php-file: a
result 02 with link to a php-file: b ...
</div>
js
// binds a click event on each result, even if they've been loaded via ajax
$('#search').delegate(".result", "click", function() {
var link = $(this),
url = link.attr("href");
// do your ajax magic...
$.ajax({url: url...})
});
It's basically the same idea than Victor's answer, but .delegate is more performant I think.

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 :)

onclick function are not working?

code:
<input type="text" name="college_name" id="college_name" placeholder="Search By College Name" >
<div id="box"></div>
<script>
$(document).ready(function() {
$("#college_name").keyup(function() {
$.ajax({
type: "POST",
url: "colleges.php",
data: 'keyword=' + $(this).val(),
success: function(data) {
$("#box").show();
$("#box").html(data);
}
});
});
});
function selectCollege(val) {
$("#college_name").val(val);
college_name = $("#college_name").val();
location.href = "college-details.php?college_name=" + college_name;
$("#box").hide();
}
</script>
college.php
<?php
$tempcollege .= "<a href='#' style='color:#fff;'><li onClick=selectCollege('".$college_name."''".$field."');>".$college_name.$field."</li></a>";
?>
In this code I have created a autocomplete box where all colleges are displaying when I keyup on input field but when click on any college then it not go to link i.e. college-details.php. So, How can I fix this problem ?please help me.
Thank You
There seem to be multiple issues in your college.php:
normally <li> should be outside <a>,
href equals to "#", which in some cases causes browser to load/reload a page and since click event is also bubbled to <a>,
You can avoid this two ways.
Either replace href='#' with href='javascript:void(0)'
<?php
$tempcollege .= "<li onClick=selectCollege('".$college_name."''".$field."');><a href='javascript:void(0)' style='color:#fff;'>".$college_name.$field."</a></li>";
?>
or cancel event bubbling and executing default behaviour of <a> tag in onClick by returning false.
<?php
$tempcollege .= "<li onClick=\"selectCollege('".$college_name."''".$field."'); return false;\"><a href='#' style='color:#fff;'>".$college_name.$field."</a></li>";
?>
Worst case scenaro if you cannot edit the college.php, then add window.event.preventDefault(); to selectCollege() function:
function selectCollege(val) {
window.event.preventDefault();
$("#college_name").val(val);
college_name = $("#college_name").val();
location.href = "college-details.php?college_name=" + college_name;
$("#box").hide();
}
There is also another error: selectCollege('".$college_name."''".$field."'); generates code selectCollege('Some college name''Some field');, which contains two apostrophes going in a row. It seems you wanted selectCollege('Some college nameSome field');, so really you should also fix the code to selectCollege('".$college_name.$field."'); or selectCollege('".$college_name."'+'".$field."');
Replace
<?php
$tempcollege .= "<a href='#' style='color:#fff;'><li onClick=selectCollege('".$college_name."''".$field."');>".$college_name.$field."</li></a>";
?>
With
<?php
$tempcollege .= "<a href='#' style='color:#fff;'><li onclick=selectCollege('".$college_name."''".$field."');>".$college_name.$field."</li></a>";
?>
$tempcollege .= "<li><a onclick='callfunction();' style='color:#fff;'>click</a></li>";
When you set click event on <a> tag at time please remove href="#" attribute with href some cases causes browser reload a page and since click event not work.

ng click not working on jquery append / how to directive dynamic tags

first of all i really cant get/understand the use of directive in dynamic way like after button submit then append in particular div.
in result i used jquery in appending elements in angular. my problem is ng-click is not binding on appended elements
below is my code for controller and draw function of my element
VIEW
<div class="box" ng-controller="addWorkOrder">
<div class="box-header with-border">
New Work Load
</div>
<div class="box-body">
<div class="form-group">
<input class="form-control" id="add_wl" ng-model="addwo_title" placeholder="Add Work Load">
</div>
<div class="form-group" id="add_wl_div" style="display:none">
<button type="" class="btn bg-olive pull-right" ng-click="click_addwo()">Add</button>
</div>
</div><!-- /.box-body -->
</div><!-- /.box -->
Angular Controller
app.controller('addWorkOrder',['$scope','$rootScope','$http','$compile',function($scope,$rootScope,$http,$compile){
$scope.$watch('project_id',function(){
$scope.click_addwo = function(){
$http.post(base_url+'ajax/add_workorder',{proj_id:$rootScope.project_id,wo_title:$scope.addwo_title})
.then(function(response){
if(response.data.success == 0){
alert(response.data.msg);
}else{
draw_workorder({
wo_id : response.data.data,
wo_title : $scope.addwo_title
});
$scope.addwo_title = "";
}
});
}
});
}]);
lastly my function draw_workorder() to be called upon success of submit button
function draw_workorder(data){
// workorder card view
l = '<tr data-id="'+ data.wo_id +'" style="display:none;">'+
'<td style="width:30px"></td>'+
'<td class="mailbox-name">'+ data.wo_title +'</td>'+
'<td class="mailbox-subject"><span class="badge bg-red">pending</span></td>'+
'<td class="mailbox-attachment"></td>'+
'<td class="mailbox-date" data-livestamp="'+ new Date().toLocaleString() +'"></td>'+
'</tr>';
$(l).prependTo('#wo_container').fadeIn();
}
anyone can teach me how to properly append/prepend elements using directives after http service ins controller is much appreciated
once again im sorry for being newbie in angular. i tried my best to read Angular Directive documentation and it seems other examples they give is so complicated for me.
what you need to do is to let Angular know, that your element actually has directives. This can be achieved by using $compile service, here, I simplified your example jsfiddle
app.controller('addWorkOrder', ['$scope', '$rootScope', '$http', '$compile',
function($scope, $rootScope, $http, $compile) {
$scope.click_addwo = function() {
l = '<button type="" ng-click="attachedFunct()">Click Me!</button>';
$('#wo_container').append($compile(l)($scope));
};
// Function that will be used by dynamically added element.
$scope.attachedFunct = function() {
alert('Clicked attached function');
};
}
]);
Your ng-click is not working because you need to compile the html before you append it to some element.
var $compile = ...; // injected into your code
var scope = ...;
var parent = ...; // DOM element where the compiled template can be appended
var html = '<div ng-bind="exp"></div>';
// Step 1: parse HTML into DOM element
var template = angular.element(html);
// Step 2: compile the template
var linkFn = $compile(template);
// Step 3: link the compiled template with the scope.
var element = linkFn(scope);
// Step 4: Append to DOM (optional)
parent.appendChild(element);
for more info please go to this link

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);

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