I am creating a custom MySQL database query UI. Inside this UI I have a Query Builder interface that I would like to dynamically append query properties based on the user selections in order to create a dynamic query. Please see the below picture for a visual description
From the picture above I would like to append CHARACTER_SET after the FROM and append as asterisk when ALL is selected from the table and so forth with the key being the positions where I place the generated variables.
How can I achieve this with JQuery?
My JavaScript
Selecting a Table
$(document).on("change", ".tbl_list", function () {
var tbls = new Array();
$("input:checkbox[name='tbl[]']:checked").each(function () {
tbls.push($(this).val());
});
var tbl = tbls.join('|');
var db = window.sessionStorage.getItem("db");
$.ajax({
type: "POST",
url: "ajax2.php",
data: {
tbl: tbl,
db: db
},
success: function (html) {
console.log(html);
$("#tblField").html(html).show();
}
});
});
Selecting All option
$(document).on("click", ".tblall", function () {
if (this.checked) {
// Iterate each checkbox
$('.tblst').each(function () {
this.checked = true;
});
} else {
$('.tblst').each(function () {
this.checked = false;
});
}
});
EDIT
As requested HTML for my DIVs
Table Selector
while ( $row = mysqli_fetch_array ( $tbl_list ) ) {
?>
<input type="checkbox" name="tbl[]" class="tbl_list"
value="<?php echo $row [0]; ?>" />
<?php echo $row [0]; ?>
<br>
Query Builder
<div id="qryDisplay">
<fieldset>
<legend> Query Builder</legend>
<div id="qryView">
<p>SELECT FROM</p>
</div>
</fieldset>
</div>
What I have tried so far
Using .append I can add data to the end of the paragraph so this would be ideal for my Table name. However its a function and i'm not sure how I would implement the code below into my select table function.
$("#qryView > p").append(" " tblName);
Anyway, not considering the logic behind the selection of multiple tables my approach would be to store selections in hidden input fields and at the end construct from the hidden fields the query.
<input type="hidden" value="" name="hiddenTables" id="hiddenTables" />
fill field according to selections in your function from above:
$("input:checkbox[name='tbl[]']:checked").each(function () {
tbls.push($(this).val());
if($('#hiddenTables').val() == ""){
$('#hiddenTables').val($(this).val());
}else{
$('#hiddenTables').val($('#hiddenTables').val()+','+$(this).val());
}
});
At the end create your query:
// hidden field for field selection, same as above.
var fieldselection = '*';
if($('#hiddenFieldselection').val() != ""){
fieldselection = $('#hiddenFieldselection').val();
}
$("#qryView > p").html("SELECT " + fieldselection + " FROM " + $('#hiddenTables').val());
This needs to be adjusted the way you need it of course and I haven't tested any of this... So that's up to you :-)
Related
I want to be able to delete checkbox-selected rows but when I click on "Delete Selected", both the table on the web page and MySQL database stay unchanged. How do I get the selected rows from both the web page and the database to be deleted?
Edit: I'm now able to delete the rows but only the first row, despite selecting more than one checkbox, or selecting another checkbox not on the first row. Also, if I want to delete another entry, I will have to first refresh the page before deleting another one.
datatable.php
<div class="row well">
<a type="button" class="delete_all btn btn-primary pull-right">Delete Selected</a>
</div>
<script type="text/javascript">
$(document).ready(function($)
{
function create_html_table (tbl_data) {
tbl +='<table>';
tbl +='<thead>';
tbl +='<tr>';
tbl +='<th rowspan="3"><input type="checkbox" id="master"></th>';
// More table headers
tbl +='</tr>';
tbl +='</thead>';
tbl +='<tbody>';
$.each(tbl_data, function(index, val)
{
var row_id = val['row_id'];
//loop through ajax row data
tbl +='<tr id="row" row_id="'+row_id+'">';
tbl +='<td><input type="checkbox" class="sub_chk"></td>';
tbl +='<td>'+(index + 1)+'</td>';
tbl +='<td><div col_name="filename">'+val['filename']+'</div></td>';
// More data
tbl +='</tr>';
});
tbl +='</tbody>';
tbl +='</table>';
}
var ajax_url = "<?php echo APPURL;?>/ajax.php" ;
// Multi-select
$(document).on("click","#master", function(e) {
if($(this).is(':checked',true))
{
$(".sub_chk").prop('checked', true);
}
else
{
$(".sub_chk").prop('checked',false);
}
});
//Delete selected rows
$(document).on('click', '.delete_all', function(event)
{
event.preventDefault();
var ele_this = $('#row') ;
var row_id = ele_this.attr('row_id');
var allVals = [];
$(".sub_chk:checked").each(function()
{
allVals.push(row_id);
});
if(allVals.length <=0)
{
alert("Please select row.");
}
else {
var data_obj=
{
call_type:'delete_row_entry',
row_id:row_id,
};
ele_this.html('<p class="bg-warning">Please wait....deleting your entry</p>')
$.post(ajax_url, data_obj, function(data)
{
var d1 = JSON.parse(data);
if(d1.status == "error")
{
var msg = ''
+ '<h3>There was an error while trying to add your entry</h3>'
+'<pre class="bg-danger">'+JSON.stringify(data_obj, null, 2) +'</pre>'
+'';
}
else if(d1.status == "success")
{
ele_this.closest('tr').css('background','red').slideUp('slow');
}
});
}
});
});
</script>
ajax.php
//--->Delete row entry > start
if(isset($_POST['call_type']) && $_POST['call_type'] =="delete_row_entry")
{
$row_id = app_db()->CleanDBData($_POST['row_id']);
$q1 = app_db()->select("select * from data where row_id='$row_id'");
if($q1 > 0)
{
//found a row to be deleted
$strTableName = "data";
$array_where = array('row_id' => $row_id);
//Call it like this:
app_db()->Delete($strTableName,$array_where);
echo json_encode(array(
'status' => 'success',
'msg' => 'deleted entry',
));
die();
}
}
//--->Delete row entry > end
I've seen other similar SO questions like this one but I don't think it is applicable to my code.
My output:
To achieve what you want, you have to select the good elements the right way. For example, an HTML id must be unique, so giving all your elements the same id="row" won't work. Using your class will be enough. Then you have to consider that each will execute the function separately for all your selected elements, so that if you want to do things for each element, all the code must be inside.
I optimized a little your code by getting rid of allVals variable, if its only goal is to test if rows have been selected, you can directly test .length on your selection. I renamed variables so that it's more clear which is what.
Also it's not very clear in the question if the "Please wait....deleting your entry" text should appear in the button or in each row, i assumed it was in the button, and it will help you differentiate all elements from how they are selected.
//Delete selected rows
$(document).on('click', '.delete_all', function(event)
{
event.preventDefault();
//'click' is called on the button, so 'this' here will be the button
var button = $(this) ;
var checked_checkboxes = $(".sub_chk:checked");
if(checked_checkboxes.length <=0)
{
alert("Please select row.");
}
else {
button.html('<p class="bg-warning">Please wait....deleting your entry</p>');
//next code will be executed for each checkbox selected:
checked_checkboxes.each(function(){
var checkbox = $(this);
var row_id = checkbox.attr('row_id');
var data_obj=
{
call_type: 'delete_row_entry',
row_id: row_id,
};
$.post(ajax_url, data_obj, function(data)
{
var d1 = JSON.parse(data);
if(d1.status == "error")
{
var msg = ''
+ '<h3>There was an error while trying to add your entry</h3>'
+'<pre class="bg-danger">'+JSON.stringify(data_obj, null, 2) +'</pre>'
+'';
//you still have to do something with your message, keeping in mind that a separate message will be generated for each separate $.post (one is emitted for each checked checkbox)
}
else if(d1.status == "success")
{
checkbox.closest('tr').css('background','red').slideUp('slow');
}
});
});
}
});
I have a javascript's script which allow to check 2 checkboxes with the same values at the same time but it doesn't work.
I get the values from a databases thanks to a php's foreach loop. Here is my test code:
<?php
//checkboxes
foreach($host1 as $row){
echo'<input type="checkbox" name="list[]" value="'.$row['table'].'">';
}
foreach($host1 as $row){
echo'<input type="checkbox" name="list[]" value="'.$row['table'].'">';
}
//script
foreach($host1 as $row){ ?>
<script type="text/javascript">
var $checkboxes = $("input[type=checkbox][name='list[]'][value='<?php echo $row['table']?>']");
$checkboxes.on("click", function() {
var checkedState = this.checked
$checkboxes.each(function() {
this.checked = checkedState;
});
});
</script>
<?php }
If I change the value $row['table'] into a simple number, "2" for example, it's working. I also look if the values ($row['table']) of every checkboxes are the same and they are all good.
Strange thing : When I check any checkboxes, it will not check the corresponding ones, but it will instead check the lasts of the table.
Any ideas where is my mistake ?
Thank you ;)
You should try this. I think this is what you want
<?php
//checkboxes
foreach ($host1 as $row) {
echo'<input class="my_cb" type="checkbox" name="list[]" value="' . $row['table'] . '"/>';
}
foreach ($host1 as $row) {
echo'<input class="my_cb" type="checkbox" name="list[]" value="' . $row['table'] . '"/>';
}
//script
?>
<script type = "text/javascript">
$(document).ready(function () {
$(".my_cb").on("click", function () {
var val = $(this).val();
var checkboxes = $("input[type=checkbox][name='list[]'][value='"+val+"']");
var checkedState = this.checked;
checkboxes.each(function () {
this.checked = checkedState;
});
});
});
</script>
Instead of doing a php loop and assigning each click event separately, let jQuery handle that:
// this selector should get all your checkboxes
var checkboxes = $("input[type=checkbox][name='list[]']");
checkboxes.click(function() {
// not sure what you are trying to do here but it just looks like you are trying to set all checkboxes to the same state as the current one
checkboxes.prop('checked', this.checked);
});
Update
As you only have 2 list of checkboxes with the same name, I have shown options for if they have different parent elements or the same parent element
JS:
var list = $('.parent-element').find("input[type=checkbox][name='list[]']"),
list1 = $('.parent-element1').find("input[type=checkbox][name='list[]']");
list.click(function() {
var checkbox = $(this),
thisIndex = list.index(checkbox);
list1.eq(thisIndex).prop('checked', this.checked);
// if at all possible I would use the above index to change the corresponding checkbox in the other list.
// if all checkboxes are under the same parent then you will only have list (list1 won't be needed)
// and it will contain all children so to get the corresponding index you would need to do:
var thisIndex = list.index(checkbox) + (list.length / 2);
list.eq(thisIndex).prop('checked', this.checked);
});
I have a pricetable with many cells, if I click on cell im getting data like "Item Name, Item Quantity and Item Format" in alert with:
$(function() {
$('#table').on('click', 'td', function(e) {
var format = e.delegateTarget.tHead.rows[0].cells[this.cellIndex],
quantity = this.parentNode.cells[0],
name = document.querySelectorAll("#item_name");
alert([$(name).text(), $(quantity).text(), $(format).text()]);
})
});
Now the question, I want to pass this data to my contact form into disabled inputfield. But i dont realy know how to. I hope you can understand what I mean!
Url to table is : mydoamin.com/catalog/item/1
Url to contact is: mydomain.com/contact
Code for my input field:
<div class="form-group">
<label for="subject" class="control-label">Bestellung</label>
<?php print form_error('order'); ?>
<?php print form_input('order', set_value('order'), 'placeholder="" class="form-control" id="disabledInput" disabled'); ?>
</div>
Fiddle with table and JS code:
https://jsfiddle.net/0bof336t/1/
Thank you!
You can use $('#disabledInput').val(<value to insert>); to insert value to input. In your case something like this: $('#disabledInput').val($(name).text());
$(function() {
$('#table').on('click', 'td', function(e) {
var format = e.delegateTarget.tHead.rows[0].cells[this.cellIndex],
quantity = this.parentNode.cells[0],
name = document.querySelectorAll("#item_name");
$('#disabledInput').val($(name).text());
alert([$(name).text(), $(quantity).text(), $(format).text()]);
})
});
If your input is in another page, then you should pass value by get method or by cookie.
By GET method
Javacript
$(function() {
$('#table').on('click', 'td', function(e) {
var format = e.delegateTarget.tHead.rows[0].cells[this.cellIndex],
quantity = this.parentNode.cells[0],
name = document.querySelectorAll("#item_name");
window.location.replace('url/?value='+$(name).text());
})
});
And then in your php file should be something like this:
<?php print form_input('order', $_GET['value'], 'placeholder="" class="form-control" id="disabledInput" disabled'); ?>
By COOKIE method
Javascript
$(function() {
$('#table').on('click', 'td', function(e) {
var format = e.delegateTarget.tHead.rows[0].cells[this.cellIndex],
quantity = this.parentNode.cells[0],
name = document.querySelectorAll("#item_name");
document.cookie = inputValue + "=" + $(name).text()+ "; " + 3600000 +"; path=/";
})
});
And then you can access cookies with php and select value from it.
This question already has an answer here:
Cloned elements' events corresponding to all elements in the form
(1 answer)
Closed 7 years ago.
I have a small table with two rows. In the first row I have 5 columns. First is select box displaying group names. WHen any of it selected, the second select box with list of item matching the value of selected group would appear in the next column. In third column, I have textbox for price. Followed by textbox for quantity in another.When price and quantity added the total of this will appear in the last column. In the second row I have a submit button with submits the form upon click.ALl these work perfectly fine.
Now I intend to allow users to dynamically add more of the first row so that they can submit multiple items! For that I'll need to add one more button type of input beside the submit.WHen clicked, it should clone the first row of 5 columns and also the function.
I tried:
$("#more_items").on("click",function
{
$("#clone_this").clone(true,true).appendTo("#submit_item");
});
This does clone the row. The first select box when selected from cloned item, the changes happen not to the current cloned row but to the parent row.Also, I couldn't clone more than once!ALso I tried replacing ID with class as I read clone would duplicate the ID yet no avail.
Now, how do I clone with the jquery also working correctly? DO I need to change my script in a way?
Below is my script for reference.
FORM
<form action="#" method="POST" id="submit_item">
<input type="text" name="contract_id" value="" id="contract_id2"/>
<table>
<tr><th>Group Item</th><th>Nama Item</th><th>Harga</th><th>Kuantiti</th><th>Amount</th></tr>
<tr id="clone_this">
<td>
<select name='group' style="width:80px;" id="gr">
<option>Choose group</option>
<?php
$group = $agency->show_all_group();
foreach($group as $k=>$v){
?>
<option value="<?php echo $v['group_id']?>"><?php echo $v['group_name']?></option>
<?php
}
?>
</select>
</td>
<td id="sub_item">
<select name='item' style="width:100px;" id="it_id">
</select>
</td>
<td><input type="text" name="harga" value="" id="harga"/></td>
<td>
<input type='text' size='2' value="" name='qty' id='qty'/>
</td>
<td><input type="text" name="amount" id="amount" value=""/></td>
</tr>
<tr><td colspan="3"><input type="submit" name="submit" value="Next" id="item_s"/></td>
<td><input type="button" value="Add more items" id="more_items"/></td>
</tr>
</table>
</form>
SCRIPT
<script>
var harga;
var qty;
$("#harga").on("keyup",function()
{
console.log($(this).val());
harga = $(this).val();
});
$("#qty").on("keyup",function()
{
console.log($(this).val());
qty = $(this).val();
var amount = harga * qty;
$("#amount").val(amount);
});
$(document).ready( function ()
{
$("#sub_item").hide();
$('#gr').change(function()
{
var gr_id = $(this).find('option:selected').val();
console.log(gr_id);
var agency_id = '<?php echo $_SESSION['agency_id'];?>';
/*show branch for selected department starts*/
var data;
$.ajax({
type: "POST",
dataType: "json",
url: s_path+"get-item.php?group="+gr_id+"&agency="+agency_id, //Relative or absolute path to response.php file
data: data,
success: function(data) {
$("#sub_item").show();
$("#it_id").empty();
for (i = 0; i < data.length; i++)
{
$("#it_id").append("<option value='"+data[i].item_id+"'>"+data[i].item_name+"</option>");
}
if(data.length == "")
{
$("#it_id").append("<option>No items found</option>");
}
console.log(data);
}});//end success
/*show branch ends*/
});
});
$(function()
{
$("#hide1").hide();
$("#hide2").hide();
$("#hide3").hide();
$('#faktor').change(function()
{
var val =$(this).val();
//alert($(this).val());
if($.trim(val)==1)
{
$("#hide1").show();
}else
{
$("#hide1").hide();
}
});
$('#insurance').change(function()
{
$("#hide2").show();
var val =$(this).val();
//alert($(this).val());
if($.trim(val)==1)
{
$("#hide2").show();
}else
{
$("#hide2").hide();
}
});
$('#bon').change(function()
{
$("#hide3").show();
var val =$(this).val();
//alert($(this).val());
if($.trim(val)==1)
{
$("#hide3").show();
}else
{
$("#hide3").hide();
}
});
});
</script>
You should bind your event to your parent element by using the function with delegation property. e.g. ".on()" function.
For example:
$("table.test").on("click","tr",function(){
//do something
});
For all newly created tr element inside the table element with class name ="test" could trigger "click" event due to event delegation. It means after you have clone a new row, your new row could trigger the same event without handling explicitly by yourself
The problem is since you have ids in the elements, when you are cloning you are creating elements with duplicate ids, which is invalid as ID of an element must be unique.
Instead of ID, use class in such cases like
<select name='group' style="width:80px;" class="gr">
....
<td class="sub_item">
<select name='item' style="width:100px;" class="it_id">
$(document).ready(function () {
$('#submit_item .gr').change(function () {
var $this = $(this),
$tr = $this.closest('tr'),
gr_id = $this.find('option:selected').val(),
$subitem = $tr.find('.sub_item'),
$it_id = $tr.find('.it_id');
var agency_id = '<?php echo $_SESSION['agency_id '];?>';
/*show branch for selected department starts*/
var data;
$.ajax({
type: "POST",
dataType: "json",
url: s_path + "get-item.php?group=" + gr_id + "&agency=" + agency_id, //Relative or absolute path to response.php file
data: data,
success: function (data) {
$subitem.show();
$it_id.empty();
for (i = 0; i < data.length; i++) {
$it_id.append("<option value='" + data[i].item_id + "'>" + data[i].item_name + "</option>");
}
if (data.length == "") {
$it_id.append("<option>No items found</option>");
}
console.log(data);
}
}); //end success
/*show branch ends*/
});
});
I am having a problem whereby a list of options is generated from some JSON data and then outputted to the DOM using .html function
/* Function to get eventd based on subject areas */
function checker() {
var eventstext = ''; // Create eventstext
$('#customise-1 input[type=checkbox]:checked').each( function(){
var subject = $(this).val(); // Define subject
var events = times[subject]; // Define events as subsect of JSON
/* Loop through JSON data and add input details of each subject area */
for (var i in events) {
eventstext += '<div class="checkbox"><label><input class="times-check times-checker" type="checkbox" value="'+events[i].value+'">'+events[i].name+' : '+events[i].startTime+' to '+events[i].endTime+'</label></div>';//output checkboxes
}
});
$('#sessiondisplay').html(eventstext);//output the data in this div
}
/* Happens on UG date selection */
$('#ug-dateselector').change(function() {
checker();
});
/* ALso happens when you select an option from the course list */
$('#customise-1 input[type=checkbox]').click( function() {
checker();
});
This is outputted to the HTML document here
<div id="sessiondisplay">
</div>
<div class='checkbox times-none'>
<label>
<input type='checkbox' id='times-none' class="times-checker" value=''>
I don't want to attend any events
</label>
</div>
I am then trying to validate this by seeing if any objects with the .times-check have been checked.
if ($('#times-none').is(':checked')) {
console.log('do not want to attend checked');
$($('#customiseDayTimesStatus')).removeClass('glyphicon-warning-sign');
$($('#customiseDayTimesStatus')).removeClass('glyphicon-remove');
$($('#customiseDayTimesStatus')).addClass('glyphicon-ok');
$($('#ug-dates-times-1')).removeClass('has-warning');
$($('#ug-dates-times-1')).removeClass('has-error');
$($('#ug-dates-times-1')).addClass('has-success');
$($('#ug-datesErrorMsg')).text('Done');
submittable = 0;
} else if ($('.times-check').is(':checked')) {
console.log('checked');
$($('#customiseDayTimesStatus')).removeClass('glyphicon-warning-sign');
$($('#customiseDayTimesStatus')).removeClass('glyphicon-remove');
$($('#customiseDayTimesStatus')).addClass('glyphicon-ok');
$($('#ug-dates-times-1')).removeClass('has-warning');
$($('#ug-dates-times-1')).removeClass('has-error');
$($('#ug-dates-times-1')).addClass('has-success');
$($('#ug-datesErrorMsg')).text('Done');
} else {
console.log('none checked');
$($('#customiseDayTimesStatus')).removeClass('glyphicon-warning-sign');
$($('#customiseDayTimesStatus')).removeClass('glyphicon-ok');
$($('#customiseDayTimesStatus')).addClass('glyphicon-remove');
$($('#ug-dates-times-1')).removeClass('has-warning');
$($('#ug-dates-times-1')).removeClass('has-success');
$($('#ug-dates-times-1')).addClass('has-error');
};
});
I am adding the class 'times-check to the .html function however the validation function doesn't work, it works with the #times-none and finally the else statement.
I appreciate any help that can be given.
Thank you!