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);
});
Related
php
// iterating through the data and displaying in table format
foreach($data['schoolList'] as $school)
{
echo'<tr>';
echo '<td><input type=checkbox class=check id=check value='.$school['sid'].'></td>';
echo '<td>'.$school['sid'] .'</td>';
echo '<td>'.$school['name'] .'</td>';
echo '<td>'.$school['specialization'].'</td>';
echo'</tr>';
}
echo '<button onclick="myFunction()">Apply</button>';
JavaScript
<script>
//to restrict the user to select only 3 checkboxes
$("input:checkbox").click(function() {
let x = $("input:checkbox:checked").length >= 3;
$("input:checkbox").not(":checked").attr("disabled",x);
});
let y=[];
function myFunction() {
y= document.getElementById("check").value;
console.log(y);
}
</script>
IT only logs the first school id no matter what i select even if i select more than 1 checkboxes! could any one please help me how to log all console values! thank you!
document.getElementById("check") returns only the first one element with id="check", because the ID is unique identifier.
Use getElementsByClassName() instead or use jQuery:
<script>
//to restrict the user to select only 3 checkboxes
$("input:checkbox").click(function() {
let x = $("input:checkbox:checked").length >= 3;
$("input:checkbox").not(":checked").prop("disabled", x);
});
let y = [];
function myFunction() {
$(":checked").each(function () {
y.push($(this).val());
});
console.log(y);
}
</script>
I want to display checked checkbox value with input box value when i clicking button in codeigniter. Checked checkbox value has deen displayed correctly using join function. but input values is not showing. In my code, when i clicking button all input text values are displayed. my problem to display only checked checkbox input value using join function.
Controller code:
public function unpaid()
{
$basicUrl=$this->config->item("basicUrl");
$query=$this->db->query("SELECT aa.id as id,customer_type_id,start_time,close_time,dd.name as customer_name,bb.name as vehicle_name,cc.name as driver_name,other_expensive,paid_amount,payment_date,payment_mode,payment,tour_file,DATE_FORMAT(aa.created_date, '%d/%m/%Y') as created_date FROM ".$this->tbl." as aa
left join vehicle as bb on aa.vehicle_id=bb.id
left join driver as cc on aa.driver_id=cc.id
left join tbl_customer as dd on aa.customer_id=dd.id
order by aa.id desc");
$result=array();
if($query->num_rows()){
$i=1;
foreach($query->result() as $row){
$result_row=array();
$result_row[]='<input type="checkbox" name="unpaid_id[]" id="unpaid_id" value="'.$row->id.'" />';
$result_row[]=$row->created_date;
$result_row[]=$i;
$result_row[]=$row->customer_name;
$result_row[]=$row->payment;
$result_row[]='<input type="text" name="paid_amount[]" id="paid_amount" value="'.$row->paid_amount.'" />';
$result_row[]=$row->payment_date;
$result_row[]='<input type="text" name="payment_mode[]" id="payment_mode" value="'.$row->payment_mode.'" />';
$result[]=$result_row;
$i++;
}
}
My view code:
<input type="button" class="btn btn-primary" id="save_value" name="save_value" value="Save" />
<script>
$(document).ready(function() {
$('#save_value').click(function(){
var favorite = [];
var favorite1 = [];
var unpaid_id = [];
var paid_amount = [];
var payment_mode = [];
$.each($("input[ type='checkbox']:checked"), function(){
unpaid_id.push($(this).val());
});
var unpaid_id = unpaid_id.join(",");
alert(unpaid_id);
$.each($("input[ id='paid_amount']"), function(){
paid_amount.push($(this).val());
});
alert(paid_amount.join(","));
var paid_amount = paid_amount.join(",");
});
</script>
Thanks #
use the class in place of id
$.each($("input[class='paid_amount']"), function(){
paid_amount.push($(this).val());
});
I'm using dropdown when selected first dropdown, based on first dropdown selected it will show second dropdown. Each dropdown have data from database and the problem is i want to insert it into new table on database based on dropdown selected.
All the code on the same page, this is the php.
<?php
$sql= mysql_query("SELECT KodeMapel,NamaTema FROM mapel");
while ($row = mysql_fetch_array($sql))
{
$tema[] = array("KodeMapel" => $row['KodeMapel'], "val" => $row['NamaTema']);
}
$query = mysql_query("SELECT KodeMapel, Subtema FROM subtema");
while ($row = mysql_fetch_array($query))
{
$subtema[$row['KodeMapel']][] = array("KodeMapel" => $row['KodeMapel'], "val" => $row['Subtema']);
}
$jsonTema = json_encode($tema);
$jsonSubTema = json_encode($subtema);
?>
This is the form, included javascript on it. Inside the javascript there's php code.
<script type='text/javascript'>
<?php
echo "var tema = $jsonTema;";
echo "var subtema = $jsonSubTema;";
?>
function loadtema(){
var select = document.getElementById("PilihTema");
select.onchange = updateSubTema;
for(var i = 0; i < tema.length; i++){
select.options[i] = new Option(tema[i].val,tema[i].KodeMapel);
}
}
function updateSubTema(){
var PilihTema = this;
var idtema = this.value;
var PilihSubtema = document.getElementById("PilihSubtema");
PilihSubtema.options.length = 0; //delete all options if any present
for(var i = 0; i < subtema[idtema].length; i++){
PilihSubtema.options[i] = new Option(subtema[idtema][i].val,subtema[idtema][i].KodeMapel);
}
}
</script>
<body onload='loadtema()'>
<select id='PilihTema' name='PilihTema' class='form-control11'>
</select>
<select id='PilihSubtema' name='PilihSubtema' class='form-control11'>
</select>
<button input class="btn btn-success" id="submit" type="submit" name="add" value="Simpan" onclick="return(submitmapel());"/>
<i class="fa fa-save fa-fw"></i> Simpan
So far I see some errors in your code.
select.onchange = updateSubTema;
You are missing () for the function. Should be select.onchange = updateSubTema();
I'm not sure if var PilihTema = this; will actually select anything, personally i'd do it the following way.
loadTema function:
var select = document.getElementById("PilihTema");
select.onchange = updateSubTema(select.value);
updateTema function
function updateTema(pilihTema){
//Your code here
}
EDIT: If you mean you want to add an item per run through your for loop, I would suggest doing it the following way (I use jQuery as it is much easier in my opinion):
$(document).ready(function(){
<?php
echo "var tema = $jsonTema;";
echo "var subtema = $jsonSubTema;";
?>
//Load Tema
$.each(tema, function (i, item) {
//I am unsure as to what you mean by KodeMapel, though if this is associative arrays encoded as JSON, you will want to use item[val] and item[KodeMapel]
$("#PilihTema").append(new Option(item.val, item.KodeMapel));
});
//Called when the first select field is changed.
$("#PilihTema").change(function(){
//Get value of first select fields' selected item
var pilihValue = $("#PilihTema option:checked").val();
//Remove all the options from the second select field
$("#PilihSubtema").html("");
//For each subtema, with first select fields value, add option to second select field
$.each(subtema[pilihValue], function (i, item) {
//Again, I am unsure as to what you mean by KodeMapel, though if this is associative arrays encoded as JSON, you will want to use item[val] and item[KodeMapel]
$("#PilihSubtema").append(new Option(item.val, item.KodeMapel));
});
});
});
I have the following hidden input field on my form:
<input class="dow" id="hidden_dow0" type="hidden" value="m,t,w,r,f,s,n">
Once the form has loaded I need to find this hidden control, extract the value... and then use each item in the list ('m,t,w ') to set corresponding checkboxes on
So far, I have been able to find all hidden inputs, but I don't know how to extract the value from it.
Here's what I have so far:
$('.dow ').each(function (i, row) {
var $row = $(row);
var $ext = $row.find('input[value*=""]');
console.log($ext.val); //fails.
});
EDIT 1
This is I tried:
//find all items that have class "dow" ... and
$('.dow ').each(function (i, row) {
var $row = $(row);
console.log(i);
console.log(row); //prints the <input> control
//var $ext = $row.find('input[value*=""]');
var $ext = $row.find('input[type="hidden"]');
console.log($ext); //prints an object
$ext.each(function() {
console.log( $(this).val() ); //does not work
});
});
In jQuery val() is a function.
The .dow element is the input, you don't need to find it
$('.dow ').each(function (i, row) {
console.log( $(this).val() ); //works
});
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 :-)