I have a form where I add input fields dynamically using a jquery and then submitting the values of that form using Laravel Php
My html:
<div class="input_fields_wrap">
<button class="add_field_button">Add More Fields</button>
<div>
<input type="text" name="mytext[]">
</div>
</div>
My script:
<script type="">
$(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--;
})
});
</script>
The problem is that when I submit the values I've entered in the input boxes and try to capture them using the following Laravel code.
$mytext =Request::get('mytext');
dd($mytext);
Only the first value of the input I've defined in the html is captured no matter how many text inputs I add.
The output:
array:1 [▼
0 => "Text box 1"
]
How do I solve this? Thanks
You can add different name for the each input you add.
Your HTML:
<input type="text" name="mytext[text]">
Your JS:
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
$(wrapper).append('<div><input type="text" name="mytext[text'+ x++ +']"/>Remove</div>'); //add input box
}
});
The output will be:
"mytext" => array:4 [▼
"text" => "Text"
"text1" => "Text1"
"text2" => "Text2"
"text3" => "Text3"
]
Hope this help!
You already have a variable to count the appended inputs...
Use it!
Notice name="mytext'+x+'":
$(wrapper).append('<div><input type="text" name="mytext'+x+'"/>Remove</div>');
And also sent the x to know how many are sent.
Related
I am using appended below script to display multiple input box as per customer needs, as the name is same, so all values are saving in database in an array form. i want to display these values in input boxes once customer save his form. suppose if customer generate three input boxes and set values 1. abc 2. def 3. ghi, how to generate 3 input fields on page load and put these values in it?? i am new to javascript, any help is highly appreciated. Here is my codes:
$value = "abc,def,ghi"
$(document).ready(function() {
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
x++; //text box increment
$(wrapper).append('<div><input type="text" name="new_field_5[]" placeholder="Description"/>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 src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<div class="input_fields_wrap">
<button class="add_field_button">Add More Fields</button>
<div><input type="text" name="new_field_5[]" placeholder="Description" value="<?php echo $value;?>"></div>
</div>
You could create a Ajax request to the php file which returns all of the values for the inputs, and then use a for in loop to assign those values to each input
I have a form with possibility to add additional input fields. I get those values with $_POST['input_name'] and can insert to db / send mail. The problem is that I want those fields and values be displayed when page is refreshed if there was errors left, but I can't get values of dynamically added inputs in Jquery code - just the first one which is added statically. Is it possible to get those values in jQuery code?
My HTML
<div class="field_wrapper">
<div>
<input type="text" name="input_name[]" class="form-control" placeholder="Enter name" value="<?php if(isset($_POST['input_name'])) echo $_POST['input_name'][0];?>"/>
</div>
</div>
My jQuery
jQuery(document).ready(function(){
console.log(jQuery('#contactForm').serialize()); <- getting first value
var vals = jQuery("input[name='input_name[]']").map(function(){ return this.value}).get();
console.log(vals); <- getting first value
var maxField = 10; //Input fields increment limitation
var addButton = jQuery('.add_button'); //Add button selector
var wrapper = jQuery('.field_wrapper'); //Input field wrapper
var x = 1; //Initial field counter is 1
//Once add button is clicked
jQuery(addButton).click(function(){
//Check maximum number of input fields
if(x < maxField){
var fieldHTML = '<div><input type="text" name="input_name[]" class="form-control" placeholder="Enter name"/> \
</div>';
x++; //Increment field counter
jQuery(fieldHTML).appendTo(wrapper); //Add field html
}
});
//Once remove button is clicked
jQuery(wrapper).on('click', '.remove_button', function(e){
e.preventDefault();
jQuery(this).parent('div').remove(); //Remove field html
x--; //Decrement field counter
});
});
I want a teacher to select multiple classes when he click a button, the classes are selected from the database and displayed via an tag. I have made a function which makes a new select and displays another list of the classes, however my foreach loop doesn't seem to work...
Here's my JQuery which is inside a 'script' tag in the HTML:
$(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><select name="klas" style="width:40%;"><?php foreach ($klas as $klas) {echo "<option value='".$klas->getCode()."'>".$klas->getCode()."</option>"; } ?></select>Verwijder</div>'); //add input box
}
});
$(wrapper).on("click",".remove_field", function(e){ //user click on remove text
e.preventDefault(); $(this).parent('div').remove(); x--;
})
});
This is the button and the corresponding div's:
<div class="input_fields_wrap">
<button type="button" class="add_field_button">Add More Fields</button>
<div>
<select name="klas">
<?php foreach ($klas as $klas) {
echo "<option value='".$klas->getCode()."'>".$klas->getCode()."</option>"; } ?>
</select>
</div>
</div>
Does someone have any idea how I can achieve the same result from JQuery as from the regular php/html select box?
put your array in arr format in this answer and append to the div wherever you want on page currently i use select_div
<div class="input_fields_wrap">
<button type="button" class="add_field_button">Add More Fields</button>
<div id ="select_div">
</div>
</div>
<script type="text/javascript">
var arr = [
{val : 1, text: 'One'},
{val : 2, text: 'Two'},
{val : 3, text: 'Three'}
];
var sel = $('<select>').appendTo('#select_div');
$(arr).each(function() {
sel.append($("<option>").attr('value',this.val).text(this.text));
});
sel.append("</select>")
</script>
Found it. Your problem is that you use the same value name for both $klas array as well as internal foreach variable. While this is not technically incorrect, notice that after foreach $klas variable will be equal to last element of the array - not the array itself.
Since you were using this loop inside javascript it was tough to spot, and local test with foreach showed that everything is fine.
Anyway please update your code (everywhere were it is used) from:
<?php
foreach ($klas as $klas) {
$klas->getCode()
}
?>
to
<?php
foreach ($klas as $k) {
$k->getCode();
}
?>
On my page I can create a new div container with 2 field (1x input type text, 1x textarea), when I press on the button "Schritt hinzufügen".
If I press the button "Schritt entfernen", it will remove the last container. I use jquery for this action. If I press on the button "Erstellen", jquery will check if all fields are filled (without the input fields type file). If some fields arent filled, they will get a red border.
But now I want, that when I focus a input field, that the red edge will go away. It works not 100%. On this code it work's (not created with jquery):
<div class="step">
<div class="header_step">Allgemeines zum Tutorial</div>
<div class="body_step">
<a class="create_tutorial_a">Titel des Tutorial's</a><input class="create_tutorial_input" type="text" name="input_tutorialtitle_name"/>
<br>
<a class="create_tutorial_a">Autor des Tutorial's</a><input class="create_tutorial_input" type="text" name="input_tutorialauthor_name"/>
<br><br>
<a class="create_tutorial_a_full_width">Beschreibung des Tutorial's</a>
<br>
<textarea class="create_tutorial_textarea" name="input_tutorialdescription_name"></textarea>
</div>
</div>
And here is a exapmple div container (created with jquery):
<div class="step">
<div class="header_step">Schritt 1 des Tutorial's</div>
<div class="body_step">
<a class="create_tutorial_a">Titel des Schrittes</a>
<input name="input_title_name1" class="create_tutorial_input" type="text">
<br>
<a class="create_tutorial_a">Bild</a>
<input type="file">
<br><br>
<a class="create_tutorial_a_full_width">Beschreibung des Schrittes</a>
<br>
<textarea class="create_tutorial_textarea" name="input_description_name1">
</textarea>
</div>
</div>
if I press again the button "Schritt hinzufügen", I will get the same container, only the name's of the fields, will get a other number.
And here is the jquery code to remove a class of the input field's:
$('input[type="text"]').click(function(){
$(this).removeClass("empty_field");
});
$('textarea').click(function(){
$(this).removeClass("empty_field");
});
If you didnt understand me, you can test it by yourself. Here is the page link: MyPage
First press the button "Schritt hinzufügen" two times, then press the button "Erstellen". After this, every input field (not filled) will get a red border. If you focus the first input field of the page ("Titel des Tutorial's") and then "unfocus" it, you will see the border will go away. But at the created step's with jquery it wont work (focus them & unfocus then (the border wont go away)). Maybe someone of you have a idea^^
Edit --- My complete js code:
$(document).ready(function() {
var max_fields = 11; //maximum input boxes allowed
var wrapper = $(".all_steps"); //Fields wrapper
var add_button = $("#add_step"); //Add button ID
var remove_step = $("#remove_step");
var x = 1; //initlal text box count
$(add_button).click(function(){ //on add input button click
if(x < max_fields){ //max input box allowed
$(wrapper).append('<div class="step"><div class="header_step">Schritt '+ x +' des Tutorial\'s</div><div class="body_step"><a class="create_tutorial_a">Titel des Schrittes</a><input name="input_title_name'+x+'" class="create_tutorial_input" type="text" /><br><a class="create_tutorial_a">Bild</a><input type="file" /><br><br><a class="create_tutorial_a_full_width">Beschreibung des Schrittes</a><br><textarea class="create_tutorial_textarea" name="input_description_name'+x+'"></textarea></div>');
x++; //text box increment
}
});
$(remove_step).click(function(){ //user click on remove text
if(x > 1){
$('.all_steps .step:last').remove();
x--;
}
});
$('form.send').on('submit', function(){
var empty = false;
$('input[type="text"]').each(function(){
if ($.trim($(this).val()) == '') {
$(this).addClass("empty_field");
empty = true;
}
else{
$(this).removeClass("empty_field");
}
});
$('textarea').each(function(){
if ($.trim($(this).val()) == '') {
$(this).addClass("empty_field");
empty = true;
}
else{
$(this).removeClass("empty_field");
}
});
if(empty == false){
var that = $(this),
url = that.attr('action'),
type = that.attr('method'),
data = {};
that.find('[name]').each(function(index, value){
var that = $(this),
name = that.attr('name'),
value = that.val();
data[name] = value;
});
$.ajax({
url: url,
type: type,
data: data,
success: function(response){
window.location.replace("index.php?content=create_tutorial_successful");
}
});
}
else{
console.log("Alles ausfüllen");
}
return false;
});
$('input[type="text"]').click(function(){
$(this).removeClass("empty_field");
});
$('textarea').click(function(){
$(this).removeClass("empty_field");
});
});
I would need to see the function where you create new elements to be completely certain, but from what I see, I think you need to reapply your click listeners when you create your new elements. They're not "retroactive", meaning the "click" you add will target what's in the dom at the moment you set them, but not new elements you create afterwards.
I tried on your page through console to set the click events with the exact code you have, and it works.
So when creating new element you can probably use something like:
$(your_new_element).click(function(){
$(this).removeClass("empty_field");
});
on each element you create for which you want this behavior.
EDIT:
Something like this:
$(add_button).click(function(){ //on add input button click
if(x < max_fields){ //max input box allowed
$(wrapper).append('<div class="step"><div class="header_step">Schritt '+ x +' des Tutorial\'s</div><div class="body_step"><a class="create_tutorial_a">Titel des Schrittes</a><input name="input_title_name'+x+'" class="create_tutorial_input" type="text" /><br><a class="create_tutorial_a">Bild</a><input type="file" /><br><br><a class="create_tutorial_a_full_width">Beschreibung des Schrittes</a><br><textarea class="create_tutorial_textarea" name="input_description_name'+x+'"></textarea></div>');
x++; //text box increment
}
add_click_events();
});
function add_click_events(){
$('input[type="text"]').last().click(function(){
$(this).removeClass("empty_field");
});
$('textarea').last().click(function(){
$(this).removeClass("empty_field");
});
}
And add add_click_events() at first launch also.
I've read many blogs and posts on dynamically adding fieldsets, but they all give a very complicated answer. What I require is not that complicated.
My HTML Code:
<input type="text" name="member" value="">Number of members: (max. 10)<br />
Fill Details
So, a user will enter an integer value (I'm checking the validation using javascript) in the input field. And on clicking the Fill Details link, corresponding number of input fields will appear for him to enter. I want to achieve this using javascript.
I'm not a pro in javascript. I was thinking how can I retrieve the integer filled in by the user in input field through the link and displaying corresponding number of input fields.
You could use an onclick event handler in order to get the input value for the text field. Make sure you give the field an unique id attribute so you can refer to it safely through document.getElementById():
If you want to dynamically add elements, you should have a container where to place them. For instance, a <div id="container">. Create new elements by means of document.createElement(), and use appendChild() to append each of them to the container. You might be interested in outputting a meaningful name attribute (e.g. name="member"+i for each of the dynamically generated <input>s if they are to be submitted in a form.
Notice you could also create <br/> elements with document.createElement('br'). If you want to just output some text, you can use document.createTextNode() instead.
Also, if you want to clear the container every time it is about to be populated, you could use hasChildNodes() and removeChild() together.
<html>
<head>
<script type='text/javascript'>
function addFields(){
// Generate a dynamic number of inputs
var number = document.getElementById("member").value;
// Get the element where the inputs will be added to
var container = document.getElementById("container");
// Remove every children it had before
while (container.hasChildNodes()) {
container.removeChild(container.lastChild);
}
for (i=0;i<number;i++){
// Append a node with a random text
container.appendChild(document.createTextNode("Member " + (i+1)));
// Create an <input> element, set its type and name attributes
var input = document.createElement("input");
input.type = "text";
input.name = "member" + i;
container.appendChild(input);
// Append a line break
container.appendChild(document.createElement("br"));
}
}
</script>
</head>
<body>
<input type="text" id="member" name="member" value="">Number of members: (max. 10)<br />
Fill Details
<div id="container"/>
</body>
</html>
See a working sample in this JSFiddle.
Try this JQuery code to dynamically include form, field, and delete/remove behavior:
$(document).ready(function() {
var max_fields = 10;
var wrapper = $(".container1");
var add_button = $(".add_form_field");
var x = 1;
$(add_button).click(function(e) {
e.preventDefault();
if (x < max_fields) {
x++;
$(wrapper).append('<div><input type="text" name="mytext[]"/>Delete</div>'); //add input box
} else {
alert('You Reached the limits')
}
});
$(wrapper).on("click", ".delete", function(e) {
e.preventDefault();
$(this).parent('div').remove();
x--;
})
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="container1">
<button class="add_form_field">Add New Field
<span style="font-size:16px; font-weight:bold;">+ </span>
</button>
<div><input type="text" name="mytext[]"></div>
</div>