I love this jQuery datepicker that I want to implement on a PHP form with other input boxes
http://multidatespickr.sourceforge.net/
When the user hits a submit button they are brought to another page update.php where the form data is obtained via POST.
I'm looking for a line to add to the javascript so I can somehow access the array of multiple dates in the multiple datepicker via POST:
var latestMDPver = $.ui.multiDatesPicker.version;
var lastMDPupdate = '2012-03-28';
var dates = $('#simpliest-usage').multiDatesPicker('getDates');
// Version //
//$('title').append(' v' + latestMDPver);
$('.mdp-version').text('v' + latestMDPver);
$('#mdp-title').attr('title', 'last update: ' + lastMDPupdate);
// Documentation //
$('i:contains(type)').attr('title', '[Optional] accepted values are: "allowed" [default]; "disabled".');
$('i:contains(format)').attr('title', '[Optional] accepted values are: "string" [default]; "object".');
$('#how-to h4').each(function () {
var a = $(this).closest('li').attr('id');
$(this).wrap('<'+'a href="#'+a+'"></'+'a>');
});
$('#demos .demo').each(function () {
var id = $(this).find('.box').attr('id') + '-demo';
$(this).attr('id', id)
.find('h3').wrapInner('<'+'a href="#'+id+'"></'+'a>');
});
// Run Demos
$('.demo .code').each(function() {
eval($(this).attr('title','NEW: edit this code and test it!').text());
this.contentEditable = true;
}).focus(function() {
if(!$(this).next().hasClass('test'))
$(this)
.after('<button class="test">test</button>')
.next('.test').click(function() {
$(this).closest('.demo').find('.box').removeClass('hasDatepicker').empty();
eval($(this).prev().text());
$(this).remove();
});
});
});
Looking at the plugin you can store the range as a common seperated list in a regular input field. Use jquery to disable to field from direct entry so people can't "mess it up" then after you post you an implode the field on a comma and then you will have your array.
http://multidatespickr.sourceforge.net/#undefined-demo
I'm not sure if that's what you're looking for, but if you need to access the dates passed to the script via POST just do this:
$dates = explode(',', $_POST['simpliest-usage']);
Related
I have some issues with JQuery.
Code;
$(document).ready(function(){
$("#area_results").click(function(){
$("#areaclickpass2 a").click(function(){
var value = $(this).html();
var input = $('#inf_custom_TESTclubarea');
input.val(value);
$("#area_results").hide(); // hide results after click
});
});
});
The current website is requiring 2 clicks to input the value into a field.
I understand why it's doing this (Best solution I can think of to achieve the outcome), however I was curious whether it is possible to achieve the same result by only using a single click.
Thanks for your time.
Create a variable that counts up with each click and execute your code when that variable equals 2.
$(document).ready(function(){
var click_count = 0;
$("#area_results").click(function(){
click_count++;
if(click_count==2){
var value = $(this).html();
var input = $('#inf_custom_TESTclubarea');
input.val(value);
$("#area_results").hide(); // hide results after click
}
});
});
You are binding a event handler within another event handler. #areaclickpass2 will not be handled unless you click on #area_results first.
Just move $('#areaclickpass2') event binding out of #area_results scope:
$("#area_results").click(function(){
//may not even be necessary to have this
});
$("#areaclickpass2 a").click(function(){
var value = $(this).html();
var input = $('#inf_custom_TESTclubarea');
input.val(value);
$("#area_results").hide(); // hide results after click
});
I am foreaching a number of suppliers in a quotation form, each with a checkbox element to tick which should be contacted. suppliers are in divs with class names supplier-checkbox, moreover upon selecting supplier the supplier-checkbox div gets appended with "checkedsupplier" or "uncheckedsupplier" class name.
<div class="supplier-checkbox checkedsupplier">
<input type="hidden" name="supplier-email" class="supplieremail" value="{$item->email}" />
</div> <!--end supplier checkbox-->
foreach supplier div I get a hidden input field within the div holding the supplier email as its value. idea is that upon submitting form I'd check for all div's with "checkedsupplier" class name and for each obtain the value of the input inside of it, hold all values in onelong variable and echo it into the To field of the email to replicate the quotation form to each supplier.
using jquery, I managed to toggle the class name and a background effect showing ticked or unticked with the below.
<script>
$(".supplier-checkbox").click(function(){
$(this).toggleClass('checkedsupplier uncheckedsupplier')
//$(this).children( ".supplieremail" ).attr("checked")
});
</script>
can anyone give me any pointers on how to foreach by class name and fetch value of each input inside every div with that class name using jquery. Im working on it and yet found the .each for looping .val for values and if (bar) for conditional. but am not yet experienced enough to put things together. have been working as a junior developer for 7 months now since graduating in networking which is a completely different field.
in the app.js file I'm obtaining the form values this way:
`
v_country:$('#country').val(),
v_quotationtel:$('#quotationtel').val(),
v_mobile:$('#mobile').val(),
v_quotationemail:$('#quotationemail').val(),
v_quotemefor:$('#quotemefor').val(),
v_quotemessage:$('#quotemessage').val()
//this line is what i'm trying to do to get input values and store them in one var to pass them to php form that sends email $( "checksupplier" ).each(function( i ) {
}`
thanks everyone on stack! I believe in you guys here you've all helped me throughout my studies and work.
Ian
** Update ** It's been modified to work as follows:
<script>
$(function(){
$( ".crew-member-con" ).click(function(){
$(this).toggleClass('whitebg greybg');
$(this).toggleClass('crew-checked crew-unchecked');
$(this).toggleClass('grey white');
if($(this).children('input').prop('checked') == true){
$(this).children('input').prop('checked', false);
}else{
$(this).children('input').prop('checked', true);
}
var selectedMembers='';
$('.selected-members').each(function(){
if($(this).is(':checked')){
selectedMembers +=$(this).val()+', ';
}
//alert(emails);
});
if(selectedMembers != ''){
selectedMembers = selectedMembers.slice(0,-2);
}
$('#exam-member span').html(selectedMembers);
console.log(selectedMembers);
});
});
Here's an example with some notes.
$('.myform').submit(function () {
getEmailAddresses();
return false;
}
function getEmailAddresses () {
// a place to hold them
var emails = new Array();
// what will be after 'mailto'
var emailsString = "";
// get 'em
$('.checkedsupplier').each(function () {
// get the hidden email input value
var email = $(this).find('.supplieremail').val();
// check, just in case;
if (email) {
// push the value into our array
emails.push(email);
}
});
//put them all together into a string, split by a semi-colon
emailsString = emails.join(';');
// finally, stuff our mail to link.
// Not sure what you're plan is here but 'emailsString' has all of the values you eed.
$('.mailtolink').attr('href', 'mailto:'+emailsString);
}
<script>
$(".supplier-checkbox").click(function(){
$(this).toggleClass('checkedsupplier uncheckedsupplier')
//$(this).children( ".supplieremail" ).attr("checked")
var emails='';
$('.supplieremail').each(function(){
emails +=$(this).val();
});
$('#mailfieldstextarea').val(emails);
});
</script>
I hope this will help.
I am trying to iterate through a number of selects in a cell of a table (they are not in a form). I have a submit button when pressed is supposed to retrieve the values and id of each select list which I will pass to the server via AJAX and PHP. My table is a table of students of a course. The table contains the students name and their attendance for a lesson in the course.
This is my table on Pastebin and jsFiddle. http://pastebin.com/NvRAbC7m and http://jsfiddle.net/4UheA/
Please note that this table is entirely dynamic. The no. of rows and the info in them is dynamically driven.
This is what I'm trying to do right now with jQuery. Please excuse the logic or the complete nonsense that is my JavaScript skills. I don't actually know what I'm doing. I'm just doing trial and error.
$('#saveAttendances').live('click', function()
{
var attendSelect = $('.attendSelect');
var students = new Array();
//get select list values and id.
for(var i in attendSelect)
{
students['student_id'] += attendSelect[i].id;
students['student_id']['attedance'] += attendSelect[i].value;
console.log(students['student_id']);
}
//after retrieving values, post them through ajax
// and update the attendances of students in PHP
$.post("",{ data: array }, function(msg)
{
alert(msg);
});
});
How do I get the values and id's of each select list and pass it to AJAX?
Edit
If you insist on going against jQuery's grain and using invalid HTML, here's a suitable solution for you:
$(function() {
$('button').click(function(){
var data = $(".attendSelect").wrap('<form/>').serialize();
$.post('process.php', data, function(response){ ... });
return false;
});
});
Worth mentioning, this example does not rely on fanciful .on() or .live() calls. However, this requires you to have the proper name attribute set on your <select> elements as described below. This also resolves your invalid numeric id attributes issue.
See it working here on jsFiddle
Original Answer
First off, some minor changes to your HTML. You need to wrap your <select> elements in a <form> tag. Using the form tag will give you access to jQuery's .serialize() method which is the exact functionality you're looking for. Personally, I'd recommend doing things the jQuery Way™ instead of implementing your own form a serialization. Why reinvent the wheel?
Next, your td have non-unique IDs. Let's update those to use a class attribute instead of an id. E.g.,
<td class="studentName">Aaron Colman</td>
Secondly, your <select> elements could benefit from a name attribute to make form processing way easier.
<select class="attendSelect" name="students[241]">
...
<select class="attendSelect" name="students[270]">
...
<select class="attendSelect" name="students[317]">
...
Lastly, jQuery's .serialize() is going to be your winning ticket.
$(function() {
$('form').submit(function(){
$.post('process.php', $(this).serialize(), function(response){ ... });
return false;
});
});
Upon submit, the serialized string will look something like
students[241]=Late&students[270]=Absent&students[317]=default
See it working here on jsFiddle
live() is deprecated as of jQuery 1.7, use on() instead
http://api.jquery.com/on/
students is an array, so I don't think you can do students['student_id'], if you would like to push an array of student, you can:
$('#saveAttendances').on('click', function() {
var students = [];
// iterate through <select>'s and grab key => values
$('.attendSelect').function() {
students.push({'id':$(this).attr('id'), 'val':$(this).val()});
});
$.post('/url.php', {data: students}, function() { // do stuff });
});
in your php:
var_dump($_POST); // see what's inside :)
As #nathan mentioned in comment, avoid using number as the first character of an ID, you can use 'student_<?php echo $id ?>' instead and in your .each() loop:
students.push({'id':$(this).attr('id').replace('student_', ''), 'val':$(this).val()});
Here's jQuery that will build an object you can pass to your script:
$('button').click(function() {
var attendance = new Object;
$('select').each(function() {
attendance[$(this).attr('id')] = $(':selected', this).text();
})
});
jsFiddle example.
This results in: {241:"Late",270:"Absent",317:"Late"}
Edit: Updated to iterate over select instead of tr.
Perhaps you want something like below,
DEMO
var $attendSelect = $('#tutorTable tbody tr select');
var students = {};
$attendSelect.each (function () { //each row corresponds to a student
students[$(this).attr('id')] = $(this).val();
});
This would give you an object like below,
students = { '241': 'Late', '270': 'Absent', '317': 'default' };
If the above is not the desired structure then modify the .each function in the code.
For ex: For a structure like below,
students = [{ '241': 'Late'}, {'270': 'Absent'}, {'317': 'default'}];
You need to change the code a little,
var students = [];
...
...
students.push({$dd.attr('id'): $dd.val()});
var $select = $('.attendSelect'),
students = [];
$('body').on('click', '#saveAttendances', function() {
$select.each(function(k, v) {
students[k] = {
student_id : $(this).attr('id'),
attedance : $(this).val()
};
});
console.log(students);
});
First problem is that I do not know how to get the values of SPECIFC checkboxes when they are checked.
I need a function that will get the value of the selected checkboxes by checkbox ID or Name.
This is the code I have so far:
$("#doStatus").click(function(){
var Tuitting = $('textarea#tuitting').val();
var F = $('input#Fb').val(); //checkboxes with ID Fb
var T = $('input#Tw').val(); //checkboxes with ID Tw
$.get("<?echo $site['url'];?>modules/yobilab/tuitting_core/classes/doStatusBox.php", { tuitting: Tuitting, f: F, t: T });
window.setTimeout('location.reload()', 1000);
return false;
});
Now the second problem is that both var F and var T may contain MORE than one values in an array..
Obviously when I use the ajax get functions the multiple values for both var F and var T are not
passed at all. What is the problem..?
How do I pass multiple values in an array that will be then runed by the foreach on the doStatusBox.php page?
Please help me.
$("#doStatus").click(function() {
var Tuitting = $('textarea#tuitting').val();
var F = $('input[name="fb"] :selected').val();
//You can give the name of checkbox and get the values of selected checkbox
return false;
});
I'm answering based on an assumption: you need checked checkboxes to pass them via GET method to your doStatusBox.php script.
However, why would you go trough the trouble of finding which checkbox is checked if you can simply use the serialize() method and let jQuery do the job for you?
$("#doStatus").click(function()
{
var serialized = $("#someFormHere").serialize()
// or, if you have your form elements within a div or another element
var serialized = $("#elementID :input").serialize();
$.get("<?echo $site['url'];?>modules/yobilab/tuitting_core/classes/doStatusBox.php", serialized);
window.setTimeout('location.reload()', 1000);
return false;
});
However, is "#doStatus" a submit button submitting the form or something else? If it submits the form, bind the submit event to the form, not click event to the button submitting it.
How would I fill in the boxes of my form if I select one of the values from the dropdown menu (The dropdown is got from the DB) Somehow in my javascript I need to connect to functions as there is to different tables involved with the form fields.
Question
Do I need to set the fields using $field name?
if(document.id('LoadExtension') && document.id('ExtensionResponse')) { // id of select box
var sel = document.id('LoadExtension'); // ser select box as var.
sel.addEvent('change', function(chg) { // add change event to select box.
if(sel.getSelected().get('value') != '') { // on change if selected value is not empty.
new Request.HTML({
url : 'http://domain.co.nz/index.php?extension='+ sel.getSelected().get('value'),
onRequest: function() {
},
onComplete: function(r1, r2, html, js) {
document.id('ExtensionResponse').set('html', html);
}
}).send();
}
});
}
The above code was set up to get from another document in the url: box but I would like to do it in one page.
for your code:
http://www.jsfiddle.net/dimitar/TXHYg/4/
(function() {
// anon closure for scope purposes of local vars.
// cache selectors used repeatedly into local vars.
var sel = document.id('LoadExtension'), resp = document.id('ExtensionResponse');
// if they are in the dom...
if (sel && resp) {
// ... then attach event listener.
sel.addEvent('change', function(event) {
// this == sel.
var value = this.get("value"); // cache getter.
if (value === '') {
return false; // do nothing if not selected/
}
// otherwise, it will run the request
new Request.HTML({
method: "get", // or post.
data: {
extension: value // etc etc, can add more object properties and values
},
url: 'http://domain.co.nz/index.php',
onComplete: function(r1, r2, html, js) {
resp.set('html', html);
}
}).send();
});
} // end if
})(); // end closure.
you should really look at some tutorials and examples and the documentation for Request and Request.HTML/JSON/JSONP
an example, similar to yours that works for jsfiddle through its echo testing service (slightly different data object that simulates the response)
http://www.jsfiddle.net/dimitar/TXHYg/3/
instead of document.id('ExtensionResponse') you can write $('ExtensionResponse')
an if you only update a content of a element you can use the update parameter from Request.HTML.
new Request.HTML({
url : 'http://domain.co.nz/index.php',
data: 'extension='+ sel.getSelected().get('value'),
update: $('ExtensionResponse')
}).send();
#medrod;
That's right about the $(), but using the latest version of mootools + making sure Jess stays library safe, document.id() is a much safer option for compatibility.
you need to build the rest of your form, and populate it, with in the result of the ajax request.
eg: http://domain.co.nz/index.php?extension=
start your first HTML form with only the drop down, then your ajax'd script will build and populate the rest of the form.