Dynamically generating form elements using jquery - javascript

There are multiple paragraphs in the page. Each paragraph must be followed by a div with two buttons Add and Edit. Clicking the Add button should create a textarea dynamically above it.
Related references that didn't work:
How to use jQuery to add form elements dynamically
How to add (clone) form fields using jQuery and increment ids and names
DEMO
HTML code:
<div id="notes"></div>
In my JavaScipt:
<script>
// get notes in json format from php array
var notes = <?php echo json_encode($notes); ?>;
// call the scan function to iterate through the notes
scan(notes);
function scan(obj)
{
jQuery.each(obj, function(key, val) {
if (val instanceof Object) {
for ( var v in val ) {
if (val[v]['type'] == 'Topic') {
$("#notes").append('<h2 class="topic">'+val[v]['content']+'</h2>');
}
if (val[v]['type'] == 'Subtopic') {
$("#notes").append('<h4 class="subtopic">'+val[v]['content']+'</h4>');
}
if (val[v]['type'] == 'Concept') {
$("#notes").append('<h5 class="concept">'+val[v]['content']+'</h5>');
}
if (val[v]['type'] == 'Paragraph') {
$("#notes").append('<p>'+val[v]['content']+'</p>');
// append input for all paragraphs
$('#notes').append('<div class="paragraphs">');
$('#notes').append('<div id="block">');
$('#notes').append('<p class="edit"></p>');
$('#notes').append('<p>');
$('#notes').append('<div id="para">');
$('#notes').append('<p><textarea cols="40" rows="2" id="textarea"></textarea></p>');
$('#notes').append('<button id="add" class="add success tiny">Add</button>');
$('#notes').append(' ');
$('#notes').append('<button id="startEdit" class="canEdit tiny">Edit</button>');
$('#notes').append('</div>');
$('#notes').append('</p>');
$('#notes').append('</div>');
$('#notes').append('</div>');
}
scan(val[v]);
}
}
});
};
// Add paragraph button
i = 1;
$('#textarea'+i).hide();
text = $('#textarea'+i).text();
var data = '{"subject_id":'+$subject_id+',"teacher_id":'+$teacher_id+',"editedContent":"'+text+'"}';
$('.paragraphs').on('click', '#add'+i, function() {
if ( $('#add'+i).text() == "Add" ) {
ajaxRequest(data, 'editNotes', 'POST'); // POST request on editNotes
$('#textarea'+i).show();
$('#add'+i).text('Save');
$('#textarea'+i).focus(function() {
this.select();
});
}
else if ( $('#add'+i).text() == "Save" ) {
ajaxRequest(data, 'saveNotes', 'POST'); // POST request on saveNotes
if ($('#textarea'+i).val() == ''){
alert('Enter something...');
} else {
$('#add'+i).text("Add");
$('#textarea'+i).hide();
var overview = $('#textarea'+i).val();
i++;
console.log('after: i='+i);
$('.paragraphs').append('<div id="block'+i+'"><p class="edit'+i+'">'+overview+'</p><div id="para'+i+'"><p><textarea cols="40" rows="2" id="textarea'+i+'"></textarea></p><button id="add'+i+'" class="add'+i+' success tiny">Add</button><button id="startEdit'+i+'" class="canEdit'+i+' tiny">Edit</button></div></div>');
}
}
});
</script>
How do I add the form elements dynamically with incremental id and class names?
Any help is appreciated

unfortunately append does not work like it may seem, when you submit something like:
$('#element').append('<div>start here'):
$('#element').append('end here</div>'):
The very first call sent will close the div, it will actually create 2 separate elements. One way to help with this rather than having a large append as it can get kinda messy, is to create a variable and place all the elements into that variable and append it.
Example:
http://jsfiddle.net/h8V93/
var appends='<div class="paragraphs">'
+'<div id="block">'
+'<p class="edit"></p>'
+'<p>'
+'<div id="para">'
+'<p><textarea cols="40" rows="2" id="textarea"></textarea></p>'
+'<button id="add" class="add success tiny">Add</button>'
+' '
+'<button id="startEdit" class="canEdit tiny">Edit</button>'
+'</div>'
+'</p>'
+'</div>'
+'</div>';
$('#notes').append(appends);
I hope this helps.
Update
Edit for further reading, the best way to actually do this is to create an html page as a separate file and include it like so:::
$.get("<urlhere>", function (data) {
//Append, After, Before, Prepend data or whatever you want to do with it.
});
This is very convenient in GM or TM scripts where you keep the html file on your own server.
Hope this update helps future readers.
in recent versions of TM (tampermonkey), because of added cross domain origin policies, use GM_xmlhttpRequest -> http://wiki.greasespot.net/GM_xmlhttpRequest

Related

Get value from jQuery editor to PHP

I'm using this jquery plugin to create a wysiwyg text editor,
I created a textarea in PHP where:
<textarea name="body" id="body"><?php echo $body?></textarea>
and
<script type="text/javascript">
$(document).ready( function() {
$("#body").Editor();
});
</script>
Now i need to get value of this area for send it to SQL
if (isset($_POST['add-article'])) {
unset($_POST['add-article']);
$_POST['user_id'] = $_SESSION['id'];
$_POST['username'] = htmlentities($_SESSION['username']);
$_POST['published'] = isset($_POST['published']) ? 1 : 0;
// I need this line
$_POST['body'] = htmlentities($_POST['body']);
When I put text into this editor, it doesn't enter (value) into the textarea.
I have to have value before I press the add-article button, beacuse now it gives me an empty text.
I found something like this
function displayText(){
alert($("#body").Editor("getText"));
}
This causes it to return text ( i think only display by JS ) but i completely dont know how to use in my PHP scripts.
Second thing is when i write article and make a mistake something like ( Article title already exist ) ( in one session ) text in textarea stayed, but now doesn`t work it.
I think about if there is an error for example "Title already exist" follows:
} else {
$title = $_POST['title'];
$body = $_POST['body'];
$category_id = $_POST['category_id'];
$published = isset($_POST['published']) ? 1 : 0;
}
In my honest opinion i need something like:
add-article.addEventListener('click', function {
$body (from PHP) = alert($("#body").Editor("getText"))(from JS);
}
Thank you in advance for help.
On the plugin page you referenced, I see this is one of the recommendations. Capture the value you want when the click button is pressed, before the form submits.
Add a script to your form submit to put the texteditor content into this element
<form onsubmit='return getItReady()'>
Add an element to the form you'll use as a proxy element and keep it hidden, something like
<textarea id='txtEditorContent' name='txtEditorContent' style='visibility:hidden;height:0px' tabindex="-1"></textarea>
Then add the script to prepare it
<script>
function getItReady() {
console.log('The content:', $('#body').Editor("getText"));
$('#txtEditorContent').val($('#body').Editor("getText"));
return true;
}
</script>
Then in your PHP, it will come through as $_POST['txtEditorContent'].

Ajax/jQuery live search is duplicating the output results

I'm currently working on Ajax and jQuery live search which finds a results in a JSON file. Script is working fine, but the is only one problem - it's duplicating the result data.
EXAMPLE:
MARKUP:
<div class="row">
<h3>Live Search Results</h3>
<div id="update-results">
<p>event_name | club_name | memberid</p>
<ul id="update">
<!-- <li></li> -->
</ul>
</div>
</div>
SCRIPT:
$('#search').keyup(function() {
var searchField = $('#search').val();
var $update = $('#update');
$update.empty();
$.get("getEventsWithVideos.php?text=" + searchField, function(data) {
var vals = jQuery.parseJSON(data);
if($.isArray(vals['Event'])) {
$.each(vals['Event'], function(k,v){
$update.append("<li value='"+v['id']+"'><a href='#'>" + v['event_name'] + "</a></li>");
});
} else {
$update.append("<li value='"+vals['Event']['id']+"'><a href='#'>" + vals['Event']['event_name'] + "</a></li>");
}
});
});
I've tried to debug and stop the error, but it was unsuccessful. Can anyone help me please with that?
Put the empty() inside the response handler:
$.get("getEventsWithVideos.php?text=" + searchField, function(data) {
$update.empty();
basically you are clearing the list on every keystroke (rapid), then requesting the data, then (sometime later) appending the results that come back (which could be multiple results depending on the timing).
I didn't reproduce your error but I suspect that you have problem with multiple request to server and adding them all instead of last one. Probably adding below code will fix your problem
$update.empty();
Anyway I suggest you to use 2 more functions: throtlle and debounce from underscore to prevent too much request on every keyup.
Also you could try Rx.js witch give following example (https://github.com/Reactive-Extensions/RxJS):
var $input = $('#input'),
$results = $('#results');
/* Only get the value from each key up */
var keyups = Rx.Observable.fromEvent($input, 'keyup')
.map(function (e) {
return e.target.value;
})
.filter(function (text) {
return text.length > 2;
});
/* Now debounce the input for 500ms */
var debounced = keyups
.debounce(500 /* ms */);
/* Now get only distinct values, so we eliminate the arrows and other control characters */
var distinct = debounced
.distinctUntilChanged();
Try changing this line $update.empty(); of your code to $update.find('li').remove(); and put it inside the response handler.
This removes all the previous data before you append the new values. Hopefully it might work.

How can I retrieve input values from elements added after page load?

I'm working with Zend Framework 1.12 and I've need to be able to dynamically add and delete fields from a sub-form, in this case we're associating hyperlinks to a parent "promotion".
I haven't found a way to accomplish dynamically adding and removing elements via Zend, and the rare tutorial I've found that claimed to do this are half a decade old and aren't working when I attempt them.
So what I am doing is storing the links I need to work with in a Zend Hidden input field and then dealing with the JSON data after I submit. Not very efficient, but it's the only thing I've gotten to work so far.
Below is the section of the code I'm working with:
Assume a form like:
<form action="/promos/edit/promo_id/15" method="POST" id="form_edit">
<!-- input is Zend_Form_Element_Hidden -->
<input type="hidden" id="link_array" value="{ contains the JSON string }"/>
<button id="add_link">Add Link</button>
</form>
The purpose is that every time the Add Link button is pressed, the form adds fields to allow the user to input new hyperlinks that will be associated with the specific items.
Here's the function:
// add links
$('#add_link').click(
function(e) {
e.preventDefault();
link = '<div class="p_link new_link">' +
'<div class="element_wrap">' +
'<label for="link_name" class="form_label optional">Text: </label>' +
'<input type="text" id="new_link_name" name="link_name"/>' +
'</div>' +
'<div class="element_wrap">' +
'<label for="link_http" class="form_label optional">http://</label>' +
'<input type="text" id="new_link_http" name="link_http"/>' +
'</div>' +
'<div class="element_wrap">' +
'<button class="submit delete_link">Delete</button>' +
'</div>' +
'</div>';
$('#add_link').prev().after(link);
}
);
Now, what I need to do is on submit, for every new_link class element, to take the links name and http reference and place it in a json object. Here's the code as I have it so far (I know I don't have both input fields represented at this point):
$('#submit').click(
function(e) {
e.preventDefault();
var link_array = [];
var new_links = document.getElementsByClassName('new_link');
$.each(new_links, function() {
console.log(this);
var n = $(this).children('#new_link_name').text();
console.log(n);
link_array.push({'link_name':n}); //'link_http':h
});
console.log(JSON.stringify(link_array));
}
);
My problem is that: var new_links = document.getElementsByClassName('new_link'); will collect all the newly added new_link elements, but it does not pull in any value that has been input into the text fields.
I need to know how I can apparently bind any input I make to the input field's value attribute, because right now anything I type into these new elements are tossed out and the field appears empty when it's anything but.
$('#submit').click(
function(e) {
e.preventDefault();
var link_array = [];
var new_links = $('.new_link');
$.each(new_links, function() {
console.log(this);
var n = $(this).find('input').val(); // you need input values! This line //is changed...
console.log(n);
link_array.push({'link_name':n}); //'link_http':h
});
console.log(JSON.stringify(link_array));
}
);
JSFIDDLE: http://jsfiddle.net/DZuLJ/
EDit: You can't have multiple IDS (make class for each input, and target class, if you want link names and http's)

How can I create dynamic controls and put their data into an object?

I created a div and a button. when the button clicked, there will be a group of element(included 1 select box and 2 text inputs) inserted into the div. User can add as many group as they can, when they finished type in data of all the group they added, he can hit save button, which will take the value from each group one by one into the JSON object array. But I am stuck in the part how to get the value from each group, so please help, thank you.
The code for the div and the add group button function -- AddExtra() are listed below:
<div id="roomextra">
</div>
function AddExtra() {
$('#roomextra').append('<div class=extra>' +
'<select id="isInset">' +
'<option value="Inset">Inset</option>' +
'<option value="Offset">OffSet</option>' +
'</select>' +
'Length(m): <input type="text" id="insetLength">' +
'Width(m): <input type="text" id="insetWidth">' +
'Height(m): <input type="text" id="insetHeight">' +
'</div>');
}
function GetInsetOffSetArray (callBack) {
var roomIFSDetail = [{
"IsInset": '' ,
"Length": '' ,
"Width": '' ,
"Height": ''
}];
//should get all the value from each group element and write into the array.
callBack(roomIFSDetail);
}
This should just about do it. However, if you're dynamically creating these groups, you'll need to use something other than id. You may want to add a class to them or a data-* attribute. I used a class, in this case. Add those classes to your controls so we know which is which.
var roomIFSDetail = [];
var obj;
// grab all of the divs (groups) and look for my controls in them
$(.extra).each(function(){
// create object out of select and inputs values
// the 'this' in the selector is the context. It basically says to use the object
// from the .each loop to search in.
obj = {
IsInset: $('.isInset', this).find(':selected').val() ,
Length: $('.insetLength', this).val() ,
Width: $('.insetWidth', this).val() ,
Height: $('.insetHeight', this).val()
};
// add object to array of objects
roomIFSDetail.push(obj);
});
you'd better not to use id attribute to identity the select and input, name attribute instead. for example
$('#roomextra').append('<div class=extra>' +
'<select name="isInset">' +
'<option value="Inset">Inset</option>' +
'<option value="Offset">OffSet</option>' +
'</select>' +
'Length(m): <input type="text" name="insetLength">' +
'Width(m): <input type="text" name="insetWidth">' +
'Height(m): <input type="text" name="insetHeight">' +
'</div>');
}
and then, usr foreach to iterate
$(".extra").each(function() {
var $this = $(this);
var isInset = $this.find("select[name='isInset']").val();
var insetLength = $this.find("input[name='insetLength']").val();
// ... and go on
});
A common problem. A couple things:
You can't use IDs in the section you're going to be repeating, because IDs in the DOM are supposed to be unique.
I prefer to use markup where I'm writing a lot of it, and modify it in code rather than generate it there.
http://jsfiddle.net/b9chris/PZ8sf/
HTML:
<div id=form>
... non-repeating elements go here...
<div id=roomextra>
<div class=extra>
<select name=isInset>
<option>Inset</option>
<option>OffSet</option>
</select>
Length(m): <input id=insetLength>
Width(m): <input id=insetWidth>
Height(m): <input id=insetHeight>
</div>
</div>
</div>
JS:
(function() {
// Get the template
var container = $('#roomextra');
var T = $('div.extra', container);
$('#addGroup').click(function() {
container.append(T.clone());
});
$('#submit').click(function() {
var d = {};
// Fill d with data from the rest of the form
d.groups = $.map($('div.extra', container), function(tag) {
var g = {};
$.each(['isInset', 'insetLength', 'insetWidth', 'insetHeight'], function(i, name) {
g[name] = $('[name=' + name + ']', tag).val();
});
return g;
});
// Inspect the data to ensure it's what you wanted
debugger;
});
})();
So the template that keeps repeating is written in plain old HTML rather than a bunch of JS strings appended to each other. Using name attributes instead of ids keeps with the way these elements typically work without violating any DOM constraints.
You might notice I didn't quote my attributes, took the value attributes out of the options, and took the type attributes out of the inputs, to keep the code a bit DRYer. HTML5 specs don't require quoting your attributes, the option tag's value is whatever the text is if you don't specify a value attribute explicitly, and input tags default to type=text if none is specified, all of which adds up to a quicker read and slimmer HTML.
Use $(".extra").each(function() {
//Pull info out of ctrls here
});
That will iterate through all of your extra divs and allow you to add all values to an array.

How to write .trigger() code for the template?

I have a table below which contains a textbox and next to the textbox it contains a hyperlink known as "Open Grid". If the user clicks on this link, it opens up a grid and on this grid it displays number buttons from 3 - 26.
<table id="optionAndAnswer" class="optionAndAnswer">
<tr class="option">
<td>1. Option Type:</td>
<td>
<div class="box">
<input type="text" name="gridValues" class="gridTxt maxRow" id="mainGridTxt" readonly="readonly" />
<span href="#" class="showGrid" id="showGridId">[Open Grid]</span>
</div>
<table class="optionTypeTbl">
<tr>
<tr><td><input type="button" value="3" id="btn3" name="btn3Name" class="gridBtns gridBtnsOff">
<input type="button" value="4" id="btn4" name="btn4Name" class="gridBtns gridBtnsOff">
<input type="button" value="5" id="btn5" name="btn5Name" class="gridBtns gridBtnsOff">
<input type="button" value="6" id="btn6" name="btn6Name" class="gridBtns gridBtnsOff">
//...goes all the way to btn26
</tr>
</table>
</td>
</tr>
</table>
Now the code below is able to trigger one of the grid buttons to state that a grid button is clicked. This code is below:
$('#btn'+gridValues).trigger('click');
Now everything above is fine.
THE PROBLEM:
The issue I have is that a user can add a row containing the same template as the option control on top. But within this option and answer control, the user can change an option type if they wish by clicking on one of the grid buttons in this template. So my question is that how do I write the .trigger() to correctly point to a grid button within this template? If you look at the above code, it users the button's id, but if you look at code below which does the template, it doesn't contain an id, it simply just copies the option and control features from above into the template.
Below is the template:
function insertQuestion(form) {
var context = $('#optionAndAnswer');
var $tbody = $('#qandatbl > tbody');
var $tr = $("<tr class='optionAndAnswer' align='center'>");
var $options = $("<div class='option'>Option Type:<br/></div>");
var $questionType = '';
$('.gridTxt', context).each( function() {
var $this = $(this);
var $optionsText = $("<input type='text' class='gridTxtRow maxRow' readonly='readonly' />")
.attr('name',$this.attr('name')+"[]")
.attr('value',$this.val())
.appendTo( $options )
.after("<span href='#' class='showGrid'>[Open Grid]</span>");
$questionType = $this.val();
});
$td.append($options);
$tbody.append($tr);
}
UPDATE:
I have created a URL for this application here. Please follow the steps to use the application and then you can see what is happening:
Step 1: When you open application, you see a green plus button on the
page, click on it and it will display a modal window.
Step 2: In modal window there is a search bar, type in "AAA" and
submit search, you will see a bunch of rows appear.
Step 3: In the first row, you see under "Option Type" A-D, click on
the "Add" button within this row, the modal window will close and you
see in the grey textbox on right hand side that "Option Type" textbox
equals 4 and it displays the Answer buttons A,B,C and D, this is
because as you remember the option type for that row was "A-D".
Now this works fine but it only works for the top option and answer control, follow the steps below:
Step 4: Click on the "Add Question" button, it adds a row underneath
containing the details from the option and answer control on top.
Step 5: Within the row you have just added, you see a green plus
button on left hand side, click on this button and perform the same
search "AAA" in search box.
Step 6: This time select the last row by clicking on its "Add"
button, the "Option Type" for this row is "A-G" so it should display
"Answer" buttons A,B,C,D,E,F and G, but it doesn't do this, it still
states "A,B,C,D".
So how do I change the answer buttons display in the option and answer control within one of the appended rows?
The addwindow() function you see in the view source in the application is the function which occurs after the "Add" button is clicked on. The "Add" button is in an included PHP script and the code for this button is below and with it are all the columns you see after you have performed a search in the modal window:
echo "<table border='1' id='resulttbl'>
<tr>
<th class='questionth'>Question</th>
<th class='optiontypeth'>Option Type</th>
<th class='noofanswersth'>Number of <br/> Answers</th>
<th class='answerth'>Answer</th>
<th class='noofrepliesth'>Number of <br/> Replies</th>
<th class='noofmarksth'>Number of <br/> Marks</th>
</tr>";
foreach ($searchResults as $key=>$question) {
echo '<tr class="questiontd"><td>'.htmlspecialchars($question).'</td>';
echo '<td class="optiontypetd">'.htmlspecialchars($searchOption[$key]).'</td>';
echo '<td class="noofanswerstd">'.htmlspecialchars($searchNoofAnswers[$key]).'</td>';
echo '<td class="answertd">'.htmlspecialchars($searchAnswer[$key]).'</td>';
echo '<td class="noofrepliestd">'.htmlspecialchars($searchReply[$key]).'</td>';
echo '<td class="noofmarkstd">'.htmlspecialchars($searchMarks[$key]).'</td>';
echo "<td class='addtd'><button type='button' class='add' onclick=\"parent.addwindow('$question','$searchMarks[$key]','$searchNoofAnswers[$key]','$searchOption[$key]','$searchReply[$key]','$searchAnswer[$key]');\">Add</button></td></tr>";
}
echo "</table>";
I'm afraid I must be the bearer of bad news. The problem you are having stems from the overall design. Your HTML and javascript really need a bottom-up overhaul with the aim of getting all javascript into a single $(function(){...}) structure, and thus into the same scope. To achieve this you will need to :
Attach all event handlers in javascript in favour of the HTML attribute approach (currently hybrid).
Purge the iFrame in favour of fetching previous questions via AJAX.
In the process you will also purge some duplicate click handling (plus button img and its <a>...</a> wrapper).
Then, you can start to find a solution to your problem :
Delegate all event handling associated with the original "Option and answer" block to a container that is common to it and all future "Option and answer" blocks. The common container may be document but preferably something more specific. This appears to be partly achieved already.
Ensure that all internal referencing within the original "Option and answer" block works with classes rather than ids. .closest() and .find() will be useful here.
On clicking the "+" button, store a reference to the "Option and answer" block (eg. a jQuery object representing its container, discovered relatively). Easiest approach is to store this reference in a variable in the $(function(){...}) scope. (Now you are benefiting from making all those structural changes). The "Add" buttons' click handler will use this reference to affect the correct "Option and answer" block.
On "Add Question", use jQuery's .clone(true, true) to make a copy of the original block (then insert the clone into the DOM). If the other fixes have been applied, then all functionality (click handlers) will attach to the clone automatically.
I work quite quickly but it would still allow 1-2 days for this.
Here's how I would organise the javascript.
$(function() {
// **********
// Data area
// **********
var $$ = { // reusable static jQuery objects
'optionTypeTbl': $('#optionTypeTbl'),
'o_and_a_proto': $("#proto"),
'o_and_a_extras': $("#extras"),
'modal': $("#modal")
},
$o_and_a_section = null;
// ******************
// Utility functions
// ******************
function trim(str) {
return str.replace(/(^\s*)|(\s*$)/gi, "") // removes leading and trailing spaces
.replace(/[ ]{2,}/gi," ") // replaces multiple spaces with one space
.replace(/\n +/,"\n"); // Removes spaces after newlines
}
// ****************
// Initial actions
// ****************
$$.modal.hide();
$("input.gridBtns").removeClass("gridBtnsOn");
$("input.answerBtns").removeClass("answerBtnsOn");
$$.optionTypeTbl.hide();
// code above makes sure all buttons start in the OFF state (so all button are white).
// **********************************************
// Handlers for elements inside the main window
// **********************************************
$(document).on('click', function() {
$$.optionTypeTbl.fadeOut('slow');
});
$("input.gridBtns", $$.optionTypeTbl).on('click', function() {
var $this = $(this);
var $container = $this.closest('.optionAndAnswer');
$container.find(".gridBtns").removeClass("gridBtnsOn");
$this.addClass("gridBtnsOn");
$container.find(".gridTxt").val($this.val());
//$container.siblings('span[name=gridValues[]]').val($this.val()); // ???
$container.find('.answerBtns').each(function(index) {
if (index < Number($this.val())) {
$(this).show();
} else {
$(this).hide();
}
});
});
$$.o_and_a_proto.find(".showGrid").on('click', function(e) {
var $this = $(this);
var $container = $this.closest(".optionAndAnswer");
$("input.gridBtns").removeClass("gridBtnsOn");
var value = $container.find(".gridTxt").val();
//$("#btn" + value.replace(/\s/g, '')).addClass("gridBtnsOn"); //???
$$.optionTypeTbl.appendTo($this.closest("div.box")).show().css({
left: $this.position().left,
top: $this.position().top + 20
});
e.stopPropagation();
});
$$.o_and_a_proto.find(".plusimage").on('click', function() {
$o_and_a_section = $(this).closest(".optionAndAnswer");
$$.modal.modal();
});
$$.o_and_a_proto.find(".answerBtns").on('click', function() {
//btnclick(this); // ???
});
$("#addQuestionBtn").on('click', function insertQuestion() {
$$.optionTypeTbl.hide().appendTo(document);//ensure this itinerant table is not cloned
$$.o_and_a_extras.append($$.o_and_a_proto.clone(true,true).attr('id','')).find("span#plussignmsg").remove();
});
// **********************************************
// Handlers for elements inside the modal window
// **********************************************
$$.modal.find("#close").on('click', function() {
$.modal.close();
return false;
});
$$.modal.find("form").on('submit', function() {
var form = $(this).get(0);
$.ajax({
url: 'previousquestions.php',
data: {
'searchQuestion': 1,
'questioncontent': trim(form.questioncontent.value)
},
type: "get",
success: function(html) {
$("#searchResults").html(html);
},
error: function() {
alert("Something went wrong");
}
});
return false;
});
$$.modal.find("#searchResults").on('click', 'button.add', function() {
var $container = $(this).closest("tr");
var g = $container.find("optiontypetd").data('g');
var btn = $container.find("answertd").text();
$o_and_a_section.find("input.gridTxt").val(g);
if($o_and_a_section.closest("#detailsBlock").length) { //if is original Options and Answers section
//do something ???
//$('#btn'+g).trigger('click'); //???
}
$.modal.close();
});
});
This works to an extent, but please note that it requires associated changes to the HTML and CSS.

Categories

Resources