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>
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
});
});
So the problem is this:
I try to get the text that is inside a specific paragraph with a specific id name and pass it inside a contact form .
i tried this
var src = document.getElementById("ptext"),
dest = document.getElementById("inform");
src.addEventListener('input', function() {
dest.value = src.value;
}};
Where "ptext" is the id of the element with the text of the paragraph and the "inform" is the id of the field in contact form.
The above code will trigger when the user clicks a button.
I am new in Javascript so the code above is probably wrong or faulty.
UPDATE: The HTML Code is this :
<p id="pext">Hello this is the text that is to be imported inside the form field</p>
form field:
<input type="text" name="your-subject" value="" size="40" id="inform" aria-required="true" aria-invalid="false" placeholder="Subjext">
I'm not sure if this is what you were trying to do, but if you're trying to get the text of a paragraph into a form field on a button click (useful a lot of the time with hidden form fields), then here is a code snippet to help you:
var src = document.getElementById("ptext");
var dest = document.getElementById("inform");
var getText = function () {
dest.value = src.innerText;
event.preventDefault();
return false;
}
<p id="ptext">This is some fake text that we'll put into the form.</p>
<form onsubmit="getText()">
<label for="text">Info from paragraph:</label><br>
<input type="text" id="inform" name="text"><br><br>
<input type="submit" >
</form>
Hello and welcome to Stack Overflow :)
To get the text that is inside specific paragraph, use
var src = document.getElementById("ptext").innerText;
To assign the value to an input field (which is what I'm assuming you are trying to do), use
document.getElementById("inform").value = src;
If you supply us with HTML element we could be even more precise.
I have a form where users can create recipes. I start them off with one ingredient field (among others) and then use .append() to add as many more as they want to the div container that holds the first ingredient. The first input field has an id of IngredientName1 and dynamically added input fields are IngredientName2, IngredientName3, etc.
When they start typing in the input field, I pop a list of available ingredients filtered by the value they key into IngredientNameX. When they click on an ingredient in the list, it sets the value of the IngredientNameX field to the text from the div - like a search & click to complete thing. This all works very well; however, when you add IngredientName2 (or any beyond the one I started them with initially) clicking on an available ingredient sets the values of every single IngredientNameX field. No matter how many there are.
I hope this is enough context without being overly verbose, here's my code (I've removed a lot that is not relevant for the purpose of posting, hoping I didn't remove too much):
<div id="ingredientsContainer">
<input type="hidden" id="ingredientCounter" value="1">
<div class="ingredientsRowContainer">
<div class="ingredientsInputContainer"><input class="effect-1 ingredientsInput" type="text" name="IngredientName1" placeholder="Ingredient" id="IngredientName1" data-ingID="1"><span class="focus-border"></span></div>
</div>
<input type="hidden" name="Ingredient1ID" id="Ingredient1ID">
</div>
<script>
$(document).ready(function(){
$(document).on('keyup', "[id^=IngredientName]",function () {
var value = $(this).val().toLowerCase();
var searchValue = $(this).val();
var valueLength = value.length;
if(valueLength>1){
var theIngredient = $(this).attr("data-ingID");
$("#Ingredients").removeClass("hidden")
var $results = $('#Ingredients').children().filter(function() {
return $(this).text() === searchValue;
});
//user selected an ingredient from the list
$(".ingredientsValues").click(function(){
console.log("theIngredient: "+theIngredient);//LOGS THE CORRECT NUMBER
var selectedIngredientID = $(this).attr("id");
var selectedIngredientText = $(this).text();
$("#IngredientName"+String(theIngredient)).val(selectedIngredientText);//THIS IS WHAT SETS EVERYTHING WITH AN ID OF IngredientNameX
$("#Ingredient"+String(theIngredient)+"ID").val(selectedIngredientID);
$("#Ingredients").addClass("hidden");
});
$("#Ingredients *").filter(function() {
$(this).toggle($(this).text().toLowerCase().indexOf(value) > -1)
});
} else {
$("#Ingredients").addClass("hidden")
}
});
$("#AddIngredient").click(function(){
var ingredientCounter = $("#ingredientCounter").val();
ingredientCounter++;
$("#ingredientCounter").val(ingredientCounter);
$('#ingredientsContainer').append('\
<div class="ingredientsRowContainer">\
<div class="ingredientsInputContainer"><input class="effect-1 ingredientsInput" type="text" name="IngredientName'+ingredientCounter+'" placeholder="Ingredient" id="IngredientName'+ingredientCounter+'" data-ingID="'+ingredientCounter+'"><span class="focus-border"></span></div>\
</div>\
<input type="hidden" name="Ingredient'+ingredientCounter+'ID" id="Ingredient'+ingredientCounter+'ID">\
');
});
});
</script>
[UPDATE] I realized the problem is happening because the function is running multiple times. I assume this happening because I'm calling a function on keyup of a field whose id starts with IngredientName so when one has a key up event, all existing fields run the function. How do i modify my:
$(document).on('keyup', "[id^=IngredientName]",function () {
to only run on the field with focus?
The mandatory div id gets different numbers of inputs field displayed in it dynamically. Each input field starting from the first gets an id attr1, then attr2,..attr[n]. I need a way to get this into an array that gets the value of each input field with keyup and puts them into a separate input field with id detail.
This code works but returns undefined in some case when the hard coded input field ids exceed the generated input field ids. Thanks.
<div id="attributes"> <!--Start of Div Refreshed on Ajax Page Refresh-->
<div id="mandatory">
</div>
</div>
var total = '#attr1, #attr2';
$("#attributes").on('keyup', total, function(){
update();
})
function update() {
$("#detail").val($('#attr1').val() + "," $('#attr2').val());
}
If I understood right your question I think you're looking for something like that:
var fields = $("#mandatory").find("input"),
ids = [];
fields.each(function(){
$(this).on("keyup", function(){
var val = "";
ids = [];
fields.each(function(){
val += $(this).val() + (fields.length === ($(this).index() + 1) ? "": ", ");
ids.push($(this).get(0).id);
});
$("#detail").val(val);
console.log(ids)
});
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="attributes">
<div id="mandatory">
<input id="one" class="one" value="54"/>
<input id="two" class="two" value="55"/>
<input id="three" class="three" value="587"/>
</div>
</div>
<input id="detail" type="text" />
I'm not sure if this is what you're looking for, but I think it'll take you down the right path. In this example, any time a text input field is generated, an input event handler is attached to it that changes the value of a main textarea. If this isn't quite what you're looking for, please let me know and I'll be happy to try to work it out more.
document.getElementById('adder').onclick = function() {
var dynamicTextbox = document.createElement('input');
dynamicTextbox.setAttribute('type', 'text');
dynamicTextbox.setAttribute('class', 'dynamicText');
dynamicTextbox.addEventListener("input", function() {
var allTextboxes = document.getElementsByClassName('dynamicText');
var allValues = '';
for (var i=0; i < allTextboxes.length; i++) {
allValues += allTextboxes[i].value;
}
document.getElementById('detail').value = allValues;
});
document.getElementById('textboxes').appendChild(dynamicTextbox);
}
<textarea id="detail"></textarea>
<input id="adder" type="button" value="Add Text Field" />
<div id="textboxes"></div>