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

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.

Related

Ajax fresh input field generated by PHP DOM

I am a student studying Ajax to change the value of an input field generated with PHP DOM.
Here is the code that generates the table rows.
<?php
$totalval = 0;
foreach($_SESSION as $name=>$value){
$total = 0;
if(substr($name,0,5) == "item_"){
$id = substr($name,5,4);
$cart_xml= new DomDocument;
$cart_xml->Load('prod_db.xml');
$root=$cart_xml->getElementsByTagName('root')->item(0);
$product=$root->getElementsByTagName('product');
foreach($product as $prod){
$itms_id=$prod->getElementsByTagName('prod_id')->item(0)->nodeValue;
$itms_categ=$prod->getElementsByTagName('prod_categ')->item(0)->nodeValue;
$itms_imgsrc=$prod->getElementsByTagName('prod_imgsrc')->item(0)->nodeValue;
$itms_name=$prod->getElementsByTagName('prod_name')->item(0)->nodeValue;
$itms_price=$prod->getElementsByTagName('prod_price')->item(0)->nodeValue;
$itms_stock=$prod->getElementsByTagName('prod_stock')->item(0)->nodeValue;
if($id==$itms_id){
$price = floatval($itms_price);
$total=$price*$value;
?>
<tr>
<td><img src="<?php echo $itms_imgsrc?>" class="citemimg"/></td>
<td>
<p class="prodname"><?php echo ucfirst($itms_name);?></p>
<p class="prodcateg"><?php echo ucfirst($itms_categ)?></p>
<p class="prodprice"><?php echo "Php. ".number_format($itms_price,2)?></p>
</td>
<td class="cartAmount;">
<img onclick="ajaxMinus('<?php echo $itms_id;?>','<?php echo $itms_stock;?>')" class="carticons" src="images/logos/Minus_r_50px.png"/>
<input type="number" min="1" max="<?php echo $itms_stock;?>" class="cartqty" id="itmQty<?php echo $itms_id;?>" value="<?php echo $value; ?>" disabled>
<img onclick="ajaxAdd('<?php echo $itms_id;?>','<?php echo $itms_stock;?>')" class="carticons" src="images/logos/Add_r_50px.png"/>
</td>
<td><?php echo "Php. ".number_format($total,2);?></td>
<td>
<a href="cart_actionCart.php?del=<?php echo $itms_id;?>&maxval=<?php echo $itms_stock;?>">
<img class="carticons" src="images/logos/Remove_r_50px.png"/>
</a>
</td>
</tr>
<?php
}
}
$totalval+=$total;
}
}
?>
And I make my image tag clickable by adding
`onclick="ajaxMinus('<?php echo $itms_id;?>','<?php echo $itms_stock;?>')"`
And I add as well
`onclick="ajaxAdd('<?php echo $itms_id;?>','<?php echo $itms_stock;?>')"`
And here is my simple function for ajaxAdd
function ajaxAdd(id,maxqty){
if(window.XMLHttpRequest){
xhrAdd=new XMLHttpRequest();
}
else{
if(window.ActiveXObject){
try{
xhrAdd=new ActiveXObject("Microsoft.XMLHTTP");
}
catch(e){}
}
}
if(xhrAdd){
xhrAdd.onreadystatechange=minusQty;
xhrAdd.open("GET","cart_actionCart.php?add="+id+"&maxval="+maxqty,true);
xhrAdd.send();
}
else{
alert("Couldn't create an XMLHttpRequest");
}
}
function minusQty(){
if(xhrAdd.readyState == 4 && xhrMinus.staus == 200){
document.getElementById('itmQty'+id).value = xhrAdd.responseText;
}
}
This is working but my problem is the input value is not changing until I refresh the page, where is my problem? Any help is greatly appreciated.
Anything loaded in via AJAX will not have a listener unless the parent element was there in the first place.
As an example, I had a form HTML come through AJAX, and the datepicker would not work, until I changed the original code from this:
$('.datepicker').datepicker();
To this:
$("body").on("focusin", ".datepicker", function(){
$(this).datepicker();
});
Because body is there always, the listener now works. This will probably what your issue is too, so I suggest trying to adapt your listeners as above.

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.

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

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.

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>

change dropdown to textBox in Yii

I am stuck in a place in Yii. I have two drop Down box, second is dependent on the first. In this first drop Down, I have many options. By referring to these options, I must decide whether the second box must be a drop Down or a text Field.
I have uploaded My code here. Please help me solving this.
Thanks in advance.
My View:
<td>
<?php echo $form->labelEx($model,'cm_classification_id'); ?>
<?php echo $form->dropDownList($model,'cm_classification_id', CHtml::listData(masterClassification::model()->findAll(array('order' => 'cm_classification_id ASC', 'condition'=>'cm_classification_type=:type', 'params'=>array('type'=>'initiate'))), 'cm_classification_id', 'cm_classification_name'), array('empty'=>'Select classification')); ?>
<?php echo $form->error($model,'cm_classification_id'); ?>
</td>
<td>
<label>Change Description <span class="required" id="desc_req_note" style="display:none;">*</span></label>
<?php echo $form->dropDownList($model,'cm_description',array(),array('empty'=>'Select Change Description')); ?>
<?php echo $form->error($model,'cm_description'); ?>
</td>
based on the change classification, I must decide where Change Description must be a drop Down or a text field.
This must be done using Javascript.
Have you tried this -
Change the code to -
<label>Change Description <span class="required" id="desc_req_note" style="display:none;">*</span></label>
<span id="cm_desc_select" style="display:none;"><?php echo $form->dropDownList($model, 'cm_description', array(), array('empty'=>'Select Change Description')); ?></span>
<span id="cm_desc_input" style="display:none;"><?php echo $form->textField($model,'cm_description'); ?></span>
<?php echo $form->error($model,'cm_description'); ?>
2.
$('#cm_classification_id').change(function() {
var val = $(this).val();
var cm_desc_select_elem = $('#cm_desc_select');
var cm_desc_input_elem = $('#cm_desc_input');
if(val === COMPARE_WITH_YOUR_VALUE) {
$(cm_desc_select_elem).show();
} else {
$(cm_desc_input_elem).show();
}
});
I hope is helps for a quick fix.

Categories

Resources