I have form where i am sending multiple checkbox items as array to controller,
<?php
foreach($groupsArray as $group)
{
?>
<label>
<input type="checkbox" class="icheck" name="groups[]" id="groups" value="<?php echo $group["id"];?>"> <?php echo $group['name']?> </label>
<?php
}
?>
Everything works fine for checkbox values update in database,
Now, what i am doing is, getting values from database and i need to check values which are stored in database,
I am getting below json response from PHP<
groups: [{user_id: "2", group_id: "4", id: "4", name: "system Creators",…}]
Below i used as AJAX
if(objData.groups[0].group_id == $("#groups").val())
{
$("#groups").iCheck('check');
}
With this $("#groups").val(), it always takes values of first checkbox, so there is problem,
How can i compare values for all checkboxes with Json?
Also if groups array will have multiple values, means multidimensional array, more groups then?
Thanks in advance!
You need to be able to know which checkbox is related to which database value.
That is what the ID is used for on the checkbox. You have them all the same being "groups" - which is bad practice.
Use: (note the dynamic id attribute)
<?php
foreach($groupsArray as $group)
{
?>
<label>
<input type="checkbox" class="icheck" name="groups[]" id="chk<?php echo $group["id"];?>" value="<?php echo $group["id"];?>"> <?php echo $group['name']?> </label>
<?php
}
?>
Then loop around your group object from the database:
for(var i = 0; i < groups.length; i++) {
var chk = document.getElementById("chk" + groups[i].id);
chk.checked = true;
}
Try this:
PHP:
<?php
$count=0;
foreach($groupsArray as $group)
{
?>
<label>
<input type="checkbox" class="icheck" name="groups[]" id="groups<?php echo $count;?>" value="<?php echo $group["id"];?>"> <?php echo $group['name']; ?> </label>
<?php
$count++;
}
?>
Jquery:
for(var i=0;i<objData.gourps.length;i++){
if(objData.groups[i].group_id == $("#groups"+i).val())
{
$("#groups"+i).iCheck('check');
}
}
First, change the groups checkbox's id to it's class, so use class="groups" instead of id="groups", like this:
<label><input type="checkbox" class="icheck" name="groups[]" class="groups" value="<?php echo $group["id"];?>"> <?php echo $group['name']?> </label>
Next, use the jQuery .each method to check all the checkboxes that is found in the JSON object like this:
$.each(objData, function(n, i){
if(i.group_id == $(".groups[name="+n+"]").val()){
$(".groups[name="+n+"]").iCheck('check');
}
});
Finally, this worked!
Find only those checkboxes which are coming from DB and check those.
for(var i = 0; i < objData.groups.length; i++)
{
$("#groups" + objData.groups[i].group_id).iCheck('check');
}
Thanks all for support!
Related
<?php
if(isset($_POST['chkStatus'])){
for ($i=0;$i<count($_POST['chkStatus']);$i++) {
$count = count($_POST['chkStatus']);
list($txtClientId, $txStatusValue) = explode('-', $_POST['chkStatus'][$i], 2);
$stmtChkStatus=$con->query("SELECT id,status FROM users WHERE id=$txtClientId");
$SRow = $stmtChkStatus->fetch();
if($SRow['status']!=$txStatusValue) {
if($txStatusValue==0) $stmtStatus=$con->query("UPDATE users SET status='0' WHERE id=$txtClientId");
else $stmtStatus=$con->query("UPDATE users SET status='1' WHERE id=$txtClientId");
}
}
}
?>
<html>
<body>
<dl>
<?php $stmtUsers=$con->query("SELECT id,status FROM users");
while($UsersRow = $stmtUsers->fetch()){
echo "<dt>$UsersRow[name]</dt>
<dd><input type='checkbox' name='chkStatus[]' value='$UsersRow[id]-$UsersRow[status]'";
if($CRow['status']==0) echo " checked";
echo " onchange='this.form.submit()'>
</dd>";
?>
</dl>
</body>
</html>
The issue with my code is that it only execute the checked checkboxes. I need a code that changes the status in SQL DB of the checkbox that i click(onchange).
Instead of looping through $_POST['chkStatus'] you could fetch all possible values with $con->query("SELECT id,status FROM users") and loop over those values. You can check then, if $_POST['chkStatus'] is set for the according value(s).
At a moment you send all checkbox values to the server. You may send only interested values. Quick and dirty solution:
split you checkboxes into individual forms and submit only form you need:
while($UsersRow = $stmtUsers->fetch()){
echo "<dt>$UsersRow[name]</dt>
<form .... > <!-- Here required attributes -->
<dd><input type='checkbox' name='chkStatus[]' value='$UsersRow[id]-$UsersRow[status]'";
if($CRow['status']==0) echo " checked";
echo " onchange='this.form.submit()'>
</form>
</dd>";
In inclick attribute take id or name of checkbox and add to request.
Guys i have foreach loop where i list some prices. All price have own input radio button.
By default only one price from looping is checked. I want to get that value when page is lodaed.
I have one session where i store number of days. Based on these days I get the price of cars.
$numDays = $_SESSION['days']; // 5
$calculate_km = $numDays * 140; // 5*140km
So in page where i want to show total KM i use:
if(isset($_SESSION['days']) {
$numDays = $_SESSION['days'];
}else {
// Show default selected radio button value
}
Problem is bcs price list with radio is on the some page and there is no sumbiting
My loop:
<?php if($prices = getCarPricePeriod($car->ID, $od, $do)):?>
<?php $first = true; ?>
<?php foreach ($prices as $price): ?>
<tr>
<td><input type="radio" name="price" value="<?= $price['value'];?>" <?= $first ? 'checked' : '' ?>> </td>
<td><input type="text" name="price_name" value=" <?= $price['name'];?>">€/per day</td>
</tr>
<?php endforeach; ?>
<?php $first = false; ?>
<?php endif; ?>
Total KM : <span> <?= $numDays * 140 ;?> </span>
Only is posible to get that value if i submit that form. So i need js for this or any way to do this in php
I want to get that value when page is lodaed.
Use .ready() , selector $("tr input:checked") , .val()
$(document).ready(function() {
var val = $("tr input:checked").val()
})
If what you are asking is "how to send data from client-side to server-side", then the answer is AJAX.
Take a look at W3School's AJAX tutorial here: http://www.w3schools.com/ajax/
EDIT 1
for javascript, this should do it:
document.querySelector("input[type=radio]:checked").getAttribute("value")
Without submit, you need JavaScript to do that, like this:
<script>
var p = document.getElementByName("price");
</script>
I have an option box which lists the users of something in my site. I then have two input boxes. One for wins and another for losses. I am trying to create an onchange event, so that whenever a certain user is selected from the option box, the php will output that users info. As of now the output is not changing. What am I doing wrong with my onchange event?
function myFunction() {
var wins_var = document.getElementById('wins');
var losses_var = document.getElementById('losses');
}
PHP that outputs the data and html with inputs
if ($stmt = $con->prepare("SELECT * FROM team_rankings WHERE user_id=user_id")) {
$stmt->execute();
$stmt->bind_result($ranking_id, $ranking_user_id, $ranking_firstname, $ranking_username, $ranking_division, $ranking_wins, $ranking_losses);
//var_dump($stmt);
if (!$stmt) {
throw new Exception($con->error);
}
$stmt->store_result();
echo "<select name = 'member' onchange='myFunction()'>";
while ($row = $stmt->fetch()) {
echo "<option value = '{$ranking_user_id}' data-wins = '{$ranking_wins}' data-losses = '{$ranking_losses}'";
echo ">{$ranking_firstname}</option>";
}
echo "</select>";
} else {
echo "<p>There are not any team players yet.</p>";
}
}
catch (Exception $e)
{
echo "Error: " . $e->getMessage();
}?><br><br>
<label>Wins
<input type="text" value="<?php echo $ranking_wins; ?>" id="win">
</label>
<label>Loss
<input type="text" value="<?php echo $ranking_losses; ?>" id="losse">
</label>
You're on the right lines, and you don't need to do any Ajax just to achieve what you asked in your question.
The main problem is that in your Javascript, you get a reference to the two inputs for wins and losses, but you don't actually assign any value to them.
Assuming you're using jQuery (as you tagged it), then it's much easier to use this for the onchange binding and value assignments.
Firstly, you just need to make sure your "member" select has an ID instead (or as well) as a name, and you don't need the "onchange" as we'll bind that with jQuery:
echo "<select id = 'member'>";
Then, your Javascript just needs to look like this:
$(document).ready(function() {
$("#member").change(function() {
myFunction();
});
myFunction();
});
function myFunction() {
$selectedOption = $("#member option:selected");
$("#wins").val($selectedOption.data("wins"));
$("#losses").val($selectedOption.data("losses"));
}
The initial $(document).ready() function sets up the onchange binding to call myFunction(), and the second myFunction() call just ensures the wins and losses inputs are populated for the default selected option on the initial page load.
JS Fiddle here: http://jsfiddle.net/fa0kdox7/
Oh yes, and finally, your wins and losses inputs just need to look like this:
<label>Wins
<input type="text" value="" id="wins">
</label>
<label>Loss
<input type="text" value="" id="losses">
</label>
Note that I corrected a couple of typos in their IDs.
I have a dynamic field that get value from database, and I want to check one of the field value if it was greater from the old value or not. If it does greater, i have to give an alert and reset field value back to ''
i want to do it without using document.GetElementById because the field was looped by foreach, I'm tryin to work with document.GetElementByName but got no where. here's my code
<?php foreach ($items->result_array() as $row){ ?>
<tr>
<td><p><?php echo $row['nmbr']; ?> </p>
<p><?php echo $row['urai']; ?><p> </td>
<td><?php echo $row['jml']?> </td>
<td><div class="oldprice"><?php echo $row['oldprice']?></div></td>
<td><input id="pnwrn" class="pnwrn" type="text" name="pnwrn[]" value="" data-harga="<?php echo $row['jml']?>" data-jumlah="<?php echo $row['oldprice']?>"/></td>
<td><div class="output"></div></td>
</tr>
<?php } ?>
and this is my javascript :
<script type="text/javascript">
$('.pnwrn').on('change', function () {
var twrn = $(this).val();
var price = parseInt($(this).data('harga'));
var jmlh = parseInt($(this).data('jumlah'));
if (twrn <= jmlh){
$(this).parents('tr').find('.output').html(twrn*price);
}
else {
alert("Price can not be greater from old price");
cleartext();
}
});
function clearInputs() {
document.getElementByName("pnwrn").value = "";
}
</script>
can someone help me?
You are not supposed to have multiple elements with the same id. Instead, try this:
<td><input id="pnwrn<?php echo $row['some_id_field_that_you_have']; ?>" class="pnwrn" type="text" name="pnwrn[<?php echo $row['some_id_field_that_you_have']; ?>]" value="" data-harga="<?php echo $row['jml']?>" data-jumlah="<?php echo $row['oldprice']?>"/></td>
You can also attach the matching ID on the <tr>, or to other elements, which makes it trivial to find the appropriate elements.
Unfortunately, with names like urai, harga, jumlah and pnwrn, it is extremely hard to pinpoint what exactly you're trying to do, thus just vague hints.
But - if you're trying to clear the very field you're checking, you already have it, so no lookup needs to be done. Just do clearInput(this).
Try this to loop through all the inputs and match on the class you want:
$("input").each(function (i) {
if ($(this).prop("class") === "pnwrn") {
$(this).val('');
}
});
I'm trying to get the value of the selected checkbox to be transfered to the next page using href. I'm not in a position to use submit buttons.I want this to be done using JavaScript.
My checkbox is populated with value from a table row-docid. Here is my code for Checkbox in view.php:
... mysql_connect("$host", "$dbuser", "$password")or die("cannot connect");
mysql_select_db("$db_name")or die("cannot select DB");
$sql="SELECT * FROM $doctbl_name";
$result=mysql_query($sql);
if(!$result ){ die('Could not get data: ' . mysql_error()); }
while ($row = mysql_fetch_array($result,MYSQL_ASSOC)) { ?>
<tr><td><input type="checkbox" name="chk_docid[]" id="<?php echo $row['docid'];?>"
value="<?php echo $row['docid'];?>"></td> ...
I have an EDIT Link as a menu in the top in view.php.
<a href="editdoc.php>Document</a>
My question : How do I pass the value of the checked checkbox when I click the edit link.
Note :I searched for a similar question, but could not find one. If I missed any similar question please provide me with the link.
Thanks in advance.
Lakshmi
Note: changed the id of the checkbox from chk_docid to the dynamic row value ($row['docid']) as suggested by Jaak Kütt.
I found a solution!!!
Though I did it in a different way, I thank Jaak Kütt for all the support and helping me to think of a possible way..
This is what I did.. I named the form as showForm and moved to editdoc.php through the function itself.
My Check Box :
<form name="showForm">
<input type="checkbox" name="chk_docid[]" id="<?php echo $row['docid'];?>" value="<? php echo $row['docid'];?>">
My Link:
<a id="a_editdoc" onclick="getchkVal();" title="Edit Document">Document</a>
The corresponding script:
<script>
function getchkVal() {
var contents, vals = [], mydocid = document.forms['showForm']['chk_docid[]'];
for(var i=0,elm;elm = mydocid[i];i++) {
if(elm.checked) {
vals.push(encodeURIComponent(elm.value));
}
}
contents = vals.join(',');
window.location="editdoc.php"+"?v="+contents;
}
</script>
In the editdoc.php :
<?php
$cval=$_GET['v'];
?>
Thanks.
make sure your inputs have different id-s..
while ($row = mysql_fetch_array($result,MYSQL_ASSOC)) { ?>
...<input type="checkbox" name="chk_docid[]" class="chk_input"
id="chk_docid<?php echo $row['docid'];?>" value="<?php echo $row['docid'];?>">...
using jQuery:
Document
$("#editdoc").click(function(){
var selection=$("input.chk_input:checked");
if(selection.length){
var href=$(this).attr('href')+'?'+selection.serialize();
$(this).attr('href',href);
}
return true;
});
non-jQuery:
<a onclick="submitWithChecked(this,'chk_input')" href="editdoc.php">Document</a>
function submitWithChecked(e,className){
// fetch all input elements, styled for older browsers
var elems=document.getElementsByTagName('input');
for (var i = 0; i < elems.length; ++i) {
// for each input look at only the ones with the class you are intrested in
if((elems[i].getAttribute('class') === className || elems[i].getAttribute('className') === className) && elems[i].checked){
// check if you need to add ? or & infront of a query part
e.href+=(!i && e.href.indexOf('?')<0)?'?':'&';
// append elements name and value to the query
e.href+=elems[i].name+'='+encodeURIComponent(elems[i].value);
}
}
return true;
}
in editdoc.php fetch the values with php using $_GET['name_of_input_element']