I am developing the app using CakePHP 1.3 Now I want to make the "Insert function" to add new user into database. I have 2 fields user & pass to insert. But I not only insert 1 user, I want insert one or multiple user (optional). If I want to add more user I will click to "add more" to add new field in view.
In cakephp, it required when we want to insert a array with multiple data. The field name will be define as:
<?php
echo $this->Form->input('Modelname.0.fieldname');
echo $this->Form->input('Modelname.1.fieldname');
?>
and in view will be:
<input type="text" id="Modelname0Fieldname" name="**data[Modelname][0][fieldname]**">
<input type="text" id="Modelname1Fieldname" name="**data[Modelname][1][fieldname]**">
My question is: Does JQuery have some function to add new element and how can I increase the index number follow the pattern above data[Modelname][0][fieldname]
Thank for your view and suggestion.
I've created this code, here it is, I've tested it and it works
http://codepen.io/anon/pen/xbxVQG
var $insertBefore = $('#insertBefore');
var $i = 0;
$('#plusButton').click(function(){
$i = $i+1;
$('<br><div class="Index">User N. ' + $i + '</div><br>Username:<br><input type="text" id="Modelname' + $i + 'Fieldname" name="**data[Modelname][' + $i + '][fieldname]**"><br>Password:<br><input type="text" id="Modelname' + $i + 'Password" name="**data[Modelname][' + $i + '][Password]**"><br>').insertBefore($insertBefore);
});
#Userlist{
border-style:solid;
width: 300px;
margin: 0 auto;
text-align:center;
padding: 0.5em;
}
.Index{
background-color:grey;
text-align:left;
}
#plusButton {
background-color:green;
color: white;
font-size:1.9em;
width: 300px;
margin: 0 auto;
text-align:center;
cursor: pointer;
}
<html>
<head>
<title>Add New Users</title>
<script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
</head>
<body>
<form action="your-script.php" method="post" id="Userlist">
<div class="Index">User N. 0</div>
Username:<br>
<input type="text" id="Modelname0Fieldname" name="**data[Modelname][0][fieldname]**"">
<br>Password:<br>
<input type="text" id="Modelname0Password" name="**data[Modelname][0][Password]**">
<br>
<div id="insertBefore"></div>
<br><br><input type="submit" value="Add User">
</form>
<div id="plusButton">+</div>
</body>
</html>
some important notes:
1- The div who's id="insertBefore" is just to tell jQuery where to put the new duplicated fields.
2- The jQuery code works with an index variable ($i) that starts in 0 and gets incremented by 1 on each new click on the "+" button (so the first time you click, it should get to 1)
3- The original Form's code (where value is 0 by default) is printed everytime the + button is clicked, but replacing each 0 in the html code by '+$i+'
3.2 - If you make some changes to the code of your form, by this method, you should change the javascript code as well. I know it's not an elegant solution to do this, but it shouldn't be so difficult either, just remember to copy the exact html code, delete all intro's and replace all 0's with '+$i+'
4- The "Index N." div is just keeping track of the user's number, you could put your own text there, like "User NÂș 0" and in the jQuery code replace the 0 with the value of $i
5- You could put a limit to the number of users (example:10) that can be added by creating an if($i<10){} variable inside the .click() function
Just write a jQuery code to append a user field. and also send data-id to the javascript.
Let say for example. in your form.
<div id="segment">
$this->Form->input('User.1.name',array('class'=>'user','data-id'=>1));
</div>
in jquery.you can have a function like this on click of add user,
var lastid = parseInt($('.user:last').attr('data-id');
var newid = lastid+1;
var input = "<input name='data[User][" + newid + "][name]' class='user' id='user-" + newid + "' data-id='" + newid + "' type='text'><br/>";
$('#segement').append(input);
Note that double check the input string, I might miss a quote or
anything.
Thanks for all answers about this, I was not test your code but I found the way to append and increase the index number too. When I have time, I will research about your code.
My code is follow this thread http://www.sanwebe.com/2013/03/addremove-input-fields-dynamically-with-jquery. He made it easily to understand.
The JS:
$(document).ready(function() {
var max_fields = 10; //maximum input boxes allowed
var wrapper = $(".input_fields_wrap"); //Fields wrapper
var add_button = $(".add_field_button"); //Add button ID
var x = 1; //initlal text box count
$(add_button).click(function(e){ //on add input button click
e.preventDefault();
if(x < max_fields){ //max input box allowed
x++; //text box increment
$(wrapper).append('<div><input type="text" name="mytext[]"/>Remove</div>'); //add input box
}
});
$(wrapper).on("click",".remove_field", function(e){ //user click on remove text
e.preventDefault(); $(this).parent('div').remove(); x--;
})
});
and the HTML:
<div class="input_fields_wrap">
<button class="add_field_button">Add More Fields</button>
<div><input type="text" name="mytext[]"></div>
</div>
The demo you can see in that link above.
More thank for everybody again.
Related
I want to be able to add n number of books to n number of authors. What I want to do is this:
where the light blue boxes are the buttons. I want to add multiple books to a author with the "add book" button.
the code that I have is this:
<form action="next.php" method="post">
<div class="input_fields_wrap">
<button class="add_field_button">Add Author</button>
<div><input type="text" name="myAuthorText[]"></div>
<button class="add_sub_field_button">Add Author Books</button>
<div><input type="text" name="myBooksText[]"></div>
</div>
</form>
<SCRIPT language="javascript">
$(document).ready(function() {
var max_fields = 10; //maximum input boxes allowed
var wrapper = $(".input_fields_wrap"); //Fields wrapper
var add_button = $(".add_field_button"); //Add button ID
var add_subButton = $(".add_sub_field_button"); //Add sub button ID
var x = 1; //initlal text box count
$(add_button).click(function(e){ //on add input button click
e.preventDefault();
if(x < max_fields){ //max input box allowed
x++; //text box increment
$(wrapper).append('<div><input type="text" name="myAuthorText[]"/>Remove</div>'); //add input box
}
});
$(add_subButton).click(function(e){ //on add input button click
e.preventDefault();
if(x < max_fields){ //max input box allowed
x++; //text box increment
$(wrapper).append('<div><input type="text" name="myBooksText[]"/>Remove</div>'); //add input box
}
});
$(wrapper).on("click",".remove_field", function(e){ //user click on remove text
e.preventDefault(); $(this).parent('div').remove(); x--;
})
});
</SCRIPT>
what I'm getting is:
Check this code snippet. I made some chnages in HTML and Javascript too. Please compare it with your original one to see the differences. Hope it will help you a bit:
$(document).ready(function() {
var max_fields = 10; //maximum input boxes allowed
var wrapper = $(".input_fields_wrap"); //Fields wrapper
var commonPart = $("#commonPart");
var add_button = $(".add_field_button"); //Add button ID
var add_subButton = $(".add_sub_field_button"); //Add sub button ID
var x = 1; //initlal text box count
$(add_button).click(function(e){ //on add input button click
e.preventDefault();
if(x < max_fields){ //max input box allowed
var htmlToAdd = commonPart.clone().attr("id","commonPart_"+x);
htmlToAdd.find(".addedDiv").remove();
$(wrapper).append(htmlToAdd); //add input box
x++; //text box increment
}
});
$(document).on("click",".add_sub_field_button",function(e){ //on add input button click
e.preventDefault();
if(x < max_fields){ //max input box allowed
x++; //text box increment
$(this).closest(".commonPart").append('<div class="addedDiv"><input type="text" class="bookname" name="myBooksText[]" placeholder="Book name"/>Remove</div>'); //add input box
}
});
$(wrapper).on("click",".remove_field", function(e){ //user click on remove text
e.preventDefault(); $(this).parent('div').remove(); x--;
})
});
.bookname{
margin-left: 30px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<form action="next.php" method="post">
<div class="input_fields_wrap">
<button class="add_field_button">Add Author</button>
<div id="commonPart" class="commonPart">
<div><input type="text" name="myAuthorText[]" placeholder="Auth name"></div>
<button class="add_sub_field_button">Add Author Books</button>
<div><input type="text" class="bookname" name="myBooksText[]" placeholder="Book name"></div>
</div>
</div>
</form>
You can use jquery.clone()
Like this:
$( "#id-of-input" ).clone().appendTo( "#id-of-same-div" );
Place this inside button click.
JSFiddle
Not a full answer, but this gives the nesting that you're looking for and lets you add books to multiple authors. I couldn't get the "saving" to work properly, I suspect the script in your question is not the complete script.
Key changes:
added styling to indent books
don't show the add book button until there is an author
add the "add book" button below each author
add books inside the author block, not the top level wrapper block
Disclaimer:
As I mentioned above, I wasn't able to test this fully. This answer is "you might find something like this helpful" rather than "I have fully and completely solved your problem, please copy+paste+deploy".
<form action="next2.php" method="post">
<div class="input_fields_wrap">
<button class="add_field_button">Add Author</button>
<div><input type="text" name="myAuthorText[]"></div>
</div>
</form>
<style>
.author_wrap button,
.author_wrap input {
margin-left: 10px;
}
</style>
<script type="text/javascript">
$(document).ready(function() {
var max_fields = 10; //maximum input boxes allowed
var wrapper = $(".input_fields_wrap"); //Fields wrapper
var author_wrapper = $(".author_wrap"); // Author's book fields wrapper
var add_button = $(".add_field_button"); //Add button ID
var add_subButton = $(".add_sub_field_button"); //Add sub button ID
var x = 1; //initlal text box count
$(add_button).click(function(e){ //on add input button click
e.preventDefault();
if(x < max_fields){ //max input box allowed
x++; //text box increment
$(wrapper).append('<div class="author_wrap"><input type="text" name="myAuthorText[]"/>Remove<br/><button class="add_sub_field_button">Add Author Books</button><div><input type="text" name="myBooksText[]"></div></div>'); //add input box
}
});
$(add_subButton).click(function(e){ //on add input button click
e.preventDefault();
if(x < max_fields){ //max input box allowed
x++; //text box increment
$(author_wrapper).append('<div><input type="text" name="myBooksText[]"/>Remove</div>'); //add input box
}
});
$(wrapper).on("click",".remove_field", function(e){ //user click on remove text
e.preventDefault(); $(this).parent('div').remove(); x--;
})
});
</script>
Note: I took the liberty of replacing the depracated language attribute on the script tags with type='text/javascript'
i dont want to use serialize() function please help me with this. I am a beginner
html
<input type='button' value='Add Tier Flavor' id='Add'>
<input type='button' value='Remove Tier Flavor' id='Remove'>
<div id='batch'>
<div id="BatchDiv1">
<h4>Batch #1 :</h4>
<label>Flavor<input class="textbox" type='text' id="fl1" name="fl[]" value=""/></label></br>
<label>Filling<input class="textbox" type='text' id="fi1" name="fi[]" value="" /></label></br>
<label>Frosting<input class="textbox" type='text' id="fr1" name="fr[]" value=""/></label></br>
</div>
</div>
<br>
</div>
this is a dynamically added fields using javascript the code is:
javascript
<script src="http://code.jquery.com/jquery-1.10.1.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
var counter = 2;
$("#Add").click(function () {
if(counter>5){
alert("Only 5 Tiers allow");
return false;
}
var newBatchBoxDiv = $(document.createElement('div')).attr("id", 'BatchDiv' + counter);
newBatchBoxDiv.html('<h4>Batch #'+ counter + ' : </h4>' +
'<label> Flavor<input type="text" name="fl[]" id="fl' + counter + '" value=""></label><br>'+
'<label> Filling<input type="text" name="fi[]" id="fi' + counter + '" value=""></label><br>'+
'<label> Frosting<input type="text" name="fr[]" id="fr' + counter + '" value=""></label><br>' );
newBatchBoxDiv.appendTo("#batch");
counter++;
});
$("#Remove").click(function () {
if(counter==1){
alert("No more tier to remove");
return false;
}
counter--;
$("#BatchDiv" + counter).remove();
});
});
</script>
i am trying to post the values in an array to post it onto next .php page
i am using this
var user_cupfl = $('input[name^="fl"]').serialize();
var user_cupfi = $('input[name^="fi"]').serialize();
var user_cupfr = $('input[name^="fr"]').serialize();
serialize is not passing the values. :(
on second page i am trying to mail it using
$message .= "<tr><td><strong>Cake Flavors(according to batches):</strong> </td><td><pre>" .implode("\n", $user_cupfl). "</pre></td></tr>";
$message .= "<tr><td><strong>Filling type (Inside the cake):</strong> </td><td><pre>" .implode("\n", $user_cupfi). "</pre></td></tr>";
$message .= "<tr><td><strong>Frosting type (top of the cake):</strong> </td><td><pre>" .implode("\n", $user_cupfr). "</pre></td></tr>";
i m posting array like this
$user_cupfl=filter_var($_POST["userCupfl"], FILTER_SANITIZE_STRING);
$user_cupfi=filter_var($_POST["userCupfi"], FILTER_SANITIZE_STRING);
$user_cupfr=filter_var($_POST["userCupfr"], FILTER_SANITIZE_STRING);
your replies will be highly appreciated
Just because you name a variable user_* doesn't mean that is what the name of the field is in the serialized POST data. You would still be looking for $_POST['fl'], $_POST['fi'] etc.
I don't understand why you think you need to serialize sets of input groups individually. You should just serialize the whole form at once.
I also see no reason why you need to have all this logic around unique id's with the counter and what not. If you are not using id's at all, just drop them altogether.
You might also consider simply using clone techniques to generate your dynamically added fields. You could greatly simplify all that javascript code by doing these things.
A more reasonable implementation may look like this.
HTML (cleaning up your code - consistent use of double quotes around properties, better strategy for class and id usage, etc.)
<div id="batch">
<div class="batchDiv">
<h4 class="batchLabel">Batch #1 :</h4>
<label>Flavor</label>
<input class="textbox" type="text" name="fl[]" value=""/>
</br>
<label>Filling</label>
<input class="textbox" type="text" name="fi[]" value="" />
</br>
<label>Frosting</label>
<input class="textbox" type="text" name="fr[]" value=""/>
</br>
</div>
</div>
Javascript:
$(document).ready(function() {
$('#Add').click(function(){
var $existingBatches = $('.batchDiv');
var count = $existingBatches.size();
if (count < 5) {
// get last batch div
var $newBatch = $existingBatches.last().clone();
// reset input values to empty string
$newBatch.find('input').val('');
// change batch label
count++;
$newBatch.find('.batchLabel').html('Batch #' + count + ' :');
// append to document
$newBatch.appendTo('#batch');
} else {
// alert or whatever
}
});
$('#Remove').click(function(){
var $existingBatches = $('.batchDiv');
var count = $existingBatches.size();
// delete last batch item if more than 1 exists
if(count > 1) {
$existingBatches.last().remove();
} else {
// alert or whatever
}
});
});
Now you haven't shown your AJAX code, but all you would need to do is something like:
var url = '/some/url';
var postData = $('[some form selector]').serialize();
var dataType = '...'; //whatever dataType you are expecting back
$.post(url, postData, function(){
// success handler
}, dataType));
Your data when then be available in PHP script at $_POST['fl'], etc.
I use a css style for personal information cards.
For example:
<strong>Name: </strong><p>Bla Bla</p>
<h1>Contact Info</h1>
<p>E-mail: blablabla</p>
Now I want to do this with PHP. I've designed my code and template for this. When you fill two textboxes (name, e-mail) and click the button, it gives me the HTML code.
But some people has more than one e-mail. So I've to add second (3rd, 4th) textbox for them. How can I do this without losing the old textbox datas?
Name: filled
E-mail: filled
I need to enter another e-mail so lets click this button for another textbox.
Boom
Name: empty
E-mail: empty
Email2: empty
How to prevent that?
I believe it would be beneficial for everybody if you could post snippet of the code you attempted.
Anyway I have to admit I don't really understand what exactly you're trying to achieve but you may want to check out the variable passing in php PHP variable passing
If I understodd.
To do this has two ways:
1) do in Jquery.
<html>
<head>
<title>jQuery add / remove textbox example</title>
<script type="text/javascript" src="jquery-1.3.2.min.js"></script>
<style type="text/css">
div{
padding:8px;
}
</style>
</head>
<body>
<h1>jQuery add / remove textbox example</h1>
<script type="text/javascript">
$(document).ready(function(){
var counter = 2;
$("#addButton").click(function () {
if(counter>10){
alert("Only 10 textboxes allow");
return false;
}
var newTextBoxDiv = $(document.createElement('div'))
.attr("id", 'TextBoxDiv' + counter);
newTextBoxDiv.after().html('<label>Textbox #'+ counter + ' : </label>' +
'<input type="text" name="textbox' + counter +
'" id="textbox' + counter + '" value="" >');
newTextBoxDiv.appendTo("#TextBoxesGroup");
counter++;
});
$("#removeButton").click(function () {
if(counter==1){
alert("No more textbox to remove");
return false;
}
counter--;
$("#TextBoxDiv" + counter).remove();
});
$("#getButtonValue").click(function () {
var msg = '';
for(i=1; i<counter; i++){
msg += "\n Textbox #" + i + " : " + $('#textbox' + i).val();
}
alert(msg);
});
});
</script>
</head><body>
<div id='TextBoxesGroup'>
<div id="TextBoxDiv1">
<label>Textbox #1 : </label><input type='textbox' id='textbox1' >
</div>
</div>
<input type='button' value='Add Button' id='addButton'>
<input type='button' value='Remove Button' id='removeButton'>
<input type='button' value='Get TextBox Value' id='getButtonValue'>
</body>
</html>
2) in PHP using Session
Store variable in a Session after you submit your form
I have a jquery function that retrieves information that a user clicks on in a database table.The user can select any one of ten rows that becomes highlighted when mouseover and when the user clicks the highlighted row the function retrieves it and puts it into a textbox. Then if the user submits this request for purchase I want to echo the textbox on the next page which is an order form.
The code below works well up until I try to retrieve the information from the url. I can see that it is passed in the url to the next page but after trying for two days I have not been able to retrieve it. I don't know where to go from here. Can someone look at this and see if I have not coded properly or done something wrong.
I have copied down the code that applies...
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("table tr").click(function(){
$("#txttread").val($.map($(this).children('td:not(:eq(7))'), function (item) { return $(item).text() }).join(' - '));
});
});
$(document).ready(function() {
$('.pickme tr').not(':first').hover(
function() { $(this).addClass('highlight'); },
function() { $(this).removeClass('highlight'); }
).click( function() {
$('.selected').removeClass('selected');
$(this).addClass('selected').find('input').attr('checked','checked');
});
});
</script>
</head>
<body>
<form action="Order.html" method="GET" name="myform2" />
<div>
<div style="text-align:left height:250px;">
<DIV STYLE="font-family: Arial Black;
color: black; font-size: 20pt;">
Select from inventory below:<br/><input type="text" style="width:500px; height:35px;" rows="1" STYLE="font-family: Arial Black;
color: red; font-size: 20pt;" name="txttread" id="txttread" DISABLED /></div></div></div>
<div>
<div style="text-align:center;">
<br/><input type="button" button id="getone" name="getone" value="Submit your request for purchase" onclick="window.location.href = 'http://localhost/order.html?txttread='+ ( $('#txttread').val() )"><br/><hr/>
</body>
</html>
The url on the next page is....
http://localhost/order.html?txttread=Firestone - All Season - FR-710 - 225/60/16 - 4 - 3 - 60.00
I think this has to do with the URL not being encoded correctly. On that last line where you append the $('#txttread').val(), you should wrap it with encodeURIComponent():
<input type="button"
button id="getone"
name="getone"
value="Submit your request for purchase"
onclick="window.location.href = 'http://localhost/order.html?txttread=' + encodeURIComponent($('#txttread').val());">
This might not answer your question completely, but consider this:
window.location.href = 'http://localhost/order.html?txttread='+ ( $('#txttread').val() )
You should apply proper escaping when you pass parameters:
window.location.href = 'http://localhost/order.html?txttread=' + encodeURIComponent( $('#txttread').val() );
To access the value of txttread from an HTML page:
function getParameterByName(name)
{
name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
var regexS = "[\\?&]" + name + "=([^&#]*)";
var regex = new RegExp(regexS);
var results = regex.exec(window.location.search);
if(results == null)
return "";
else
return decodeURIComponent(results[1].replace(/\+/g, " "));
}
As found here: https://stackoverflow.com/a/901144/1338292
I am using Jquery ui functions and created Drag and Drop plugins. The all i have achieved is the draggable item and droppable area and implemented this successfully.
My next step is to drop my working plugins to be drop into the ckeditor body both source or design view.
i am using this code to make drag drop.
HTML
<div class="item" id="image">
<label class="title">Image</label>
<label class="price"></label>
</div>
<div id="cart_items" class="back"></div>
JavaScript :
$("#cart_items").droppable({
accept: ".item",
//activeClass: "drop-active",
//hoverClass: "drop-hover",
drop: function(event, ui) {
var coordsp=[];
var coordsc=[];
var item = ui.draggable.html();
var itemid = ui.draggable.attr("id");
//alert(itemid);
var coordsp = $('#cart_toolbar').position();
var coordTopp = coordsp.top ;
var coordLeftp = coordsp.left;
//alert(itemid);
var coordsc = $('#'+itemid).position();
//alert(coordsc.top);
//alert(coordsc.left);
var coordTopc = coordsc.top ;
var coordLeftc = coordsc.left;
var coordLeft = coordLeftc-coordLeftp;
//var coordLeft = 0;
var coordTop = coordTopc-coordTopp;
//numControls++;
var numControls = document.getElementById('numControls');
controls_count += 1;
numControls.value = controls_count;
count += 1;
var hrml_sort_pre = '<div class="column" id="column1">';
if(itemid == "image")
{
var html = '<div class="dragbox" id="item'+count+'"><img src="<?=base_url()?>/css/move_arrow.gif" alt="no-image" class="drag-image"><h2 id="'+count+'" value="para_1" onclick="do_collapse(this);" onmouseup="do_fill_data(this.id);" onmouseover="fetch_editor_data(this.id);" > </h2><div style="float:right;margin-top:-20px;margin-right:4px"><a onclick="remove_item(\'item'+count+'\')" id="remove'+itemid+count+'" class="remove'+itemid+count+' x-button"> </a></div><div class="dragbox-content" ><div id="item_cart_'+count+'" style=" position: relative; left: 0px; top:-2px;width:100%;">';
html = html + '<a id="image_'+count+'" href="<?=base_url()?>index.php/media/index/'+count+'" ><img src="<?=base_url()?>images/na.jpg" id="temp_image_'+count+'" name="para_'+count+'" onclick="box_load(\'image_'+count+'\')" title = " " alt = "" /></a><input type="hidden" name="control_type[]" value="image" /><input type="hidden" id="input_temp_image_'+count+'" name="content[]" value="" /> <input type="hidden" name="image-para[]" value="" /></div></div></div>';
}
$("#cart_items").append(html); }}
Is there any way that we can use this to drop image html in editor and call some function on it.
Thanks in advance
You could create a CKEditor plugin that creates a button on the toolbar. This button would then inject the javascript, and then the markup for the drop area.
However, I see a major problem with this kind of implementation. Be careful when putting script tags inside the CKEditor body, as CKEditor will most likely filter this out upon submit.
Instead of creating a plugin which would inject the HTML into the body of the editor (thus creating multiple copies of the same code around the site), why not use a token, and then parse the token upon loading the content into the page?
Here's a couple of references for creating CKEditor plugins to help get you started:
CKEditor Plugin Development
Official CKEditor Plugin Creation Tutorial
The CKEditor Javascript API