Add form elements to one form element - php

Ok ,
Lets say I am creating a form. And its an address form,form elements as such :
field 1 / house number
field 2 / street name
field 3 / suburb
etc etc etc
And someone fills in the form,:
1
smith street
townsville
What I want ( similar to stack overflows live form )
Is another form element, that propagates the form field entries LIVE but replaces spaces with text:
So it appears like: 1+snith+street+townsville
With a search button at the end. This then triggers the rest of the script we have already done, which basicaly grabs the lat and long of the address and displays a gmap.
Thats essentially it, but we would need that all this occurs, whilst on the form, and before submission.
Any help appreciated, have asked several other places. No joy, but always use StackOverflow..
Thanks Ozzy

$('#my_form input').change(function() {
var new_text = '';
$('#my_form input').each(function() {
new_text += $.trim($(this).val()).replace(' ', '+') + '+';
});
$('#my_display').val(new_text);
});

here something that might work. . .
$(document).ready(function(){
$('body').live('keypress', function (event) {
if ($(event.target).hasClass('form-element')) {
var text;
$('#yourform input.form-element').each(function() {
text += $(this).attr('value') + '+';
});
$('#yourtargetelementthatwillholdallthenames').attr('value', text.substring(0,text.length - 1))
}
});
});
i haven't tried this in a browser, but give it a shot. It might need some tweaking for your needs.

If you're submitting this for a search, use encodeURIComponent() instead so you encode everything needed, like this:
$("#form1 input[type=text]").bind("keyup change", function() {
var vals = $("#form1 input[type=text]").map(function() { return this.value; });
$("#otherField").val(encodeURIComponent(vals.join(" ")));
});

Related

Jquery Change Input background color if entry matches PHP Array?

I have a simple form that has 3 fields. user, id, email.
I have 2 PHP arrays $user & $id
When a user enters there name into the user or id fields I want the respective php arrays checking and if the name or id is in the array then change the background color of the input box they are currently in.
If they update there entry then the checking should continue and if no match is found then revert the background back to it's original white color.
If they empty the input field then the color should change back to white.
The page may be preloaded with values, so I may be changing the background color using php on the initial load..
I've found this, which sort of works for the specified characters in it's array:
$('input').bind("change keyup", function() {
var val = $(this).val();
var regex = /["<>&]/g;
if (val.match(regex)) {
$(this).css("background", "red");
val = val.replace(regex, "");
$(this).val(val);
}
$("p").html(val);
});
I've tried to update it to support a php array, but it doesn't work and I don't know how to make it check either array and revert the color back.
This is what I have so far :
JFIDDLE
Thanks :)
UPDATE
I've got this working using the following :
$(function(){
$('input').bind("change keyup", function() {
var val = $(this).val();
if ($(this).attr('id')=="user") {
var check = <?php echo json_encode($user)?>;
} else {
var check = <?php echo json_encode($id)?>;
}
if ($.inArray(val, check) != -1) {
$(this).css("background-color", "red");
} else {
$(this).css("background-color", "white");
}
});
});
But is there a neater way to write this ?
Thanks :)
if you want to use your php array in javascript, you can do this:
var myArray = <?php echo json_encode($myArray) ?>;
and do the javascript magic

Submit jQuery multiple date picker form as POST data

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']);

How would I duplicate form elements AND the data inside them with jQuery?

See this form - http://schnell.dreamhosters.com/form.php
This form has a portion of it where you enter data and can choose to add more of the same data by clicking a button called 'Add A Site' and it will make another of that section to enter another site. This is the jQuery that performs the duplication...
$(function () {
var sites = 1;
var siteform = $("#site1").html();
$(".addsites").live("click", function(e) {
e.preventDefault();
sites++;
$("#events").append("<div id='site" + sites + "'>"
+ "<br /><hr><br />"
+ siteform
+ "<center><button class='removesites' title='site"
+ sites + "'>Remove This Site</button><br />"
+ "<button class='addsites'>Add Another Site</button>"
+ "</center></div>");
});
$(".removesites").live("click", function(e) {
e.preventDefault();
var id = $(this).attr("title");
$("#" + id).remove();
});
});
The duplication works perfectly, but one thing that's bugging me is that when I have to enter data for someone claiming a LOT of sites, it gets very annoying having to repeat same or similar parts of this section of the form (like every site is in the same city, on the same day, by the same person, etc.) So I had the idea that with each duplication, the values of the form elements would also carry over and I just edit what's not the same. The current implementation only duplicates the elements, not the data. I'm not sure how to easily copy the data into new sections, and I can't find any jQuery tools to do that.
PS - This part isn't as important, but I've also considered using this same form to load the data back in for viewing/editing, etc. The only problem with this is that the reprinting of the form means that there will be a form section with the id "Site7" or something, but jQuery starts its numbering at 1, always. I've thought about using selectors to find the highest number site and start off the variable 'sites' at that number, but I'm not sure how. Any advice how to do this, or a better system overall, would be much appreciated.
You want to itterate over the input fields in siteform and store them in an object using their name attribute as a key.
Then after the duplication of the object you made and look for the equivelant fields in the new duplicated form ans set their values.
Somthing like this (not tested, just the idea)
var obj = new Object();
$("#site1 input").each(function(){
obj[this.id] = this.value;
);
// Dupicate form
$.each(obj, function(key, value){
$('#newform input[name="'+key+'"]').value = value;
});
Mind you these two each() functions differ from each other.
http://api.jquery.com/jQuery.each/
http://api.jquery.com/each/
You could consider using cloneNode to truely clone the previous site-div and (by passing true to cloneNode) all of its descendants and their attributes. Just know that the clone will have the same id as the original, so you'll have to manually set its id afterwards
Try this in your click-function
var clone = $("#site" + sites).clone(true, true); // clone the last div
sites++; // increment the number of divs
clone.attr('id', "site" + sites); // give the clone a unique id
$("#events").append(clone); // append it to the container
As Scuzzy points out in a comment jQuery does have its own clone() method (I don't use jQuery much, so I didn't know, and I didn't bother to check before answering). Probably better to use jQuery's method than the built-in cloneNode DOM method, since you're already using jQuery for event listeners. I've updated the code
The query to transfer values is quite simple (please, check the selector for all the right types on the form):
$("#site1").find("input[checked], input:text, input:hidden, input:password, input:submit, option:selected, textarea")
//.filter(":disabled")
.each(function()
{
$('#site2 [name="'+this.name+'"]').val(this.value);
}
Ok I finally figured this out. It's, more or less, an expansion on Alex Pakka's answer.
sites++;
$("#events").append("<div id='site" + sites + "'>"
+ "<hr><br />"
+ siteform
+ "<center><button class='removesites' title='site"
+ sites + "'>Remove This Site</button><br />");
$("#site1").find("input:checked, input:text, textarea, select").each(function() {
var name = $(this).attr("name");
var val = $(this).val();
var checked = $(this).attr("checked");
var selected = $(this).attr("selectedIndex");
$('#site' + sites + ' [name="'+name+'"]').val(val);
$('#site' + sites + ' [name="'+name+'"]').attr("checked", checked);
$('#site' + sites + ' [name="'+name+'"]').attr("selectedIndex", selected);
});
I used extra vars for readability sake, but it should do just as fine if you didn't and used the methods directly.
Dont forget to create a function for registering the event! Its very important because when the DOM is loaded, all new attributes need to be registrated to the DOM.
Small example:
<script>
$(document).ready(function(){
$('#click-me').click(function(){
registerClickEvent();
})
function registerClickEvent(){
$('<input type="text" name="input_field_example[]">').appendTo('#the-div-you-want')
}
registerClickEvent();
})
</script>

how to extract data from an array in PHP

Hello Stack Overflow i hope you are well today;
So i am using jQuery to append a form with more input fields;
The Session is storing the data as an Array for the key: Children.
I would like to know show the user the data in that array how would this be done?
jQuery that adds the input fields (some pages previous)
$('.children-main-add').click(function(){
var attrName = $(this).attr('name');
var count = $(this).attr('count');
$(this).attr('count', (parseInt(count)+1))
var input = $('<input />');
input.attr('type','text')
input.attr('name',attrName+"["+count+"]" )
$('.children-main').append($('<li />').append(input));
$('#content li').removeClass('alt');
$('#content li:odd').addClass('alt');
$(this).val('Add Another Child');
})
The data from the session : Key: children / Value: Array
If i was not clear on something please let me know !
I thank you in advance for your help
if you want to show them as an continue string
use impode(',' , $_SESSION['children']);
Or
if(isset($_SESSION['children']) && is_array($_SESSION['children']))
{
foreach($_SESSION['children'] as $child)
{
echo $child."<br />";
// some other html
}
}

Printing results from function on page onclick?

Honestly, I'm not even sure the best way to go about this, but essentially, I have a function in an include file that takes a $type parameter and then will retrieve/print results from my db based on the $type passed into it... What I'm trying to do is have a series of links on a page that, when you click on a certain link, will run the function and display the results accordingly...
So, on the initial load of the page, there is a table that displays everything (and I'm simplifying the table greatly...)
<table>
<tr><th>Item</th><th>Type</th></tr>
<tr><td>Milk</td><td>Dairy</td></tr>
<tr><td>Yogurt</td><td>Dairy</td></tr>
<tr><td>Chicken</td><td>Meat</td></tr>
<tr><td>Zucchini</td><td>Vegetable</td></tr>
<tr><td>Cucumber</td><td>Vegetable</td></tr>
</table>
And, then, in a sidebar, I have a series of links:
Dairy
Meat
Vegetable
I'd like to filter the initial table (and back and forth, etc.) based on the link that is clicked, so that if the user clicks "Vegetable", the function from my include file will run and filter the table to show only "Vegetable" types...
The first idea that comes to mind is to add a class attribute to the <tr> tags and id attribs to the <a> tags so that you can easily filter that way:
<tr class="dairy"><td>Milk</td><td>Dairy</td></tr>
<tr class="meat"><td>Chicken</td><td>Meat</td></tr>
Dairy
Meat
Then in your JavaScript (I'm using jQuery here):
$('a').click(function(evt){
var myId = $(this).attr('id');
$('tr').each(function(idx, el){
if ($(el).hasClass(myId))
{
$(el).show();
}
else
{
$(el).hide();
}
});
});
This has the added benefit of allowing you to localize the text without having to change your code.
Ok I created a proper answer. You can do it the way Darrel proposed it. This is just an extension for the paging thing to avoid cookies:
$('a').click(function(evt){
var myId = $(this).attr('id');
// append a idndicator to the current url
var location = "" + document.location + "";
location = location.split('#',1);
document.location = location + '#' + $(this).attr('id');
//append to next and previous links
$('#nextlink').attr({
'href': $('#nextlink').attr('href') + '#' + $(this).attr('id')
});
$('#previouslink').attr({
'href': $('#previouslink').attr('href') + '#' + $(this).attr('id')
});
$('tr').each(function(idx, el){
if ($(el).hasClass(myId))
{
$(el).show();
}
else
{
$(el).hide();
}
});
});
Some code that is executed after page load:
var filter = window.location.hash ? '[id=' + window.location.hash.substring(1, window.location.hash.length) + ']' : false;
if(filter)
$('a').filter(filter).click();
This simulates/executes a click on page load on the link with the specific id.
But in general, if you have a large database, you should filter it directly with SQL in the backend. This would make the displayed table more consistent. For example if page 1 may only have 3 rows of class 'dairy' and on page 2 10 of class 'dairy'.
If youre printing out the whole tabel up front there is no need to go back to the server you can simple hide all teh rows of a given type. For example with jQuery:
$('#sidebar a').click(function(){
// grab the text content of the a tag conver to lowercase
var type = $(this).text().toLowerCase();
/* filter all the td's in the table looking for our specified type then hid the
* row that they are in
*/
$('#my_data_table td').contents().filter(function(){
return this.nodeType == 3 && this.toLowerCase() == type;
}).parent('tr').hide();
return false;
});
Really though the suggestion abotu adding a class to the TR is better because filtering on text content can get tricky if there is content youre not expecting for some reason (hence my conversion to all lower case to help with this).

Categories