I have been trying to follow the example here to add a dynamic field that is created upon a button click example and have been unable to get it to work.
Here is my javascript file, which I am storing in my static file directory(other static files load fine, filename is 'recipeadd.js'):
$(document).ready(function(){
var next = 1;
$("#b1").click(function(e){
alert("Hi");
e.preventDefault();
var addto = "#field" + next;
var addRemove = "#field" + (next);
next = next + 1;
var newIn = '<input autocomplete="off" class="form-control" id="field' + next + '" name="field' + next + '" type="text">';
var newInput = $(newIn);
var removeBtn = '<button id="remove' + (next - 1) + '" class="btn btn- danger remove-me" >-</button></div><div id="field">';
var removeButton = $(removeBtn);
$(addto).after(newInput);
$(addRemove).after(removeButton);
$("#field" + next).attr('data-source',$(addto).attr('data-source'));
$("#count").val(next);
$("#remove").click(function(e){
e.preventDefault();
var fieldNum = this.id.charAt(this.id.length-1);
var fieldID = "#field" + fieldNum;
$(this).remove();
$(fieldID).remove();
});
});
});
Here is what's in my html header, loading both the js and associated css file:
<!--CSS code for recipeadd-->
<link href="{% static 'recipes/css/recipeadd.css' %}" rel="stylesheet">
<!--JS code for reccipeadd-->
<script src="{% static 'recipes/js/recipeadd.js' %}"></script>
Finally, here is the container that contains button 'b1', which I'm trying to have execute the javascript:
<div class="container">
<div class="form-group">
<!--div class="col-xs-4"-->
<label for="recipeName">Recipe Name</label>
<input type="text" class="form-control" id="recipeName">
</div>
<div class="form-group">
<input type="hidden" name="count" value="1" />
<div class="control-group" id="fields">
<label class="control-label" for="field1">Ingredients</label>
<div class="controls" id="profs">
<form class="input-append">
<div id="field"><input autocomplete="off" class="form-control" id="field1" name="prof1" type="text" placeholder="Enter one ingredient per line" data-items="8"/><button id="b1" class="btn add-more" type="button">+</button></div>
</form>
</div>
</div>
</div>
<div class="form-group">
<label for="directions">Directions</label>
<textarea class="form-control" rows="5" id="directions"></textarea>
</div>
I am teaching myself web development and using the Django framework for this project. Sincerely appreciate any help on this.
First I am assuming you have jQuery on the page, your code is not showing a jQuery reference.
Now assuming that the code adds the elements, I see one issue with adding your click event. You give the remove button the id with a number: id="remove' + (next - 1) + '"
Now when you attach the event, you do not use a number: $("#remove").click(
So either you need to use a number OR better yet, you already have the button element referenced, use that.
removeButton.click( function(){ });
Well as I mentioned I am just learning. I did not have a jQuery reference in my html file. I assumed as long as I had the javascript file reference that was good enough. I downloaded jQuery and added the following reference, working now - thank you!
<!--jQuery core code-->
<script src="{% static 'recipes/js/jquery-3.1.0.min.js' %}"></script>
Related
I try to make a dynamic input form group to add extra rows.
Adding rows in the input group works!
Now I would like to send a variable back with the number of rows.
I have a working for loop that counts the rows. But the variable stays the same.
$(document).ready(function(){
var max_fields = 16;
var add_input_button = $('.add_input_button');
var field_wrapper = $('.field_wrapper');
var input_count = 4;
var new_field_html = // html code with input_count(works but stays on 4)
// Add button dynamically
$(add_input_button).click(function(){
if(input_count < max_fields){
input_count++;
console.log(input_count);
$(field_wrapper).append(new_field_html);
}
});
I can see in my console log the correct loop!
How can I change the code to update the input_count on return value?
screenshot of the problem
You should move this line within the click event, as this line gets called only once on page load. So to use the input_count incremented value within the new field, it should also be formed every time the click is performed.
var new_field_html = // html code with input_count(works but stays on 4)
Here I have designed a rough page what you are trying to achieve, please read out the comments to understand.
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>The HTML5 Herald</title>
</head>
<body>
<form>
<div class="field_wrapper">
<div class="form-group">
<label for="exampleInputEmail1">Email address</label>
<input type="email" class="form-control" id="exampleInputEmail1" aria-describedby="emailHelp" placeholder="Enter email">
<small id="emailHelp" class="form-text text-muted">We'll never share your email with anyone else.</small>
</div>
<button type="button" class="btn btn-primary add_input_button">Submit</button>
</div>
</form>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
var max_fields = 16;
var add_input_button = $('.add_input_button');
var field_wrapper = $('.field_wrapper');
var input_count = 4;
// html code with input_count(works but stays on 4)
console.log("Outside ======> " + input_count); // Executes only on page load
// Add button dynamically
$(add_input_button).click(function(){
if(input_count < max_fields){
input_count++;
var new_field_html = '<div class="form-group"><button type="button" class="btn btn-primary" class="add_input_button">Submit-' + input_count + '</button></div>';
$(field_wrapper).append(new_field_html);
console.log("Inside ======> " + input_count); // Executed everytime the button is clicked
}
});
console.log("Outside-2 ======> " + input_count); // Executed only on page load
});
</script>
</body>
</html>
I have a code (down below) that has a text-box and a comment section. I also have a button where it's supposed to add that comment. I don't know the code that will post the comment below the comment section. This is my code:
<div id="comments">
<fieldset><legend>Post Your Comments!</legend>
Name: <input type="textbox" name="name"><br><br>
</fieldset><br>
<textarea rows="10" cols="30" placeholder="Your Comments!"></textarea>
<button>Add!</button>
I'm sure you'll want to do some kind of server-side saving of the comments, but the code below answers your question by adding the elements to the DOM. You'll see some changes to your code, including some IDs and proper closing of input and br tags.
HTML:
<div id="comments">
<fieldset>
<legend>Post Your Comments!</legend>Name:
<input type="textbox" id="txtName" name="name" />
<br />
<br />
</fieldset>
<br />
<textarea id="txtComments" rows="10" cols="30" placeholder="Your Comments!"></textarea>
<button id="btnAdd">Add!</button>
</div>
<div id="postedComments"></div>
JavaScript:
$(document).ready(function () {
$('#btnAdd').on('click', function (event) {
event.preventDefault();
// Create new HTML string containing name & comment
var newComment = '<hr /><div class="name">' + $('#txtName').val() + '</div>' +
'<div class="comment">' + $('#txtComments').val() + '</div>';
// This creates a new jQuery object containing newComment
// and appends it to the posted comments section
$(newComment).appendTo('#postedComments');
// Clear input
$('#txtComments').val('');
$('#txtName').val('');
});
});
Demo: http://jsfiddle.net/BenjaminRay/85k8y6eo/
If you want to post the comments to the server and only add them to the DOM after they have been saved on the server, look into jQuery's post() (or other similar AJAX functions). https://api.jquery.com/jquery.post/
Something along these lines (in pure JavaScript):
window.onload = function() {
var addButton = document.getElementById("add");
addButton.addEventListener("click", addComment);
var theDiv = document.getElementById("comments");
function addComment() {
var name = document.getElementById("name").value;
var comments = document.getElementById("post").value;
var newPara = document.createElement("P");
newPara.innerHTML = "<u>" + name + "</u><br/>" + comments;
theDiv.appendChild(newPara);
}
};
<div id="comments">
<h3>Post Your Comments!</h3>
Name:
<input type="textbox" name="name" id="name">
<br/>
<br/>
<textarea id="post" rows="10" cols="30" placeholder="Your Comments!"></textarea>
<br/>
<button id="add">Add!</button>
</div>
I am trying to create clones of a HTML div. The div has a label and two text boxes inside it. I need to change the label value of the newly created div. Here is my code.
<body>
<div id="PayDiv2">
<label id="PayLbl2">Payment No 2: </label>
<input type="text" />
<input type="text" />
</div>
<div id ="totPayForm" >
<label id="totPayLbl">Total Payment: </label>
<input type="text" />
<input type="text" />
<input type="submit" value="Add new one" onclick="addNewField();
return false;">
</div>
<input type="button" value="Clone box" id="btn" />
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script>
var i=3;
//When DOM loaded we attach click event to button
$(document).ready(function() {
$('#btn').click(function() {
var cloned = $('#PayDiv2').clone();
cloned.insertBefore("#totPayForm");
$('#PayLbl2').html("Payment No "+ i++ + ':');
});
});
</script>
</body>
The problem is the place the newly created clones placed. First clone get placed before everything(even though I need to place it after the original div which I used to create divs. )
divs generated after that also get placed at first and, early divs goes down. It is hard to describe here. If you can be kind enough to run my code you will see what the issue is.
I have an another requirement to generate unique ids to cloned divs. Since I am new in JQuery, I found it difficult to generate id's.
I am pleased if you can help me in this case. Thank you all.
The problem is $('#PayLbl2').html("Payment No "+ i++ + ':'); it always changes the first element's label instead of the clone(because of the duplicated ids)...
so use class instead of id
<div class="PayDiv2">
<label class="PayLbl2">Payment No 2:</label>
<input type="text" />
<input type="text" />
</div>
then
var i = 3;
//When DOM loaded we attach click event to button
$(document).ready(function () {
$('#btn').click(function () {
var cloned = $('.PayDiv2').first().clone();
cloned.insertBefore("#totPayForm");
cloned.find('.PayLbl2').html("Payment No " + i+++':');
});
});
Demo: Fiddle
Here it is.
Demo
Make your HTML like below
<div id="PayDiv0" class="PayDiv0">
<label id="PayLbl0" class="PayLbl2">Payment No 2:</label>
<input type="text" />
<input type="text" />
</div>
<div id="totPayForm">
<label id="totPayLbl">Total Payment:</label>
<input type="text" />
<input type="text" />
<input type="submit" value="Add new one" onclick="addNewField();
return false;">
</div>
<input type="button" value="Clone box" id="btn" />
And JS should be like this
var i = 3;
$(document).ready(function () {
$('#btn').click(function () {
var cloned = $('.PayDiv0').first().clone();
var noOfDivs = $('.PayDiv0').length;
cloned.insertBefore("#totPayForm");
cloned.attr('id', 'PayDiv' + noOfDivs);
cloned.find('label').attr('id', 'PayLbl' + noOfDivs);
cloned.find('.PayLbl2').html("Payment No " + i+++':');
});
});
As mentioned in the answer by #Arun P Johny, set the div id PayDiv0
$('#btn').click(function () {
var cloned = $('.PayDiv2').first().clone();
// find total divs with class PayDiv2
var noOfDivs = $('.PayDiv2').length;
cloned.insertBefore("#totPayForm");
// add new id to the cloned div
cloned.attr('id', 'PayDiv' + noOfDivs);
// find the label element inside new div and add the new id to it
cloned.find('label').attr('id', 'PayLbl' + noOfDivs);
cloned.find('.PayLbl2').html("Payment No " + i+++':');
});
this way you can add the dynamic ids to your elements.
The idea behind this small project of mine is to have an user enter an URL for an img, when the user hits a button the img should then be inserted into a new <div> within the page.
I tried looking for hours at stackoverflow but I honestly don't understand how I can use other answers to my own code. Most of the CSS and HTML code is already done, I just need help with the javascript part if its possible at all.
Here is what I have so far:
HTML code:
<form name="imgForm">
enter URL:
<input type="text" name="inputbox1" value="src" />
<input type="button" value="Get Feed" onclick="GetFeed()" />
</form>
Javascript code:
<script type="text/javascript">
function GetFeed(imgForm) {
var imgSrc = document.getElementById("src").value;
}
</script>
Can anyone help me out? I dont know where to go from here.. at least give me some pointers how can i get the value from the txt box and add a new
<div><img src="user input from txt box should go here"/></div> for every time an unser inserts and new URL for an img?
I think according to your need how can i get the value from the txt box and add a new <div><img src="user input from txt box should go here"/></div> you need this
HTML
<form>
<input type="text" id="txt">
<input id="btn" type="button" value="Get Image" onclick="getImg();" />
</form>
<div id="images"></div>
JS (goes inside your head tags)
function getImg(){
var url=document.getElementById('txt').value;
var div=document.createElement('div');
var img=document.createElement('img');
img.src=url;
div.appendChild(img);
document.getElementById('images').appendChild(div);
return false;
}
Here is an example.
You should add an id attribute to your <input>:
<input type="text" name="inputbox1" id="box1" value="src" />
...then, adjust your code:
var imgSrc = document.getElementById('box1').value;
Once you have the source, you can get back an object for the img tag, and set its properties using the value from the text box. The img object's properties are defined by the Document Object Model:
http://www.w3schools.com/jsref/dom_obj_image.asp
Something like this will create a div with an image element that has a src equal to the text in the input box. It then appends the div to end of the page.
<html>
<head>
<script type="text/javascript">
function GetFeed(form){
var imgSrc = form.elements["inputbox1"].value;
var imgDiv = document.createElement('div');
imgDiv.innerHTML = "<img src=\"" + imgSrc + "\"/>"
document.body.appendChild(imgDiv);
}
</script>
</head>
<body>
<form name="imgForm">
enter URL:
<input type="text" name="inputbox1" value="src" />
<input type="button" value="Get Feed" onclick="GetFeed(this.form)"/>
</form>
</body>
</html>
your codes better should be like this:
html Codes:
<div class="input-group col-md-5" style="margin: 0px auto;">
<div class="input-group-append">
<button class="btn btn-outline-secondary" type="button" id="button-image">
Choose
</button>
</div>
<input type="text" id="image_label" class="form-control" name="image" aria-abel="Image" aria-describedby="button-image" onclick="getImg()">
</div>
<div id="image-holder">
<img id="imgThumb" class="img-thumbnail" src="{{Your Image Source}}" alt="">
</div>
js Codes:
function getImg(){
var url = document.getElementById('image_label').value;
var img = document.getElementById('imgThumb');
img.src = url;
return true;
}
I am a beginner, so keep that in mind.
so what I currently have working is my form successfully adds another input to the form, however it appears out of the form div. Basically I want it to appear within the div and above the submit button.
how do I do this?
here is main appendTo in my javascript:
var i = $('input').size() + 1;
$('a#add').click(function() {
$('<input type="text" value="user' + i + '" />').appendTo('form');
i++;
});
here is the form html as on request.
<div id="stylized" class="myform">
<form name="addstudents" method="post" action="add_students.php">
<div id="formHeader">
<h1>Add student(s)</h1>
<p>Please enter student's HEMIS number</p>
</div>
<label>Student: <span class="small">Enter HEMIS number</span> </label>
<input type='text' name="user_1">
<input type="submit" class="Mybutton" id="mybutton" name="submit" value='Submit Student(s)'>
<div class="spacer"></div>
</form>
AddRemove</div>
Any help would be greatly appreciated.
thanks
NEW PROBLEM: REMOVING!
here is my current remove JS, it simply removes the submit button first :(
$('a#remove').click(function() {
if(i > 3) {
$('input:last').remove();
i--;
}
});
$('a.reset').click(function() {
while(i > 2) {
$('input:last').remove();
i--;
}
});
Thanks again
You can use this snippet to insert the input before the button:
$('form #idofsubmitbutton').before($('<input type="text" value="user' + i + '" />'))
EDIT:
I played around with jsfiddle.com after your last edit and came upp with this:
var i = $('input').size() + 1;
$('a#add').click(function() {
$('div#stylized form input:submit').before($('<input type="text" value="user' + i + '" />'))
i++;
});
With the example html you posted this works. When I press the add link new inputs appear before the submit button.
If you still got problems you might have elements with duplicate ids.
var i = $('input').size() + 1;
$('a#add').click(function() {
$('<input type="text" value="user' + i + '" />').appendTo('div#divId');
i++;
});
This is not a "PHP form", once it's on the client, it's just HTML/CSS/Javascript. PHP is on the server.
.appendTo('form'); appends to the form TAG, not a "form div". If you have a DIV named "form" you need to use .appendTo('#form');