I'd like to add a form field to the template when the user clicks on a button via javascript. I don't want to hide it and just make it appear, I need to insert it because it can be loaded into multiple parts. This is what I've tried but no luck.
document.getElementById("div_id").value = '{{ my_form.field|as_crispy_field }}';
Here is an example:
// update element innerHTML with input field
function addField2(e) {
e.preventDefault();
var container = document.getElementById("field_2_container");
var input = `
<div class="some_class">
<input type="text" name="field_2" id="id_field_2">
</div>
`;
// append input field to the element
container.innerHTML += input;
}
<form id="form">
<div id="field_1_container">
<input type="text" name="field_1" id="id_field_1">
</div>
<div id="field_2_container"></div>
<div id="field_3_container"></div>
<button onclick="addField2(event)">Add field 2</button>
</form>
Related
I'm trying to make a table in Javascript that does not use a table element, and I'm using pure vanilla nodeJS. I can get a new row to show up very briefly, but it disappears when I hit the button that made it show up in the first place. My code is:
<!DOCTYPE html>
<html>
<body>
<h1> Title Tests </h1>
<div id="Experiments">
<form id="Exp">
<input type="text" name="url box" placeholder="publisher URL"><br>
<div class="Title">
<input type="text" name="title box" placeholder="Test Title"><br>
</div>
<button id="addButton" onclick="newRow()">+</button><br>
<input type=submit value="Submit">
</form>
</div>
<script>
function newRow(){
var number = 2;
var newTitleRow = document.createElement('div');
newTitleRow.setAttribute('id',`Title${number}`);
var newBT = document.createElement('input');
newBT.setAttribute('type','text');
newBT.setAttribute('name',`title box ${number}`);
newBT.setAttribute('placeholder','Test Title');
newTitleRow.appendChild(newBT)
var button = document.querySelector("#addButton");
button.before(newTitleRow);
number++;
}
</script>
</body>
</html>
The problem is that you're using a html <button> inside a <form> element. This means it will automatically act as a submit button unless you declare it to be something different. So as soon as you push the + button it will try to submit the form to an undefined URL.
To work around you need to define that + button to be of type "button" like:
<button type="button" id="addButton" onclick="newRow()">+</button><br>
I'm not really sure the best way to go about this but I've laid the framework.
Basically, I would like to add the functionality so that when my #moreItems_add button is clicked and calls the moreItems function, I simply want to add a new Input field below it, and so on. I want to limit this to 10 fields though, so I show that in the function.
The only trick is, I will be submitting all fields via ajax to save to the database, so I need to try and keep track of an ID with each.
What's the best way to continue the javascript here so that I can append an input field on button press and keep track of IDs for each?
<div class="modal-body">
<form id="Items">
<label id="ItemLabel">Item 1:</label>
<input type="text" name="Items[]">
<button id="moreItems_add" onclick="moreItems()" id="moreItems">More Items</button>
</form>
</div>
<div class="modal-footer">
<input type="submit" name="saveItems" value="Save Items">
</div>
<!-- modal JS -->
<script type="text/javascript">
function moreItems(){
var MaxItems = 10;
//If less than 10, add another input field
}
</script>
You can use the jQuery .insertBefore() method to insert elements right before "more items" button. Below is the code representing this:
var maxItems = 1;
function moreItems() {
if (maxItems < 10) {
var label = document.createElement("label");
label.id="ItemLabel"+maxItems;
label.innerHTML = "Item "+(maxItems+1)+": ";
var input = document.createElement("input");
input.type='text';
input.name = 'item'+maxItems;
$('<br/>').insertBefore("#moreItems_add");
$(label).insertBefore("#moreItems_add");
$(input).insertBefore("#moreItems_add");
maxItems++;
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="modal-body">
<form id="Items">
<label id="ItemLabel">Item 1:</label>
<input type="text" name="Items[]">
<button type="button" id="moreItems_add" onclick="moreItems()" id="moreItems">More Items</button>
</form>
</div>
<div class="modal-footer">
<input type="submit" name="saveItems" value="Save Items">
</div>
Something like this should do the trick:
<!-- modal JS -->
<script type="text/javascript">
var MAX_ITEMS = 10,
added = 0;
function moreItems(){
if (added >= MAX_ITEMS) return;
var newField = document.createElement('input');
newField.type = 'text';
// TODO: Any field setup.
document.getElementById('items').appendChild(newField);
added++;
}
</script>
In terms of tracking each field with an ID, that should always be done by the back-end for data integrity and safety reasons.
some years ago I've wrote an article about making a repeated section using jQuery.
The live example is available on jsFiddle.
In the example you can find that both "add" and "remove" button are available, however you can set just the "add" button for your purpose.
The idea to limit to specific number of repeated boxes is to watch the number of repeatable elements just created in the context. The part of code to change in the live example is rows 13-18:
// Cloning the container with events
var clonedSection = $(theContainer).clone(true);
// And appending it just after the current container
$(clonedSection).insertAfter(theContainer);
There you should check if the number of repeated elements is less than <your desired number> then you will allow the item to be created, else you can do something else (like notice the user about limit reached).
Try this:
const maxItens = 10,
let itensCount = 0;
function moreItems() {
if (itensCount++ >= maxItens) {
return false;
}
let newInput = document.createElement('input');
// use the iterator to make an unique id and name (to submit multiples)
newInput.id = `Items[${itensCount}]`;
newInput.name = `Items[${itensCount}]`;
document.getElementById('items').appendChild(newInput);
return false;
}
Add type "button" to stop submiting the page (also, your button have two ID):
<button id="moreItems_add" onclick="moreItems();" type="button">More Items</button>
The submit button must be inside the form to work:
<form>
<div class="modal-body">
<div id="Items">
<label id="ItemLabel">Item 1:</label>
<input type="text" name="Items[]">
</div>
<button id="moreItems_add" onclick="moreItems()" id="moreItems">More Items</button>
</div>
<div class="modal-footer">
<button type="submit">Save Items</button>
</div>
</form>
To append itens in sequence the button must be outside of div "itens".
How to add multiple contact numbers within a single textbox and also a X(clear) button for each of the text added using javascript?
Below is a part of my HTML page
Contact No:<input type="text" id="no"><input type="button" value="ADD" id="add" onclick="javascript:addContact();">
<input type="text" id="text_name" style="width: 300px;height:50px;" />
Here is my javascript function
function addContact(){
var temp = document.createElement("input");
temp.innerHTML="<input type='search' value='' alt='clear' >";
var contact_added=document.getElementById("text_name").value;
var contact=document.getElementById("no").value;
document.getElementById("text_name").value=contact+temp+contact_added;
}
This is what I get as my output
![My output]
However what I need is that for every text that I enter,it should be follow by a clear so that I can clear that selected block of text
function addContact(){
temp="<input type='search' value=''. alt='clear' >";
var contact_added=document.getElementById("text_name").value;
var contact=document.getElementById("no").value;
document.getElementById("text_name").value=contact+temp+contact_added;
}
However this doesnt solve your problem. I think it isnt a good idea, doing this with inputs and buttons. This only makes it complicated.
At first make a form with a hidden field:
<form action="submit.php" method="post">
<input name="contacts" id="contacts_hidden" style="display:none">
</form>
<div id="contacts">
</div>
//your submit button and input
Now you can do:
contacts=[];
function addContact(){
newcontact=document.getElementById("no");
contacts.push(newcontact.value);
newcontact.value="";
render();
}
function delete(i){
contacts.splice(i,1);
render();
}
//this takes the contacts array and adds it to the page + hidden submit field
function render(){
hidden=document.getElementById("contacts_hidden");
all=document.getElementById("contacts");
content="";
for(i=0;i<contacts.length;i++){
//add a delete button
content+=contacts[i]+"<a href='javascript:delete("+i+")'>Delete</a>";
}
all.innerHTML=content;
hidden.value=contacts.join(";");
}
I have a simple html form where I input a title and description and hit submit. At the top of the page are some paragraphs of text that I often copy and paste into these fields. It's a repetitive task, and the paragraphs are generated dynamically with php.
Can I put a button or link at the end of each paragraph or div that would fill in my form input fields with a script? Then all I would have to do is hit submit. I'm already using jquery on the page too.
EDIT:
<p>Sentence one. Longer than this</p><!--would like a button here to populate field in form below-->
<p>Sentence two. Longer than this</p>
<p>Sentence three. Longer than this</p>
<form id="sampleform" action="actionpage.php" method="post">
Title<input type="text" name="title>
Desc<input type="text" name="title>
<input type="submit" value="Submit"></form>
If you have some selector that can select all of the <p> tags that contain those paragraphs, you can do something like the following:
$(function() {
var $descInput = $('input[name=desc]');
// wrap the text of each paragraph in a span so we can target it easily.
// Then add a button inside each <p> at the end that will prepopulate that text.
$('p.prefill').wrapInner('<span class="text"></span>').append('<button class="prefill-sentence">Prefill</button>');
// Add a click handler for all the newly added buttons
$('button.prefill-sentence').click(function() {
// get the contents of the span we used to wrap the sentence with
var sentence = $(this).prev('.text').text();
// add that sentence to the current value of the description input
$descInput.val($descInput.val() + sentence);
});
});
.prefill-sentence {
margin-left: 20px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p class="prefill">Sentence one. Longer than this</p>
<p class="prefill">Sentence two. Longer than this</p>
<p class="prefill">Sentence three. Longer than this</p>
<form id="sampleform" action="actionpage.php" method="post">
Title
<input type="text" name="title" />Desc
<input type="text" name="desc" />
<input type="submit" value="Submit" />
</form>
(Note I assumed you had a name of "desc" for your description input. Ideally, you can use a class or id to target it easier in the real code).
Is this what you are looking for?
http://plnkr.co/edit/S3OegSh80UH6oQJPDatr?p=preview
$(function(){
$('p').each(function(){
$(this).after('<button>Click<\/button>');
});
$('button').on('click', function(){
var txt = $(this).prev().text();
$('input').eq(0).val(txt);
})
});
You'll probably want to add something more specific to those php-generated paragraphs/divs, so they can safely be selected and manipulated by JS.
CodePen: http://codepen.io/anon/pen/PwJwmO
HTML
<div class="text-section">
Sentence one. Longer than this
</div>
<div class="text-section">
Sentence two. Longer than this
</div>
<div class="text-section">
Sentence three. Longer than this
</div>
<form id="sampleform" action="actionpage.php" method="post">
Title<input type="text" name="title">
Desc<input type="text" name="desc">
<input type="submit" value="Submit">
</form>
JS
var $text_section = $('.text-section');
var $description_field = $('input[name="desc"]');
$text_section.each(function(){
var section_text = $(this).text();
var $autofill_button = $('<button>Autofill</button>');
$autofill_button.click(function(){
$description_field.val(section_text);
});
$(this).append($autofill_button);
});
Hi all I have a form in which I dynamically add in a new row consisting of a text box and check button on button press. However I need some sort of way to know which checkbuttons were pressed in the post data and therefore need a value field consisting of an ID on each of the the check buttons, code is seen below:
<div id='1'>
<div class="template">
<div>
<label class="right inline">Response:</label>
</div>
<div>
<input type="text" name="responseText[]" value="" maxlength="400" />
</div>
<div>
<input type="radio" name="responseRadio[]" value="" />
</div>
</div>
<div>
<input type="button" name="addNewRow" value="Add Row" />
</div>
</div>
JS to add new row:
var $template = $('.template');
$('input[type=button]').click(function() {
$template.clone().insertAfter($template);
});
can anyone suggest a good way to help me know in the post data which text field, links to which check button, and to know if it was pressed?
at the moment if you were to add 3 rows and check row 3 I have no way of identifying that row three was the button pressed - This is my issue
after you cloned it, change the name so you know about this input
also it's good to have a counter for naming:
like : 'somename[myInput' + counter + ']'
update:
var counter = 0;
var $template = $('.template');
$('input[type=button]').click(function() {
counter++;
$template.clone().attr('name' , 'somename[myInput' + counter + ']').insertAfter($template);
});
now you have array named:somename which you can have a loop over its content on your form handler.