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".
Related
The code is supposed to randomly select from the user input to generate a random one.
The HTML includes a form where the user can input values which are saved, but I do not know how to store them in an array in javascript where the let decision is what stores them. When the user inputs an option, they press submit where the javascript appends a child with the option that was input (this is not included) In the javascript, but what is included is the random decision button, if let decision was an array, the button would randomly choose from the array.
The HTML:
let btn = document.getElementById('decide');
let output = document.getElementById('output');
const option_input_el = document.createElement('input');
option_input_el.classList.add('text');
option_input_el.type = 'text';
option_input_el.value = task;
option_input_el.setAttribute('readonly', 'readonly');
let decision = []; /*how to make array of the user inputs*/
btn.addEventListener('click', function() {
var chosen = decision[Math.floor(Math.random() * decision.length)];
output.innerHTML = chosen;
});
//this is our code for the decicon
<body>
<!--Our input of choices-->
<div id="center">
<header>
<h1 id="Title">Input Your Choices</h1>
<form id="form">
<input type="text" id="newT" placeholder="Options" />
<input type="submit" id="sumbitT" value="Add" />
</form>
</header>
</div>
<main>
<section class="option-list">
<h2 id="option">Your Options</h2>
<div id="options"></div>
</section>
<div class="container">
<button id="decide"> Let's Decide! </button>
<div id="output">DECISION</div>
</div>
</main>
your HTML code didn't work properly for what you wanted to achieve, so I had to rework it.
to make an array from user input, you can use push to the input.value to an array.
I used only two functions to do what you asked for. and what happens is simple:
1- when the user click add button, it get user's input then
2- push it into an array.
3- display it in the options div.
4- when the user click decide button, it will select a random value from the displayed array. then display it on the decision div.
var input = document.getElementById("input");
var inputArr = [];
var addBtn = document.getElementById("add-btn");
var display = document.getElementById("options-list");
var decideBtn = document.getElementById("decide-btn");
var resultDisplay = document.getElementById("random-output");
addBtn.addEventListener("click", addAnddisplay);
function addAnddisplay() {
inputArr.push(input.value);
display.textContent = inputArr;
}
decideBtn.addEventListener("click", decide);
function decide() {
var decision = inputArr[Math.floor(Math.random() * inputArr.length)];
resultDisplay.textContent = decision ;
}
<h1 id="Title">Input Your Choices</h1>
<input type="data" id="input" placeholder="Options" />
<button id="add-btn">Add</button>
<!-- <input type="submit" id="add-btn" value="Add" /> -->
<h2>Your Options</h2>
<div id="options-list"></div>
<button id="decide-btn"> Let's Decide! </button>
<div id="random-output"></div>
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>
So I have some buttons that will toggle some input text areas where I can send a message, how do I make it so when I click a button from a specific list, it only activates the button in that specific list.
I tried so many other things but I really don't know how to get this over it.
I'm kinda new to JS, I mainly do Java.
function showFeedback (list) {
var lines = "";
var counter = 0;
list.forEach(function (obiect) {
$(document).ready(function(){
$("button").click(function(){
$("#div"+ obiect.idfeedback +"").fadeToggle("slow");
});
});
counter++;
var style = "";
if(obiect.feedbackType == 1){
style = "style=\"background: green;\"";
} else if(obiect.feedbackType == 0){
style = "style=\"background: red;\"";
}
lines += `<div class="page-block"><div style="text-align: right">X</div><div class="cv-block" ${style} >
<div id="parent_div_1">
Name: ${obiect.firstn}
${obiect.lastn}
</div>
<div id="parent_div_2" style="float: right">
Date: ${obiect.date}
</div>
<div class="message_div"><p>${obiect.message}</p></div>
</div>
<button>Contact</button>
<div id="div`+ obiect.idfeedback +`" style="display: none">
<form action="contact" method="post">
<textarea name="message" id="umessage" cols="30" rows="10" maxlength="450" placeholder="Type your message here..." style="height:115px;width: 620px"></textarea>
<input type="hidden" name="email" id="umail" value="`+obiect.email+`">
<input type="hidden" name="action" value="feedback">
<div><input type="submit" value="Send Email"></div>
</form>
</div>
</div>`;
}); if(counter==0){
lines+= `<div class="page-block">No feedbacks to review.</div>`;
}
$("#obiect").html(lines);}
Get rid of $(document).ready, it is used to make sure the markup has been loaded before assigning events. In your scenario, markup is being generated dynamically, plus document.ready inside a loop does not make sense.
The simplest way to fix this code is to move the $('button') outside the loop. After the loop, do the following
$('button').click(function(){
$(this).next().fadeToggle("slow");
})
What this code does is add a handler on the click event of every button element, when the button's clicked, it finds the element which is placed next to the button element, which in your case is the required div element, and show that.
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.
I need to show a form using a button, and hide it when the user presses another button, because the other button shows another form. I did a similar thing with a select box, but I can't figure out how to do this.
Use the following code fragment to hide the form on button click.
document.getElementById("your form id").style.display="none";
And the following code to display it:
document.getElementById("your form id").style.display="block";
Or you can use the same function for both purposes:
function asd(a)
{
if(a==1)
document.getElementById("asd").style.display="none";
else
document.getElementById("asd").style.display="block";
}
And the HTML:
<form id="asd">form </form>
<button onclick="asd(1)">Hide</button>
<button onclick="asd(2)">Show</button>
There's something I bet you already heard about this! It's called jQuery.
$("#button1").click(function() {
$("#form1").show();
};
It's really easy and you can use CSS-like selectors and you can add animations. It's really easy to learn.
If you have a container and two sub containers, you can do like this
jQuery
$("#previousbutton").click(function() {
$("#form_sub_container1").show();
$("#form_sub_container2").hide(); })
$("#nextbutton").click(function() {
$("#form_container").find(":hidden").show().next();
$("#form_sub_container1").hide();
})
HTML
<div id="form_container">
<div id="form_sub_container1" style="display: block;">
</div>
<div id="form_sub_container2" style="display: none;">
</div>
</div>
There's the global attribute called hidden. But I'm green to all this and maybe there was a reason it wasn't mentioned yet?
var someCondition = true;
if (someCondition == true){
document.getElementById('hidden div').hidden = false;
}
<div id="hidden div" hidden>
stuff hidden by default
</div>
https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/hidden
Would you want the same form with different parts, showing each part accordingly with a button?
Here an example with three steps, that is, three form parts, but it is expandable to any number of form parts. The HTML characters « and » just print respectively « and » which might be interesting for the previous and next button characters.
shows_form_part(1)
/* this function shows form part [n] and hides the remaining form parts */
function shows_form_part(n){
var i = 1, p = document.getElementById("form_part"+1);
while (p !== null){
if (i === n){
p.style.display = "";
}
else{
p.style.display = "none";
}
i++;
p = document.getElementById("form_part"+i);
}
}
/* this is called at the last step using info filled during the previous steps*/
function calc_sum() {
var sum =
parseInt(document.getElementById("num1").value) +
parseInt(document.getElementById("num2").value) +
parseInt(document.getElementById("num3").value);
alert("The sum is: " + sum);
}
<div id="form_part1">
Part 1<br>
<input type="number" value="1" id="num1"><br>
<button type="button" onclick="shows_form_part(2)">»</button>
</div>
<div id="form_part2">
Part 2<br>
<input type="number" value="2" id="num2"><br>
<button type="button" onclick="shows_form_part(1)">«</button>
<button type="button" onclick="shows_form_part(3)">»</button>
</div>
<div id="form_part3">
Part 3<br>
<input type="number" value="3" id="num3"><br>
<button type="button" onclick="shows_form_part(2)">«</button>
<button type="button" onclick="calc_sum()">Sum</button>
</div>