Working with date picker: simple task - javascript

Below is a fiddle example as a starting point:
http://jsfiddle.net/1ezos4ho/8/
Essentially I would want the followings to happen:
The date selected to be dynamically be added as the value of the input, where it would be like <input type text value="date selected"....
Update:
<script>
$(function() { // on load function, everything inside here will not run until the pagehas had time to load
$("#dpick").datepicker(); //date picker added here at its state its only able to grab the startDate not the end date not sure why
$('.filter').click(function(){
document.getElementById("results").innerHTML = "<div class='loading-indication'><img src='ajax-loader.gif' /> Please wait... Loading New Courses...</div>";
var datastring = $('#testform').serialize(); // this will create key/value pairs to send to the phph page like `duration5=5` with a `&` sepparating each key/value pair
$('#display-datastring').html(datastring); // this line is just so you can see the variable being created
$.ajax({
url: 'fetch_pages.php',
type: 'post',
data: datastring,
success: function(res){
$('#results').html(res);
}
});
});
});
</script>
Below is the form:
<form id="testform">
<input type="text" placeholder="Start" style="width: 40%;" name="dateStart" class="filter" id="dpick" >
<label id="Paylbl0">To</label>
<input type="text" style="width: 40%;" placeholder="End" name="dateEnd" class="filter" id="dpick">
problem is function start to run as soon as i hit the input when it should only be executed oncce the date has been selected. For some reason the date picker only comes in action with start date and not end date.

Not sure you fully understand how the plug-in works. It'll assign the value. Here's a quick "alert" test I did to show you. Just select a date. It watches for a change to the input and then alerts the date selected - based on the VALUE.
Submit your form (or grab the input value via js, as per my example) and it should work.
http://jsfiddle.net/1ezos4ho/11/
A js example to show you...
var i = 3;
$(function() {
$(".dpick").datepicker();
$('.dpick').on('change', function() {
$val = $(this).val();
alert($val);
});
});
Also, make sure you name your inputs if you're submitting them via a form. based on your comment, you're doing a POST request which is looking for those items which haven't been identified.
In short, $_POST['endDate'] is looking for an input with the name, endDate.
<input type="text" name="startDate" placeholder="Start" style="width: 40%;" class="dpick" id="dpick0" >
<input type="text" name="endDate" style="width: 40%;" placeholder="End" class="dpick" id="dpick1">

Related

Trouble with getting right value from html input using jquery

I have this at the end of my PHP file:
<script type="text/javascript>"
$("#id").on("click", "#otherId", function(e)
{
var html = "<input class='id' type='text' size='5' />";
var row = $(this).closest("#addoid").html(html);
row.find("input").focus();
row.find('input').change( function(e)
{
var value = $(this).val();
var fid = $("input#idName").val();
$.ajax({
type: "POST",
url: "page.php",
data: { entryId: fid, val: value }
})
.done(function( msg ) {
alter("data: " + msg);
});
});
</script>
</body>
The html is something like this:
<div id="id">
<div id="otherId">
<input id="idName" type="hidden" value="1234" />
<button type="button" id="otherId">Add</button>
</div>
<div id="otherId">
<input id="idName" type="hidden" value="1235" />
<button type="button" id="otherId">Add</button>
</div>
<div id="otherId">
<input id="idName" type="hidden" value="1236" />
<button type="button" id="otherId">Add</button>
</div>
</div>
I left the earlier jquery code out, but basically, when the Add button is pressed, it is changed to an input field, if the user puts an id into the input field, it will display a link (on blur) or go back to the add button if nothing is entered.
So far it is working, however
var fid = $("input#idName").val();
is taking the next id (instead of 1234, it is posting 1235).
I am new to jquery. I have searched around and tried several different things but I am getting nowhere.
Thanks.
ADDITION
To make this more clear, I have a table that is being populated with a foreach loop (using php) it is pulling records from a database.
looks something like this:
<div id="list">
<table>
<?php foreach ($data as $value):?>
<tr>
<td>
<div class="row">
<button class="add">Add</button>
<input class="hiddenId" type="hidden" name="hiddenName" value="<?php echo $value['id']?>" />
</div>
</td>
</tr>
<?php endforeach?>
</table>
</div>
Like I explained earlier, when the "Add" button is clicked, it turns into an input field.
On change (of the input field), I need the ajax to send a request containing the values of the two input fields.
The problem I am having is I am not able to get the correct value of the hidden input. jquery is grabbing a value from another row, not the correct row.
I can't seem to figure this out and have honestly tried many different ways, including some that would probably be considered unconventional.
Thanks for any help.
Please first rename input ids, since ID has to be unique.

Jquery input type file as trigger doesnt work

I have multiple input type files. On default they are hidden and only first one is shown. When user selects file with the first input file the funcion below shows the next input type file by id. The problem is that it works only for first 2 change events and than it stops without errors.. How can I make it work for every next input file. Here is the function:
//first we hide all inputs
$('.imagediv').hide();
$('.imagediv:first').show();
var nextupload=$('.imagediv:first').attr('data');
nextupload=(parseInt(nextupload) + 1);
//this is the event
$(function() {
$("input:file").change(function (){
var nextf = $(this).attr('data');
$('#input'+(nextupload)+'').show();
alert('#input'+(nextupload)+'');
});
});
here is how html looks like:
<div class="imagediv" id="input2" data="2">
<input type="file" name="gallery_upload_2" data="gallery_upload_3" id="gallery_upload_2" />
</div>
and so on with the next input..
How to make it work for every next input change? Thanks
I made jsfiddle here: http://jsfiddle.net/Lbu3ksjh/1/
You were missing the +1 part in the change-function:
$('input:file').change(function (){
var nextupload = $(this).parent('.imagediv').attr('data');
nextupload = (parseInt(nextupload) + 1);
$('#input'+(nextupload)+'').show();
alert('#input'+(nextupload)+'');
});
I updated your fiddle:
Demo
Here's another solution. It works on a variable number of file inputs and doesn't require a lot of code nor markup.
DEMO
js
$(function() {
var $fileInputs = $(':file[name*="gallery_"]'), // could be whatever
next = 0;
$fileInputs.not(':first').hide();
$fileInputs.change(function (){
$fileInputs.eq(++next).show();
});
});
html
<input type="file" name="gallery_upload_1" />
<input type="file" name="gallery_upload_2" />
<input type="file" name="gallery_upload_3" />
<input type="text" name="random_text_input" />
<!-- notice it only reveals file inputs -->
<input type="file" name="gallery_upload_4" />

datepicker: display value from DB but allow user change; multiple datepicker()s on page

I'm a noob wrt jquery and javascript. So, while I've looked at a lot of SO posts that deal with a piece of my problem, I've not been able to "assemble" the various solutions into something that works for me.
My context: the results of a query are displayed in a form. In each row, one of the fields is a date with an existing value. When first rendered, the data of all fields is text (non-editable). Via a button, I "enable" the fields for editing and I want to use jQuery datepicker for the date field. (I have this part working.)
One requirement: dates are stored in the database in ISO ('yyyy-mm-dd') format. The date displayed in the form (formatted via php) are 'M d y'.The datepicker should use the 'M d y' format for display as well (also seems to be working), but "post" the revised date in ISO format.
I've posted my code so far below and
here (jsfiddle)
<div class="container" id="myDiv">
<form method="post" action="">
<input type="hidden" id="projID" name="projID" value="fakeProjID">
<div class="row">
<!-- initially form is in "display-only mode" -->
<a class="btn btn-default btn-xs" id="make-editable" onClick = "toggle_edit(id,'fakeProjID');">Edit</a>
</div>
<!--rows dynamically generated via query
the id of the record is appended to the ids and inserted into the data-ids, data-dateval and values
these are fixed values for demo, but are dynamic values in reality -->
<div class="row">
<input type="text" name="date_pickr[]" id="date_pickr_511" class="input date_pickr disabled" data-id="511" data-dateval="2012-03-12" value="2012-03-12" disabled="true"/>
<input type="hidden" name="fmt_date[]" id="fmt_date_511" value="2012-03-12"/>
<input type="hidden" name="activityID[]" value="511"/>
//more info goes here//
</div>
<div class="row">
<input type="text" name="date_pickr[]" id="date_pickr_376" class="input date_pickr disabled" data-id="376" data-dateval="2013-05-19" value="2013-05-19" disabled="true"/>
<input type="hidden" name="fmt_date[]" id="fmt_date_376" value="2013-05-19"/>
<input type="hidden" name="activityID[]" value="376"/>
//more fields goes here//
</div>
<div class="row">
<button type="submit" class="btn btn-primary">Save changes</button>
</div>
</form>
</div>
and the javascript:
//datepickers
$(function() {
$.datepicker.setDefaults({
dateFormat: 'M d y',
altFormat: 'yy-mm-dd'
});
$('.date_pickr').datepicker();
$('.date_pickr').datepicker( 'option','altField','#fmt_date');
});
function toggle_edit(ID,projID) {
var working_elemID = ID;
var ItemID = projID;
//name of modal div to enable/disable
var group_id = 'myDiv';
//if elem_ID = make_editable
if (working_elemID.search('un') == -1) {
//working code to make field editable
} else {
//working code to make field uneditable
}
}
The parts I need help with are:
a) getting the default dates to show in the field before they are edited/editable
b) getting datepicker to open to the default date shown for that field
c) getting datepicker to set the new value to a field that is included in the $_post data (currently trying to use the hidden input field).
Any assistance at all would be greatly appreciated!
After hours of iteration, I've solved my own question. Here's what I came up with:
The HTML (with PHP for the values)...
<div class="container">
<form method="post" action="">
<input type="hidden" id="projID" name="projID" value="<?php echo $projID; ?>">
<div class="row">
<!-- initially form is in "display-only mode" -->
<a class="btn btn-default btn-xs" id="make-editable" onClick = "toggle_edit(id,'fakeProjID');">Edit</a>
</div>
<!--rows dynamically generated via query
the id of the record is appended to the ids and inserted into the data-ids, data-dateval and values
these are fixed values for demo, but are dynamic values in reality -->
<?php
foreach($vals as $ky=>$v) {
$row = '
<div class="row">
<input type="text" name="date_pickr[]" class="input disabled" data-id="'.$vals[$ky].'" value="'.date('M d y',strtotime($dates[$ky])).'" disabled="true"/>
<input type="hidden" name="fmtd_date[]" id="fmtd_date_'.$vals[$ky].'" value="'.date('Y-m-d',strtotime($dates[$ky])).'">
<input type="hidden" name="activityID[]" value="'.$vals[$ky].'"/>
//more info goes here//
</div>';
echo $row;
}
?>
<div class="row">
<button type="submit" class="btn btn-primary">Save changes</button>
</div>
</form>
</div>
And the javascript:
function toggle_edit(ID,projID) {
var working_elemID = ID;
var ItemID = projID;
//if elem_ID = make_editable
if (working_elemID.search('un') == -1) {
var selector = '#'+ group_id +' .disabled';
var fields = $(selector);
fields.removeClass('disabled');
fields.addClass('enabled');
fields.removeAttr('disabled','');
fields.addClass('date_pickr');
$('.date_pickr').datepicker({
dateFormat: 'M d y',
altFormat: 'yy-mm-dd',
firstDay: 1,
showOtherMonths: true,
selectOtherMonths: true,
showOn: 'focus',
onSelect: function() {
var id = $(this).data('id');
var currentDate = $(this).datepicker('getDate');
var altFormat=$(this).datepicker('option','altFormat');
var formatedDate = $.datepicker.formatDate(altFormat,currentDate);
$('#fmtd_date_'+id).val(formatedDate);
}
});
} else {
//if elem_ID == make_uneditable
var selector = '#'+ group_id +' .enabled';
var fields = $(selector);
fields.removeClass('enabled');
fields.addClass('disabled');
fields.disabled = 'true';
}
}
And here are the explanations for each of the three questions. The key breakthrough came when I stuck the datepicker functions inside the "toggle-edit" function.
(a) The default dates (i.e. the database values) are shown by
assigning the date value from the database (formatted by using the
php Date() function with the exact same format as the datepicker
dateFormat value...in this case 'M d y') into the value field of the
datepicker input control.
(b) When the control is enabled for editing,
the date_pickr class is added to the control. With the value of the
control set to the right value and format, the datepicker
automatically displays the correct calendar when the field receives
focus.
(c) the $_POST value (for writing back to the db) is set in a
hidden input control. At first the control receives the database
value. If the value is edited, then the 'onSelect:' option function
is fired and therein the id of the datepicker (which is the recordID
for the row, from the database) is appended to the ID of the hidden
field with the properly formatted date value.
NOTE: the php date formats are different than jQuery. To get yyyy-mm-dd in PHP, you need 'Y-m-d'. For jQuery, you need 'yy-mm-dd'.
Voila! Mission accomplished, but always open to suggestions/improvements.

data-bind multiple text boxes to display in one text box

I'm using a Kendo edit box that a user can enter the different parts of a SQL connection string (server name, database, user name and password). I also have a text box that will show the user the entire connection string as they type.
My question is how can I data-bind each of the four text boxes (server, database, user and password) to one text box as the user enters data into each one.
Also, the user requested seperate fields.
Thanks in advance,
Dan Plocica
Doing it using Kendo UI would be:
HTML:
<div id="form">
<label>Server : <input type="text" class="k-textbox" data-bind="value: server"></label><br/>
<label>Database : <input type="text" class="k-textbox" data-bind="value: db"></label><br/>
<label>User : <input type="text" class="k-textbox" data-bind="value: user"></label><br/>
<label>Password : <input type="password" class="k-textbox" data-bind="value: password"></label><br/>
<div id="connections" data-bind="text: connection"></div>
</div>
JavaScript:
$(document).ready(function () {
var model = kendo.observable({
server : "localhost:1521",
db : "database",
user : "scott",
password : "tiger",
connection: function () {
return this.get("user") + "/" +
this.get("password") + "#" +
this.get("server") + ":" +
this.get("db");
}
});
kendo.bind($("#form"), model);
});
In the HTML there are two parts:
The input files where I define each input to what field it is bound in my model.
A div where I found its text to connection function in my model that creates a string from the different values.
This is automatically updated and you can freely edit each input.
You might decorate the input as I did setting it's CSS class to k-textbox, that's optional. The only important thing is the data-bind="value : ...".
The JavaScript, is just create and Observable object with the fields and methods that we want.
Running example here: http://jsfiddle.net/OnaBai/xjNMf/
I will write solution using jQuery JavaScript library, and you should use jQuery because its much easier and easier to read and also to avoid errors in different browsers.
**HTML**
Server: <input type="text" id="server"/><br/>
Database: <input type="text" id="database"/><br/>
Username: <input type="text" id="username"/><br/>
Password: <input type="text" id="password"/><br/>
<br/>
Full CS: <input type="text" id="solution"/><br/>
JS
<script type="text/javascript">
var _template = 'Data Source=%server%;Initial Catalog=%db%;Persist Security Info=True;User ID=%user%;Password=%pass%';
$(document).ready(function(){
$('#server,#database,#username,#password').keyup(function(){ updateSolution();});
});
function updateSolution(){
var _t = _template.replace('%server%', $('#server').val()).replace('%db%', $('#database').val()).replace('%username%', $('#username').val()).replace('%pass%', $('#password').val());
$('#solution').val(_t);
};
</script>

Jquery - Show/Hide a hidden input form field

I'm new to Javascript and trying to understand it better. I have a form which is generated by php, using data from POST. The form has some hidden form fields, which are supposed to be populated with values after validation.
The relevant html code:
<form action="" method="post" name="FormProcessor">
<b>Domain Name: </b>
<input type="text" name="MAIN_DOMAINNAME" value="" id="DomainField">
<input type="hidden" name="CONF_FILE" value="" id="ConfFile">
<div id="infomsg">
Javascript code:
$(document).ready (function()
{
$('#DomainField').blur(function() {
var DomField=$("#DomainField");
var DomText=DomField.val();
var fold="/var/lib/bind/db.";
alert(fold+DomText);
var ConfFile=$("#ConfFile");
ConfFile.val(fold+DomText);
ConfFile.show();
});
});
I'm trying to get the second <input> field to be 'unhidden' when the focus of the previous field is lost. The function gets executed, and the alert is shown.
On checking the source, I can see that it shows:
<input type="hidden" id="ConfFile" value="/var/lib/bind/db.g.com" name="CONF_FILE" style="display: inline;">
So the value is propogated, so I did address the object properly. Why isnt it becoming shown?
A hidden input field is supposed to remain hidden.
What I think you want to do is use a normal input field of the type text and hide it using css. Then you are able to show it using jQuery the way you are doing it now.
It should work if you replace your hidden field with:
<input type="text" name="CONF_FILE" value="" id="ConfFile" style="display:none">
using show() only sets the display property to something visible, but as the input has a type of hidden, it still won't show, you have to actually change the type for that:
$(document).ready (function() {
$('#DomainField').on('blur', function() {
var DomField = $("#DomainField");
var DomText = DomField.val();
var fold = "/var/lib/bind/db.";
var ConfFile = $("#ConfFile");
ConfFile.val(fold+DomText).prop('type','text');
});
});
As per your code input type is hidden and same is not shown even doing show forcefully as hidden have property to hide existence of control.So you need to change your input type.
You can replace your hidden
<input type="hidden" id="ConfFile" value="/var/lib/bind/db.g.com" name="CONF_FILE" style="display: inline;">
to
<input type="text" id="ConfFile" value="/var/lib/bind/db.g.com" name="CONF_FILE" style="display: none;">
or
<input type="label" id="ConfFile" value="/var/lib/bind/db.g.com" name="CONF_FILE" style="display: none;">
You should change attribute from hidden to text before showing:
ConfFile.attr('type', 'text');
ConfFile.show();
use code for hide
$(document).ready(function () {
$('#ConfFile').hide();$('#ConfFile').show();
});

Categories

Resources