I am working on a new system and am stuck at a point with jquery + ajax and getting it work work correctly with the other things happening on the page.
Basically the page is to submit a quote and on the page you can add as many quote items as you want. When someone clicks on new item it runs the below code wich gets the value of a hidden element and uses it in all of the new elements Ids in order to keep them all unique.
New Product code:
function addFormField() {
var id = document.getElementById("field_id").value;
$("#products").append("
<table width='600' cellpadding='5' cellspacing='0' class='Add_Products' id='row" + id + "'>
<td width='250' class='left'>
<label>Select Product Category</label>
</td>
<td class='right' >
<label><select name='ProductCategory' id='ProductCategory'>
<?php foreach($categories as $key=>$category){
echo "<option value=".$key.">".$category."</option>";
}
?>
</select>
</label>
</td>
</tr>
<tr>
<td width='250' class='left'>
<label>Select Product Template</label>
</td>
<td class='right' >
<label>
<select name='data[QuoteItem][" + id + "][product_id]' id='QuoteItem" + id + "product_id'></select>
</label>
</td>
</tr>
<tr >
<td class='left'>Name</td>
<td class='right'>
<label>
<input name='data[QuoteItem][" + id + "][name]' type='text' id='QuoteItem" + id + "name' size='50' />
</label>
</td>
</tr>
<tr >
<td class='left'>
Price (ex GST)
</td>
<td class='right'>
<input type='text' name='data[QuoteItem][" + id + "][price]' id='QuoteItem" + id + "price' onchange='totalProductPrice();' class='quote-item-price' />
</td>
</tr>
<tr>
<td class='left'>
Description
</td>
<td class='right'>
<label>
<textarea name='data[QuoteItem][" + id + "][description]' cols='38' rows='5' id='QuoteItem" + id + "description'>
</textarea>
</label>
</td>
</tr>
<tr>
<td>
<a href='#' onClick='removeFormField(\"#row" + id + "\"); return false;'>Remove</a>
</td>
</tr>
</table>
");
$('#row' + id).highlightFade({
speed:1000
});
id = (id - 1) + 2;
document.getElementById("field_id").value = id;
}
The next thing i want to do is setup an AJAX query using jQuery that when selected will request the appropriate data and populate the products box but i cannot figure out how to get the ID of that set of elements to ensure that the correct dropdown box is populated and also to make sure that the onchange is detected for the correct box.
Ive tried methods like adding the ID to the id of the dropdown box but then the onchagne doesnt work.
My jquery ajax code is below that retreives the list of products
$(function(){
$("select#ProductCategory").change(function(){
var url = "productList/" + $(this).val() + "";
var id = $("select#ProductCategory").attr('name');
$.getJSON(url,{id: $(this).val(), ajax: 'true'}, function(j){
var options = '';
options += '<option value="0">None</option>';
$.each(j, function(key, value){
options += '<option value="' + key + '">' + value + '</option>';
})
$("select#QuoteItem" + id + "product_id").html(options);
})
})
})
For the life on my cannot figure this out so if anyone could shed some light on the best way to do it that would be great.
ALso if i need to clarify further let me know because im strugling to explain it.
Thanks in advance
I have similar functionality in my project. Here how I do it:
I have a global variable that start with 0, and increased every time new field added:
var num = 0;
jQuery(function($){
$("#add_field").click(function(){
num++;
//here add new field, with id contains 'num'
});
});
to make it easier to debug, you should start with a simple element, test it so it's bug free, and add more field to it.
To submit form via AJAX, use jQuery form plugins, so you don't need to add all fields manually in ajax code that submit the form.
Related
I am trying to bind column dynamically in a table using jQuery .but click event is not working while trying to click 'btnASizeR' and 'btnWdDelete' button event is not working .Any idea would be appreciated.
$(function() {
var i = 0;
$('#btnASizeR').click(function() {
/* To check the count of already exist tr in WireDimTbl and then assigning the i value for controlids*/
var i = $("#WireDimTbl tbody>tr").length + 1;
/* To check the count of already exist tr in WireDimTbl and then assigning the i value for controlids*/
var sizerangeMin = "<input type='text' ID='SizeMin" + i + "' name='SizeMin' value='2.00' />";
var sizerangeMax = "<input type='text' ID='SizeMax" + i + "' name='SizeMax' value='3.00' />";
var ToleranceMin = "<input type='text' ID='TolMin" + i + "' name='TolMin' value='1' />";
var ToleranceMax = "<input type='text' ID='TolMax" + i + "' name='TolMax' value='1' />";
var markup = "<tr><td>" + sizerangeMin + "</td><td>" + sizerangeMax + "</td><td>" + ToleranceMin + "</td><td>" + ToleranceMax + "</td></tr>";
$("#WireDimTbl tbody").append(markup);
});
$('#btnWdDelete').click(function() {
$("#WireDimTbl tbody>tr:last").remove();
})
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<tr>
<td class='text-left'><strong>Wire Dimensions</strong></td>
</tr>
<tr>
<td class='text-left'><strong>Standard Sizes & Tolerances</strong></td>
<td>
<input type="button" id="btnASizeR" value="AddSizeRange" />
<input type="button" id="btnWdDelete" value="Delete" />
<table id="WireDimTbl" class="table table-bordered">
<thead>
<tr>
<th class="text-center">Size Range Min (mm)</th>
<th class="text-center">Size Range Max (mm)</th>
<th class="text-center">Tolerance (-)mm</th>
<th class="text-center">Tolerance (+) mm</th>
</tr>
</thead>
<tbody></tbody>
</table>
</td>
</tr>
You mentioned that you are loading the table dynamically. Do you mean that when the page first loads the table is missing and its added later?
If that is the case, are you sure the code is called that binds the click events? The above example binds the events on page_load however, if the buttons are not yet available on the page it won't be able to bind it. JQuery will not automatically bind future elements.
Try settings a console.log($('#btnASizeR')); before binding the click event to make sure that JQuery can actually find the button.
I have written some code in Jquery that when a button is pressed, creates a new variable and displays it on the screen. I'd like to take whatever data is entered into this new variable and store it in a database however before I get there I have to figure out to access the variables information properly.
In HTML I have 3 text boxes created and a button to add up to 7 more for a total of 10. My code looks like this (and these store in the database just fine):
<table style="width:90%" class="Long-Term-Conditions">
<center>
<tr>
<td><b><center>Long term condition 1:</center></b></td>
<td><center><input type='text' id="Var1" name ='Var1' value='%Var1%' /></center></td>
</tr>
<tr>
<td><b><center>Long term condition 2:</center></b></td>
<td><center><input type='text' id="Var2" name ='Var2' value='%Var2%' /></center></td>
</tr>
<tr>
<td><b><center>Long term condition 3:</center></b></td>
<td><center><input type='text' id="Var3" name ='Var3' value='%Var3%' /></center></td>
</tr>
</center>
</table>
Add another long-term health condition
<div id="Message"></div>
My problem now is that my Jquery variables cant be inspected (says not available) and no data is passed to the database after. My Jquery looks like this:
<script>
//Adds another row to the above table.
var counter = 3;
jQuery('a.add-cond').click(function(event){
event.preventDefault();
if (counter < 10) {
counter++;
var newRow = jQuery('<tr><td><b><center>'+ "Long term condition "+ counter + ":" + '</center></td> <td><center><input type="text" name="Var' +
counter + '" id="Var' + counter + 'value="%Var' + counter + '%"/></center></b></td></tr>');
jQuery('table.Long-Term-Conditions').append(newRow);
}
else
{
document.getElementById("add-cond").style.visibility = "hidden";
document.getElementById("Message").innerHTML = '<font color="Red">Please
contact us</font>';
}
});
</script>
The code works in creating the new variable however any data entered into the newly created text box is never passed to the debugger or the database. What am I doing wrong? Any help is appreciated.
The problem you are having is that when you bind the click event to the elements it only binds to the elements that already exist on the document. So when you add new ones it won't trigger that click event because you didn't bind it to the new ones.
A simple solution to this is to add the click event listener to the body like so:
jQuery('body').on('click', 'a.add-cond', function(event){
I think that is what you are looking for.
Also like the other guy mentioned you are missing a closing quote and a space
id="Var' + counter + 'value="%Var' + counter + '%"
Should be:
id="Var' + counter + '" value="%Var' + counter + '%"
I think you were just missing a " between the id and value of your new input
//Adds another row to the above table.
var counter = 3;
jQuery('a.add-cond').click(function(event) {
event.preventDefault();
if (counter < 10) {
counter++;
var newRow = jQuery('<tr><td><b><center>' + "Long term condition " + counter + ":" + '</center></td> <td><center><input type="text" name="Var' +
counter + '" id="Var' + counter + '" value="%Var' + counter + '%"/></center></b></td></tr>');
jQuery('table.Long-Term-Conditions').append(newRow);
} else {
document.getElementById("add-cond").style.visibility = "hidden";
document.getElementById("Message").innerHTML = '<font color="Red">Please contact us </font>';
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table style="width:90%" class="Long-Term-Conditions">
<center>
<tr>
<td><b><center>Long term condition 1:</center></b></td>
<td>
<center><input type='text' id="Var1" name='Var1' value='%Var1%' /></center>
</td>
</tr>
<tr>
<td><b><center>Long term condition 2:</center></b></td>
<td>
<center><input type='text' id="Var2" name='Var2' value='%Var2%' /></center>
</td>
</tr>
<tr>
<td><b><center>Long term condition 3:</center></b></td>
<td>
<center><input type='text' id="Var3" name='Var3' value='%Var3%' /></center>
</td>
</tr>
</center>
</table>
Add another long-term health condition
<div id="Message"></div>
I got a table (which gets created with PHP (data from mySQL)) that look like this:
<table class="data-table">
<tbody>
<tr>
<td class="databasecontent">maybe some values</td>
<td class="databasecontent">maybe empty</td>
</tr>
<tr>
<td class="databasecontent">another row</td>
<td class="databasecontent"></td>
</tr>
</tbody>
</table>
Then I got a list, which I want the content to append to:
<ul class="plannerlist" id="plannerlist2">
</ul>
(I got 6 <ul> in total with id="plannerlist1, 2, ...").
So I want the text from .databasecontent:nth-child(1) to append to ul#plannerlist1 with this JS:
var database1 = $("td.databasecontent:nth-child(1)").text;
$("ul#plannerlist1:visible").append('<input type="text" readonly value="' + database1 + '">');
var database2 = $("td.databasecontent:nth-child(2)").text;
$("ul#plannerlist2:visible").append('<input type="text" readonly value="' + database2 + '">');
and so on...
I think that jQuery should work but it's just giving me an input with the value:
function (a){return S(this,function(a){return void 0===a?r.text(this):this.empty().each(function(){1!==this.nodeType&&11!==this.nodeType&&9!==this.nodeType||(this.textContent=a)})},null,a,arguments.length)}
Whats the problem with my code?
You should use .text() instead of using .text and it will work perfectly if nothing wrong you have done.
By using var database2 = $("td.databasecontent:nth-child(2)").text; you return function text itself, not the result of it. Try var database2 = $("td.databasecontent:nth-child(2)").text();.
For the jquery Guru's out there, I am trying. I am trying to add a jquery toggle between smarty template { foreach item list } my code works great just that it works on the first list item, it does not toggle when I click on the 2nd, 3rd etc items in the list. any suggestions?
jquery code
<script>
$(function(){
$("#itm_add").each(function(){
$(this).click(function(e){
e.preventDefault();
$("#itm_add_box").parent("tr").empty();
href=$(this).attr("href");
$(this).closest("tr").next("tr").empty().append('<td colspan="6"><div
id="itm_add_box" data-href="'+href+'">
<input type="text" id="itm_serial" class="input" placeholder="Serial
Number..." />
<input type="text" id="itm_qty" class="input"
placeholder="Quantity..." />
<button class="green" id="itm_submit">Submit</button></div><td>');
$("#itm_add_box button").click(function(e){
e.preventDefault();
href2=$(this).parent("#itm_add_box").attr("data-href");
serial=$(this).parent().find("#itm_serial").val();
qty=$(this).parent().find("#itm_qty").val();
href2=href2+"&item_serial="+serial+"&item_quantity="+qty;
window.location=href2;
});
});
});
});
</script>
Smarty template:
<table>
<tr>
<td class="olohead" align="center" width="80">ID</td>
<td class="olohead" align="center">Type</td>
<td class="olohead" align="center">Name</td>
<td class="olohead" align="center">No</td>
<td class="olohead" align="center">Features</td>
</tr>
{foreach from=$customer item=customer}
<td class="olotd4" nowrap align="center">{$customer.ID}</td>
<td class="olotd4" nowrap align="center">{$customer.TYPE}</td>
<td class="olotd4" nowrap > {$customer.NAME} </td>
<td class="olotd4" nowrap > {$customer.NO} </td>
<td class="olotd4" nowrap align="center">
<a id="itm_add">Add</a>
</td>
</tr>
{/foreach}
</table>
Again: This works, just that the toggle only works on the first listed item. Any suggestions?
The suggestion to remove the id from the loop and make it into a class was already made in the comments. With that in mind, I tried to clean up your js a bit:
$(function() {
$(".itm_add").click(function(e) {
e.preventDefault();
$(this).parent("tr").empty();
$(this).closest("tr").next("tr").empty().append(getTemplate($(this).attr("href")));
$(this).find("button").click(function(e) {
e.preventDefault();
var href = $(this).parent("#itm_add_box").attr("data-href");
var serial = $(this).parent().find("#itm_serial").val();
var qty = $(this).parent().find("#itm_qty").val();
href += "&item_serial=" + serial + "&item_quantity=" + qty;
window.location = href;
});
});
});
function getTemplate(href) {
return '<td colspan="6">'
+ '<div id="itm_add_box" data-href="' + href + '" >'
+ '<input type="text" id="itm_serial" class="input" placeholder="Serial Number..." /> '
+ '<input type="text" id="itm_qty" class="input" placeholder="Quantity..." /> '
+ '<button class="green" id="itm_submit">Submit</button>'+
+'</div>'
+ '<td>';
}
Note that this code is not tested, so there could be bugs in there...
What I changed:
Removed the .eachas it is not required. jQuery will automatically
add the event handler on all elements that the selector applies to.
Used $(this) inside the handler, to make the code only apply to the item that has triggered the event, in stead of all the matched items.
Moved the html to a separate function, just to keep things a bit more readable.
Made all the variables function scope in stead of global, by adding the varkeyword in front of their declaration.
Let me know if there are any bugs that I missed, or if this is anything that needs further explanation.
I am trying to build a form where users can add a course using select boxes.
When a course is added, it creates a new table row displaying the course to the user and also adds the course prefix and number (e.g. MATH120) to a hidden form field value. Finally, it adds a delete button.
The delete button should remove the table row AND the hidden input value that corresponds to the course being deleted.
Here's my jsfiddle: http://jsfiddle.net/MtJF2/10/
My script is deleting the row just fine, but its not removing the input value correctly. It's not throwing any errors. Sometimes I've noticed that it will delete the zero in the correct value (e.g. MATH120, becomes MATH12,). Any ideas what might be causing this?
HTML:
<script type="text/javascript">
function deleteCourse($course){
$('#' + $course).remove();
$course = $course + ','
alert($course);
$('#required-courses').val(function($course, value) {
return value.replace($course, '');
});
}
</script>
<table width="80%" align="center">
<tr id="add-required-course">
<td><input type="button" value="+ Add a Required Course" class="MC-big-button" onclick="$('#course-menu').slideToggle()" /></td>
</tr>
</table>
<input type="hidden" id="required-courses" name="required-courses" value="null" />
<table id="course-menu" width="80%" align="center">
<tr>
<td>Select the course prefix:</td>
<td><select id="1" name="course-prefix">
<option value="MATH">MATH</option>
<option value="BIOL">BIOL</option>
</select>
</td>
</tr>
<tr>
<td>Select the course number:</td>
<td><select id="2" name="course-num">
<option value="101">101</option>
<option value="120">120</option>
</select>
</td>
</tr>
<tr>
<td colspan="2">
<input type="button" value="Add this course" class="MC-big-button" id="save-course" />
</td>
</tr>
</table>
Javascript:
document.getElementById("save-course").onclick = buildCourse;
function buildCourse() {
var $coursePrefix = ($('#1').val());
var $courseNum = ($('#2').val());
var $course = $coursePrefix + $courseNum;
var $HTMLoutput = '<tr id="' + $course + '"><td>' + $course + '<input type="button" value="Delete" onclick="deleteCourse(\'' + $course + '\')" /></td></tr>';
var $VALUEoutput = ($('#required-courses').val());
if ($VALUEoutput == 'null') {
$VALUEoutput = $course + ',';
}
else {
$VALUEoutput = $VALUEoutput + $course + ',';
}
$('#course-menu').slideToggle();
$('#add-required-course').before($HTMLoutput);
$('#required-courses').val($VALUEoutput);
}
I found this question to be helpful, but I think my implementation is off.
You are replacing $course with a new value in the delete function at
$('#required-courses').val(function($course, value) {
// here it gets a new value which is wrong
Use it like this
function deleteCourse($course){
$('#' + $course).remove();
$course = $course + ','
alert($course);
$('#required-courses').val(function(_, value) {
return value.replace($course, '');
});
}