Enabling checkboxes in javascript and getting their values if they are disabled - javascript

I have following table
<tbody>
<?php
foreach($redeemSales as $sale)
{
?>
<tr value='<?php echo $sale['id']; ?>'>
<td><input type="checkbox" name="salesIds[]" value="<?php echo $sale['id']; ?>" /></td>
<td><?php echo $sale["ring"];?></td>
<td><?php echo formatFullDate($sale["soldDate"]) ?></td>
<td><?php echo $sale["saleType"]; ?></td>
<td>
<div class="col-lg-8">
<select name="claimTypes[]" class="form-control redeemOptions">
<option value="None">None</option>
<option value="CD">CherieDori Credit (CD)</option>
<option value="Amex">American Express Card (Amex)</option>
</select>
</div>
</td>
</tr>
<?php }?>
</tbody>
On Changing any value of redeemOptions, it should check the corresponding Checkbox. Now i do not want people to automatically click on checkboxes. So i have them disabled , the get checked when i change options in redeemOptions. Here is the javascript code
$('.redeemOptions').change(function()
{
var menuChanged = $(this);
parentForm = menuChanged.closest('form');
correspondingCheckbox = parentForm.find('input[name=salesIds]');
var status = (menuChanged.val() === 'None') ? false : true;
$(this).closest('tr').children()[0].childNodes[0].checked = status;
});
I have a button, that gets all the saleIds associated with only checked checkboxes
Here is the code
$('.redeemBtn').on('click', function()
{
$('input[name="salesIds[]"]').disabled = false;
var checked = $('input[name="salesIds[]"]:checked').serialize();
var cclaim = $('select[name="claimTypes[]"]').serialize();
if(checked !== '')
window.location.href = 'actions.php?j=4&' + checked + '&' + cclaim;
else
alert('No sales were selected');
});
It works fine if i remove the disabled from checkbox otherwise it gives "No sales selected" however i do not want to remove the disabled. I don't want users to interact with it. How can i get values of the checkBoxes that are displaying as being checked. What should be done

You can't do this, you'll need to enable it to see/get it server-side (otherwise the "client won't send it at all"). The browser "doesn't include disabled controls" in the " submission", since they "don't count as "successful" controls".
so better assign some value to this check box by default at the time of your submission.
see this article:http://www.w3.org/TR/html401/interact/forms.html#h-17.13.2
e.g.:enable/disable checkbox on button click
<html>
<head>
<title></title>
<script type="text/javascript">
function chk_control(str) {
if(str=='dsb'){document.getElementById('ck1').disabled=true;}
else {document.getElementById('ck1').disabled=false;}
}
</script>
</head>
<body >
<form name=form1 method=post action=check.php>
<table>
<tr ><td ><input type=checkbox name=ckb id=ck1 value=1></td><td >PHP</td></tr>
<tr ><td ><input type=button value='Disable' onClick="chk_control('dsb')";></td>
<td ><input type=button value='Enable' onClick="chk_control('enb')";></td></tr>
</table></form>
</body>
</html>

It's a pretty common case for webdev. You should add some hidden input in this case.
<input type="hidden" name="salesIds[]" value="smth">
and keep your checkboxes without name for "presentation" purposes.

$('#id of checkbox').prop("disabled", false);
This will enable the field. If you need to get the disabled field value just enable it after clicking the submit.This is the easiest way go get values.

Related

Event in JS only works on first checklist inside of a foreach

I have a function that monitors a list of checkboxes to detect if some are selected. If some are selected the button shows, otherwise the button hides. The checkbox lies within of a foreach in PHP to transform into a list of checkboxes.
The problem is that only the first checkbox shows the delete button.
agenda.php:
<tbody>
<form id="delTask" name="delTask" method="POST" action="">
<?php foreach ($tasks as $value): ?>
<tr>
<td>
<div class="checkbox">
<label>
<input name="excluir[]" value="<?php echo $value[0] ?>" id="taskSelect" type="checkbox">
</label>
</div>
</td>
<td><?php echo $value[1] ?></td>
<td><span class="label label-success">+50</span></td>
</tr>
<?php endforeach; ?>
</form>
</tbody>
app.js:
// Hide/Show button of del
$("#taskSelect").click(function () {
if( $("#taskSelect").is(':checked') ) {
$("#writeTask").hide();
document.getElementById("deleteTask").style.display = 'block';
} else {
$("#writeTask").show();
document.getElementById("deleteTask").style.display = 'none';
};
});
The problem is that you have many checkbox inputs with the ID taskSelect. Element IDs must be unique throughout the whole document. Instead you will want to use a class name, as the same class can be attached to multiple elements:
<input name="excluir[]" value="<?php echo $value[0] ?>" class="taskSelect" type="checkbox">
You then use a selector like .classname rather than #id in your jQuery click handler:
$(".taskSelect").click(function () {
...
});
As an aside, rather than doing document.getElementById("id").style.display to show and hide things, as your are using jQuery you can just use $("#id").show() and $("#id").hide() throughout.

How can I update a specific record in a sql database based on a selection made in a dropdown select box?

Ok, I have spent days on this, and I am out of my depth. I admit I am completely new to sql, jquery, and ajax. I apologize in advance for this.
I am trying to build an application where an admin can see a users performance over time, averaging the last 2 weeks of input scores. Using a dropdown box a member should be selected from the DB (this part seems to work), then a form below can be filled out and an "update" button pressed to update the record in the DB (this is completely broken).
The select box is populated from the DB with ajax, and I can return values from the selection with an onchange function, but when I try to then update the database with my form, nothing is updated.
The insert button and associated code work properly, and information is stored correctly in the DB. (I will break the data off into more accurate tables when I have the code correct as I did not want to deal with joins and multiple tables while struggling.)
When selecting a name from the select menu $_POST['memberID'] shows the correct number.
Once information is entered into the form and "update" is pressed, $_POST['memberID'] is blank and the DB is not updated.
Controller.php:
<?php require 'php/dbconnect.php';
$records = array();
if(!empty($_POST)) {
switch (true) {
case isset($_POST['insert']):
if(isset($_POST['name'], $_POST['designation'], $_POST['rank'], $_POST['currentScore'])) {
// The following trim functions followed by !empty ensures that a series of spaces is not accepted from users as input.
$name = trim($_POST['name']);
$designation = trim($_POST['designation']);
$rank = trim($_POST['rank']);
$currentScore = trim($_POST['currentScore']);
if(!empty($name) && !empty($designation) && !empty($rank) && !empty($currentScore)) {
$insert = $conn->prepare("INSERT INTO members (name, designation, rank, currentScore) VALUES (?,?,?,?)");
$insert->bind_param('ssii' , $name, $designation, $rank, $currentScore);
if($insert->execute()) {
$insert->free(); //Remove Query Data from memory since it is no longer needed.
header('location: index.php');
die();
}
}
}
break;
case isset($_POST['update']):
$name = trim($_POST['name']);
if(!empty($name)) {
$update = $conn->prepare("UPDATE members SET name = ? WHERE '$memberID'");
$update->bind_param('s', $name);
if($update->execute()) {
header('location: index.php');
die();
}
}
break;
// case isset($_POST['delete']):
// // Delete statement goes here
// break;
// else
}
}
if($results = $conn->query("SELECT *, ((previousScore + currentScore) / 2) AS avgScore FROM members")) {
if($results->num_rows) {
while($row = $results->fetch_object()) {
$records[] = $row; //Appending value to array
}
$results->free();
}
}
?>
Index.php:
<?php include 'header.php' ?>
<?php if(!count($records)) {
echo 'No Records' ;
} else {
?>
<form id="memberSelect" method="post">
<select name="memberID" id="members" onchange="change()">
<!-- Populated with function members in footer.php -->
</select>
</form>
<table>
<thead>
<tr>
<th>Name</th>
<th>Designation</th>
<th>Rank</th>
<th>Previous Score</th>
<th>Current Score</th>
<th>Average Score</th>
</tr>
</thead>
<tbody>
<?php
foreach($records as $r) {
?>
<tr>
<td><?php echo escape($r->name); ?></td>
<td><?php echo escape($r->designation); ?></td>
<td><?php echo escape($r->rank); ?></td>
<td><?php echo escape($r->previousScore); ?></td>
<td><?php echo escape($r->currentScore); ?></td>
<td><?php echo escape($r->avgScore); ?></td>
<!-- Remember when putting data in that current score needs to be moved to previous score's
position and the NEW score will take the place of current score(which will be the old score until updated) -->
</tr>
<?php
}
?>
</tbody>
</table>
<?php
}
?>
<hr>
<form action="" method="post">
<div class="field">
<label for="name">Member name</label>
<input type="text" name="name" id="name" autocomplete="off">
</div>
<div class="field">
<label for="designation">Designation</label>
<input type="text" name="designation" id="designation" autocomplete="off">
</div>
<div class="field">
<label for="rank">Rank</label>
<input type="text" name="rank" id="charLevel" autocomplete="off">
</div>
<div class="field">
<label for="currentScore">Current Score</label>
<input type="text" name="currentScore" id="currentScore" autocomplete="off">
</div>
<div id="submit">
<!-- Add a comment section to be input into DB -->
<input type="submit" name="insert" value="Insert">
<input type="submit" name="update" value="Update">
<input type="submit" name="delete" value="Delete">
<!-- <input type="hidden" name="id" value="<?php //echo $?>"> -->
</div>
</form>
<?php include 'footer.php' ?>
Footer.php:
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script>window.jQuery || document.write('<script src="js/vendor/jquery-1.11.3.min.js"><\/script>')</script>
<script src="js/plugins.js"></script>
<script src="js/main.js"></script>
<script>
//How do you explain something you barely understand? The following function uses JQUERY
//json, and ajax to fill a select dropdown with items populated from a linked database.
//See the jsonData.php for the json data being referenced here, it is imperitive to the operation of
//this function that json data be available.
function members(){
$('#members').empty();//Removes all content of the associated ID 'members' to ensure a clean default value
$('#members').append("<option>Loading</option>");//fill them with a default message
$.ajax({
type:"POST",
url:"php/jsonData.php",//the location of the json data, for this it is required to be in its own file
contentType:"application/json; charset=utf-8",
dataType: "json",
success: function(records){ //only fires if the json data is found
$('#members').empty();//If everything is ok, removes previous default value
$('#members').append("<option value='0'>--Select Member--</option>");
$.each(records,function(i,memberID){//Uses a foreach loop to fire a function for every memberID, assigning the value to i
$('#members').append('<option value="'+ records[i].memberID +'">'+ records[i].name +'</option>');
//^ The workhorse. Grabs the select value by the ID, appends the option value by looking within the records array
//(which is defined and assigned values in the jsonData.php file) and assigns the member id as the value and the 'name'
//as the option. This populates the dropdown with the names and gives them the value 'memberID' from the database.
});
},
complete: function(){
}
});
}
$(document).ready(function(){
members();
});
</script>
<script>
function change(){
$('#memberSelect').submit();//Submits the page to the server when called
}
</script>
<!-- Google Analytics: change UA-XXXXX-X to be your site's ID. -->
<script>
(function(b,o,i,l,e,r){b.GoogleAnalyticsObject=l;b[l]||(b[l]=
function(){(b[l].q=b[l].q||[]).push(arguments)});b[l].l=+new Date;
e=o.createElement(i);r=o.getElementsByTagName(i)[0];
e.src='https://www.google-analytics.com/analytics.js';
r.parentNode.insertBefore(e,r)}(window,document,'script','ga'));
ga('create','UA-XXXXX-X','auto');ga('send','pageview');
</script>
</body>
</html>
I think the problem is in this line of the Update Block:
$update = $conn->prepare("UPDATE members SET name = ? WHERE '$memberID'");
I am assuming the primary key of your member table is: member_id
Then this code will be:
$update = $conn->prepare("UPDATE members SET name = ? WHERE member_id = ?");
$update->bind_param('si', $name, $memberID);
Try this. Hope it helps.

Check the checkbox by changing values in optionsMenu using Multiple rows with same id

I am creating a Data table with following code
<?php
foreach($redeemSales as $sale)
{
?>
<tr class='clickableRow<?php echo $isRead ? '' : ' newrow' ?>' href='#'>
<td><form><input type="checkbox" id="userSelection" name="userslection" ></form></td>
<td><?php echo $sale["ring"];?></td>
<td><?php echo formatFullDate($sale["soldDate"]) ?></td>
<td><?php echo $sale["saleType"]; ?></td>
<td>
<div class="col-lg-8">
<select name="type" id="redeemOptions" class="form-control">
<option value="None">None</option>
<option value="CD">(CD)</option>
<option value="Amex">American Express Card (Amex)</option>
</select>
</div>
</td>
</tr>
<?php }?>
I want to make it so if anyone change the option to any oe of CD Or Amex, it will set the selection to its row as checked.
jAVAScript code is here
<script language="javascript">
$(document).ready(function(e)
{
$('#redeemOptions').change(function(){
if($('#redeemOptions').val() == 'None')
{
document.getElementById("userSelection").checked = false;
}
else
{
document.getElementById("userSelection").checked = true;
}
});
});
</script>
As you can see that there is a for loop, so its rows getting added in a table. The above method works only for first row. If i change the options, it will set selection to Checked. But after first rows, no other row is showing that behavior. It is probably something to do with id of the elements.
How can one find out a solution so that other rows show same behavior. Secondly, if I have to get the ids or values of all rows that are "Checked" how will i do it in php
the problem is that an id has to identify one single element on the page, and you are generating multiple items with the same id. Change your select to something like the following:
<select name="type" class="form-control redeemOptions">
And then change your javascript function to the following, to take advantage of the fact that "this" will equal the object that the change event is being fired from:
$('.redeemOptions').change(function(){
var menuChanged = $(this),
parentForm = menuChanged.closest('form'),
correspondingCheckbox = parentForm.find('input[name=userSelection]');
if(menuChanged.val() == 'None')
{
correspondingCheckbox[0].checked = false;
}
else
{
correspondingCheckbox[0].checked = true;
}
});
Finally, remove the id="userSelection" from the checkbox and just leave the name. It won't hurt the functionality but it is technically invalid because again you can only have one element of a given id on the page.
As I can see for every $sale in $redeemSales you have a checkbox having id "userSelection" and a select box having id "redeemOptions". I advise you to use unique ids. So append $i=0...$i++ to the ids of both.
For Row 1: userSelection0 redeemOptions0
For Row 2: userSelection1 redeemOptions1
and so on..
In Select tag, use onchange event :-
<select name="type" id="redeemOptions<?php echo $i; ?>" class="form-control" onchange="foo(<?php echo $i; ?>)">
And write a javascript function :-
<script language="javascript" type="text/javascript">
function foo(id)
{
if($('#redeemOptions'+id).val() == 'None')
{
document.getElementById("userSelection"+id).checked = false;
}
else
{
document.getElementById("userSelection"+id).checked = true;
}
}
</script>

Autofill textfield with custom text after selected a stat from dropdown menu

I need some help for this script. It's a script I got from other place and I would like to add a function to it but I really got stuck. This is the script:
<select name="order_status_id">
<?php foreach ($order_statuses as $order_statuses) { ?>
<?php if ($order_statuses['order_status_id'] == $order_status_id) { ?>
<option value="<?php echo $order_statuses['order_status_id']; ?>" selected="selected"><?php echo $order_statuses['name']; ?></option>
<?php } else { ?>
<option value="<?php echo $order_statuses['order_status_id']; ?>"><?php echo $order_statuses['name']; ?></option>
<?php } ?>
<?php } ?>
</select>
</td>
</tr>
<tr>
<td><?php echo $entry_notify; ?></td>
<td><input name="notify" type="checkbox" value="1" checked="checked" /></td>
</tr>
<tr>
<td><?php echo $entry_comment; ?></td>
<td><textarea name="comment" cols="40" rows="8" style="width: 99%"></textarea>
I would like to fill the textfield automatically after I selected one name from the dropdown menu.
for example in the dropdown listbox I selected a status "Processing" then the textfield below will automatically fill with "We are now processing your request. Please wait for X days and we would inform you shortly."
So when I selected another status "canceled" , the textfield will change it's content with "We have cancelled your request." and so on..
Please tell me if my description wasn't clear enough. Thank you so much beforehand.
You can add a javascript function that will do what you need in the onchange event of your select box like this:
<select id="order_status_id" name="order_status_id" onchange="updateTextBox()">
<textarea id="comment" name="comment" cols="40" rows="8" style="width: 99%"></textarea>
Also I added id values for both elements so we can easily select them with getElementById
This event would fire each time you change the selection. You then would implement a simple javascript function updateTextBox() that will update the textbox for you:
function updateTextBox() {
var orderStatusSelect = document.getElementById("order_status_id");
var status = orderStatusSelect.options[orderStatusSelect.selectedIndex].text;
var myTextBox = document.getElementById("comment");
if(status == "Processing") {
//set the value of the text box
myTextBox.value = "We are now processing your request. Please wait for X days and we would inform you shortly." ;
} else if(status == "Cancelled") {
myTextBox.value = "We have cancelled your request!";
} else if(status == "OtherStatus") {
myTextBox.value = "another message goes here!";
}
//and so on for all different options
}
See this jsFiddle for a running example.

when one radio button is checked the other radio button should automatically get checked

I think this is simple one but i am not able to get the desired output.i have two radio buttons with different name.what i want is when one radio button is checked the other radio button should automatically get checked and also the vice versa.
here is the simplified code snnipett.
<tr>
<?php
for($mb=0;$mb<count($emaildetails);$mb++)
{ ?>
<td align="left" style="padding-right:30px;">
<input type="radio" id="contactkanaalid" name="contactkanaalid"
value="<?php echo $emaildetails[$mb]['id']; ?>"
<?php if($mb == 0)echo 'checked="checked"'; ?> onclick="selectText(this)" />
</td>
<?php
} ?>
</tr>
and the other one
<tr>
<?php
for($mb=0;$mb<count($emaildetails);$mb++)
{ ?>
<td align="left" style="padding-right:30px;">
<input type="radio" id="kcontactkanaalid" name="kcontactkanaalid"
value="<?php echo $emaildetails[$mb]['id']; ?>"
<?php if($mb == 0)echo 'checked="checked"'; ?> onclick="selectText(this)" />
</td>
<?php
} ?>
</tr>
and i am trying the following to achieve the output but no luck:
if(document.getElementById('contactkanaalid').checked){
document.getElementById('kcontactkanaalid').checked="checked";}
and the javacsript code
function selectText(t)
{
selbu=t.value;
<?php
for($i=0;$i<count($emaildetails);$i++)
{
$buid=$emaildetails[$i]['id'];
echo "if(selbu=='$buid'){";
//the logic for radio buttons
}
?>
}
thanks in advance
There is no way to get two radio buttons checked at the same time. With name you´re grouping radio options.
The use that you´re thinking for your radios is incorrect, and will cause UX issues, you must use checkboxes. But if you still want to achieve the result that you want, simply change the name attribute in one of your radios.
Regards.

Categories

Resources