I am currently using jquery ui datepicker for two input fields. In order to call the calendar the inputfield must have a class of datepicker. I am using a for loop in the javascript to generate the input fields. I have added the class datepicker to each input field that can be possibly generated. But no calendar appears. In the firebug console the html does show that the input fields have class datepicker. Now if do this with a static input field it works fine. How can I display calendar when the field is click? Example
In the jquery this is the line where i set the class:
content += '</select></br>Class Start Date: <input type="text" id="start_date_'+i+'" name="start_date_'+i+'" class="datepicker" />Class End Date: <input type="text" id="end_date_'+i+'" name="end_date_'+i+'" class="datepicker" /><div>';
Full Jquery code
<script>
$(document).ready(function () {
$('select').change(function() {
var option = $(this).val();
showFields(option);
return false;
});
function showFields(option) {
var content = '';
for (var i = 1; i <= option; i++) {
content += '<div id="course_'+i+'"><label>Course # '+i+'</label><br /><label>Course Name:</label> <select id="coursename_'+i+'" name="coursename_'+i+'"><option value="">--- Select ---</option>"'
<?php
$course_query = $db_con->prepare("SELECT course_id, course_name FROM courses_selection_list ");
$course_query->execute();
$data = $course_query->fetchAll();
foreach ($data as $row) {
//dropdown values pulled from database
echo 'content += \'<option value="' . $row['course_id'] . ':'.$row['course_name'].'">' . $row['course_name'] . '</option>\';';
}
?>
'"';
content += '</select></br>Class Start Date: <input type="text" id="start_date_'+i+'" name="start_date_'+i+'" class="datepicker" />Class End Date: <input type="text" id="end_date_'+i+'" name="end_date_'+i+'" class="datepicker" /><div>';
}
$('#course_catalog').html(content);
}
});
$(function() {
$( ".datepicker" ).datepicker({ dateFormat: "yy-mm-dd" }).val();
});
</script>
HTML
<form action="courses.php" method="POST">
<b>Select the course</b>
Academy<input id="academy_id" name="acad_id" placeholder="Academy ID" type="text" />
Courses being offered?
<select name="courses_offered">
<option value="default">---Select---</option>
<option value="1">1</option>
<option value="2">2</option>
</select>
<div id="course_catalog"></div>
Static input: <input type="text" id="last_contacted_date" name="last_contacted_date" class="datepicker" />
<input value="SAVE" name="submit" type="submit">
</form>
What you want to do is make sure that the datepicker code runs after the content has been created and added to the DOM. The easiest way to do this would be to move the datepicker code inside your showFields method, right at the end. Like this:
function showFields(option) {
. . . rest of method . . .
$('#course_catalog').html(content);
$('#course_catalog').find(".datepicker").datepicker({dateFormat: "yy-mm-dd"});
}
The $('#course_catalog').find(".datepicker") part will make sure that only the dynamically added datepicker fields will be initialized (you don't want to run it again against the static ones).
Include jQuery UI to your page.
http://jqueryui.com/download/
In the <head>:
<script type=text/javascript src="your_jquery_ui.js"></script>
Ok, you included the jQuery UI, now check your class is not hasDatepicker instead of datepicker ?
As you see here: http://jqueryui.com/datepicker/
Since you're adding inputs (datepickers) dynamically, the easiest solution is to add this:
$('body').on('focus',".datepicker", function(){
$(this).datepicker();
});
jsFiddle example
BTW, you really only need one document ready call in your page.
Related
I have an issue with the code below where the floating label stops working when executing the php script via function "loadStaff". The floating label works prior to the execution of the php script. My limited knowledge suggests that the issue is caused by the option select value not being passed on to the angular model which in turn did not trigger the floating label since the option select retains the selected value ($('select#account_list').val('<?php echo $_POST['account_list'];?>') as I can see it showing up. However, the floating label is not executing even though I see the selected value in the option select field. How do we pass the selected value to the angular model for it to trigger the floating label? I could be wrong with my reasoning.
<div ng-app="myApp">
<form id="orderformstaff" action="<?php echo $_SERVER['PHP_SELF'];?>" method="post" enctype="multipart/form-data">
<div class="field" style="width: 100%">
<label class="show-hide" ng-show="account">Account</label>
<div class="input-group mb-4">
<span class="input-group-addon gi gi-user-key"></span>
<select id="account_list" class="form-control custom-select" name="account_list" ng-model="account" onchange="loadStaff()" autocomplete="on" required/>
<?php
$a_list = $DB_CON_A->query("SELECT `id`, `email` FROM `staffs` ORDER BY `id` ASC");
$data_row = '<option value="" disabled>Choose an account</option>';
if($a_list !== false) {
foreach($a_list as $row){
$data_row .= '<option value="'.$row['email'].'">'.$row['email'].'</option>'."\n";
}
}
unset($row);
echo $data_row;
?>
</select>
</div>
</div>
</form>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.13/angular.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.13/angular-animate.js"></script>
<script> var myApp = angular.module('myApp', ['ngAnimate']);</script>
<script>
function loadStaff() {
var form =
document.getElementById('orderformstaff');
form.submit();
};
</script>
<script type="text/javascript"> <!--allows option select to retain value after executing loadStaff-->
$(document).ready(function(){
$('select#account_list').val('<?php echo $_POST['account_list'];?>');
});
</script>
Actualy you don't need using AngularJS because did all jobs with PHP.
However if you want to fix current code
REMOVE
$('select#account_list').val('<?php echo $_POST['account_list'];?>');
THEN set attribute on select element
<select id="account_list" class="form-control custom-select" ng-init="account = <?php echo $_POST['account_list'];?>" name="account_list" ng-model="account" onchange="loadStaff()" autocomplete="on" required/>
EDIT
If you want to use AngularJS you should bind data with angularjs not with PHP.
If there is no JQuery you cannot use $(document).ready etc...
If you want to start learn AngularJS, you can start from here http://www.journaldev.com/7750/angularjs-simple-forms-tutorial
It use PHP on back-end.
I have a form with input field and this input contain a drop down menu read information from database.
If the user enters value and when he arrives to the drop menu he doesn't find what he wants he go to another page to add this info to the drop down menu and then go to the first page to continue enter the information.
How can I keep this information if he goes to another page to add info to drop menu and how can after adding the info to drop menu find this info without refresh and without submit.
This is the first page with the form
<form name='' method='post' action='<?php $_PHP_SELF ?>'>
<input name='txt_name' id='' type='text'>
This drop menu read from database
<select id="groups" name="txt_label" class="form-control">
';?>
<?php
$sql=mysqli_query($conn,"select DISTINCT db_label from tbl_label")or die(mysqli_error($conn));
echo'<option value="">-- Select --</option>';
while($row=mysqli_fetch_array($sql)){
$label=$row['db_label'];
echo "<option value='$label'>$label</option>";
}echo'</select>';?><?php echo'
</div>
</form>
Second form in another page
<form class="form-inline" role="form" name="form" method="post" action="';?><?php $_PHP_SELF ?><?php echo'">
<div class="form-group">
<label for="pwd">Label</label>
<input id="txt_label" name="txt_label" type="text" placeholder="Label" class="form-control input-md">
</div>
<div class="form-group">
<label for="pwd">Sub Label</label>
<input id="txt_sublabel" name="txt_sublabel" type="text" placeholder="SubLabel" class="form-control input-md">
</div>
<input type="submit" name="addlabel" value="Add" class="btn btn-default">';
EDIT: Keep value of more inputs
HTML:
<input type="text" id="txt_1" onkeyup='saveValue(this);'/>
<input type="text" id="txt_2" onkeyup='saveValue(this);'/>
Javascript:
<script type="text/javascript">
document.getElementById("txt_1").value = getSavedValue("txt_1"); // set the value to this input
document.getElementById("txt_2").value = getSavedValue("txt_2"); // set the value to this input
/* Here you can add more inputs to set value. if it's saved */
//Save the value function - save it to localStorage as (ID, VALUE)
function saveValue(e){
var id = e.id; // get the sender's id to save it .
var val = e.value; // get the value.
localStorage.setItem(id, val);// Every time user writing something, the localStorage's value will override .
}
//get the saved value function - return the value of "v" from localStorage.
function getSavedValue (v){
if (!localStorage.getItem(v)) {
return "";// You can change this to your defualt value.
}
return localStorage.getItem(v);
}
</script>
if the above code did not work try this:
<input type="text" id="txt_1" onchange='saveValue(this);'/>
<input type="text" id="txt_2" onchange='saveValue(this);'/>
You can also use useContext() from react context() if you're using hooks.
In MVC/Razor,
first you should add a variable in your model class for
the textBox like this:
namespace MVCStepByStep.Models
{
public class CustomerClass
{
public string CustomerName { get; set; }
}
}
Then in Views --> Index.cshtml file make sure the Textbox
is created like this:
#Html.TextBoxFor(m => m.CustomerName)
For a complete example, please check out this site:
How to update a C# MVC TextBox By Clicking a Button using JQuery – C# MVC Step By STep[^]
I have a form with text boxes and drop down menus. One of the drop down menus is Dependant on the value of another, e.g. InventoryUsage is dependent on the value in InventoryID.
So far I have done the entire site using PHP since I do not know JavaScript, though I found a JavaScript function that can get the value entered in InventoryID, but I cannot use that value in the PHP since PHP is server-side.
What I need to do is change the second dropdown options depending on that of the first dropdown. Then submit the data as I would with a normal form.
Edit:
I used ob_start and included the tpl page and sent all the variables to the page which were pulled from the database prior. All the variables have the same index meaning that InventoryID['0']=ID3456 corresponds to InventoryUsage['0']=60. Therefore when InventoryID is ID3456 i would like to display the Number located at InventoryUsage['0']. I hope this adds some context to the problem.
The index is determined by the php variable $i in my code snippet. The $i would be changed to match the index of the InventoryID field. Say the value of InventoryUsage is 20 then I want to display numbers 1 to 20.
Snippet of code below:
<label>TypeOfSurgery</label> <input type="text" name="TypeOfSurgery" size="35" value="" />
<label>CauseOfSurgery</label> <input type="text" name="CauseOfSurgery" size="35" value="" />
<label>AnaesthesiaUsage</label> <input type="text" name="AnaesthesiaUsage" size="35" value="" />
<label>SurgeryOutcome </label> <input type="text" name="SurgeryOutcome" size="35" value="" />
<label>RecoveryTime</label> <input type="text" name="RecoveryTime" size="35" value="" />
<label>Stages </label> <input type="text" name="Stages" size="35" value="" />
<label>EmployeeName </label> <p>
<select name="EmployeeName">
<option value=""></option>
<?php
for($i=0;!empty($EmployeeName[$i]);$i++)
echo '<option value="">'.$EmployeeName[$i].'</option>';
?>
</select><p>
<label>Cost</label> <input type="text" name="Cost" size="35" value="" />
<label>InventoryID</label> <p>
<select name="InventoryID">
<option value=""></option>
<?php
for($i=0;!empty($InventoryID[$i]);$i++)
echo '<option value="">'.$InventoryID[$i].'</option>';
?>
</select><p>
<label>InventoryUsage </label> <p>
<select name="InventoryUsage">
<option value=""></option>
<script type="text/javascript">
var model= document.getElementById('InventoryUsage');
</script>
<?php
//if inventory in
for($i=0;!empty($InventoryUsage[$i]);$i++)
echo '<option value="">'.$InventoryUsage[$i].'</option>';
?>
</select><p>
In order to populate the InventoryUsage dropdown you need to use JavaScript.
You can use the onChange event for the dropdown InventoryID then fetch the corresponding values via Ajax.
$('#InventoryID').change(function () {
var value =$(this).val(); // selected InventoryID option
//get InventoryUsage values
$.ajax({
method: "POST",
url: "myfile.php",
data: { data: value },
success: function(data){
// Populate new dropdown $("#InventoryUsage")
// this is an example without knowing what is the returned data
var Newoptions = [];
for (var i = 0; i < data.length; i++) {
Newoptions.push('<option value="',
data[i].someValue, '">',
data[i].someName, '</option>');
}
$("#InventoryUsage").html(Newoptions .join(''));
}
});
});
});
then in your PHP file you need to handle the $_POST['data'] , then query your database and return the drop-down options( Arrays ) that will be populated above...
edit :
If you are sure that this index matches the Inventory_Usage and that the InventoryUsage dropdown has previously been populated then
you could try to select the InventoryUsage option using the index of the InventoryID dropdown on change and load events...
try adding this function to you select :
<select name="InventoryID" onChange="set_inventory_usage()"></select>
then add this script to your page's HEAD section..
<head>
<script type="text/javascript">
function set_inventory_usage(){
// Change to getElementById if it is the ID not the name
var Inventory_ID = document.getElementsByName('InventoryID')[0];
var Inventory_Usage = document.getElementsByName('InventoryUsage')[0];
// returns the index of the selected option in the InventoryID dropdown
var InventorySelected = Inventory_ID.selectedIndex ;
// Sets the Usage dropdown to the same index as the Inventory selected option
Inventory_Usage.selectedIndex = InventorySelected ;
}
window.onload = set_inventory_usage ;
</script>
</head>
Option 1: Without JavaScript, the best option is to add an onchange to your first dropdwon list, and when a value is selected submit the form. Since the form is not complete, and only the dropdown value and elements before that are passed, you can set a condition to query the database, get values based on first drop down and reload the form with those options. IThere is nothing wrong with this solution if done properly but to be honest I perfer to do such things with Ajax, hence option 2 below.
Option 2: Learn some JavaScript and use Ajax (Use caution when using other people's scripts in your system)
Edit: Perhaps instead of wring Ajax code from scratch, use jQuery where most things are already done for you. Learning jQuery is very useful if you are going to do web development
Hi I have a form that has a button used to prefill my form with data from my database. Using Json It works fine to populate text inputs but how do I get it to select a radio button based on the value returned from my database?
FORM
<form action="#">
<select id="dropdown-select" name="dropdown-select">
<option value="">-- Select One --</option>
</select>
<button id="submit-id">Prefill Form</button>
<input id="txt1" name="txt1" type="text">
<input id="txt2" name="txt2" type="text">
<input type="radio" id="q1" name="q1" value="4.99" />
<input type="radio" id="q1" name="q1" value="7.99" />
<button id="submit-form" name="Submit-form" type="submit">Submit</button>
</form>
SCRIPT
<script>
$(function(){
$('#submit-id').on('click', function(e){ // Things to do when
.......
.done(function(data) {
data = JSON.parse(data);
$('#txt1').val(data.txt1);
$('#txt2').val(data.txt2);
$('#q1').val(data.q1);
});
});
});
</script>
/tst/orders2.php
<?php
// Create the connection to the database
$con=mysqli_connect("xxx","xxx","xxx","xxx");
........
while ($row = mysqli_fetch_assoc($result))
{
echo json_encode($row);
die(); // assuming there is just one row
}
}
?>
Don't use ID because you have same ID of both radio buttons
done(function(data) {
data = JSON.parse(data);
$('#txt1').val(data.txt1);
$('#txt2').val(data.txt2);
// Don't use ID because the name of id is same
// $('#q1').val(data.q1);
var $radios = $('input:radio[name=q1]');
if($radios.is(':checked') === false) {
$radios.filter('[value='+data.q1+']').prop('checked', true);
}
});
You currently have both radio buttons using the same ID. ID's should be unique.
You can use the [name] attribute to do this, or you can set a class on the element. Here is an example:
$('input[name=q1][value="'+ data.q1 +'"]').prop('checked', true);
You can do it based on the value of said input:
instead of
$('#q1').val(data.q1);
Try
$('input:radio[value="' + data.q1 + '"]').click();
On a side note, you have both radios with the same ID, the results of an id based selector are going to vary from browser to browser because an id should be UNIQUE
you can refer the following link to solve your problem. works fine for me
JQuery - how to select dropdown item based on value
How can I retrieve a value from HTML hidden field then its value is changed (all time value ischanged by other javascript), without a button. Every time the value changes (value is changed without page refresh), I want to grab it with javascript/ajax/JQuery without any button press.
UPDATE
How I change the hidden fields
<?php
echo '<select name="d2" onchange="checkTextbox12(this)">';
for($i=0; $i<=$d2; $i++){
echo
'<option value='.$i.'>'.$i.'</option>';
}
echo '</select>';
?>
</td>
<td id="kiek250decaffeinatoTest">
<script>
function checkTextbox12(element){
var kiek = element.value * 14;
document.getElementById('kiek250decaffeinatoTest').innerHTML = kiek + " LT";
document.getElementById('kiek250decaffeinatoKaina').value = kiek;
kiekis(kiek);
}
</script>
</td>
<input type="hidden" name="kiek250decaffeinatoKaina" onchange="" id="kiek250decaffeinatoKaina" >
With jQuery you would need to wire-up a change event to your hidden field.
$(function() {
$("#hiddenfield").change(function() {
alert($(this).val());
});
});
http://api.jquery.com/change/
Use a javascript onChange function:
<input type="text" onchange="myFunction()">
Put this in your html and link to whatever javascript function you want to execute.
Since hidden fields do not trigger change events when their values are changed by javascript you will have to manually fire the event after your code has changed the hidden fields value.
<input type="hidden" id="myhiddenfield" value="0" />
then in javascript
$("#myhiddenfield").change(function(){
alert("field changed");
});
function changeField(){
$("#myhiddenfield").val(55);
//Manually trigger the change event.
$("#myhiddenfield").change();
}
changeField();
JSfiddle demo
If you the code changing the field is not your code (like changed from some library) you will have to setup a timer(setTimeout,setInterval etc) to constantly watch the field for changes.