Dynamic javascript form - javascript

I have a simple form as follows so a user can type the name of a question:
<input type="text" id="question_name" name="question_name" value="">Question Name: <br />
Add Another
<div id="container"/>
<input id="go" name="btnSubmit" type="submit" value="Submit" class="btn" />
I am wanting to create a Javascript function (addNewQuestion()) which allows a user to add another question dynamically by clicking the "Add Another" link. All the text boxes with the questions should be displayed on the screen.
I understand that it is using getElementById and most likely a for loop but I keep hitting a brick wall. Can anyone show me a simple solution please?

There are many ways to do this. Here's a simple example in plain JavaScript. Note that you will either want to avoid using ids so they aren't duplicated in the DOM, or you will want to dynamically name them.
function addNewQuestion() {
var container = document.getElementById("questions");
var question = document.querySelector(".question");
container.appendChild(question.cloneNode(true));
return false;
}
.question { display: block }
<div id="questions">
<label class="question">
Question Name:
<input type="text" value="" />
</label>
</div>
Add Another

Related

html onclick keeps redirecting to a function of javascript

Im calling a function from onclick of a button. When i press the button it executes my function deletes everything from the screen and displays the button inside my function. Everything works ok but why does it delete everything from screen. How to make it for it to only run the function but keep previous html elements prior to clicking the function?
<div id="form-container">
<form id="dim_form" action="">
<div class="bg">
<label class="form-label-a" for="dimm">Dimension</label>
<input id="dimm" type="text" />
</div>
<div class="bg">
<label class="form-label-b" for="dimm_upper">Upper tolerance</label>
<input id="dimm_upper" type="text" required />
</div>
<div class="bg">
<label class="form-label-c" for="dimm_lower">Lower tolerence</label>
<input id="dimm_lower" type="text" required />
</div>
<div class="bg">
<input class="form-button" type="submit" onclick="data_table();" value="Calculate" />
</div>
</form>
</div>
data_table()
document.write("<input class='download' type='button' id='button-a' value='download xls' />");
I tried with "button" instead of submit. return false, basically everything i found on google and nothing works for me.
The write() method is mostly used for testing: If it is used after an HTML document is fully loaded, it will delete all existing HTML.
When this method is not used for testing, it is often used to write some text to an output stream opened by the document.open() method. See "More Examples" below
see the full documentation here: https://www.w3schools.com/jsref/met_doc_write.asp
if you want to add some nodes without cleaning the whole HTML try append
https://developer.mozilla.org/en-US/docs/Web/API/ParentNode/append
document.write will erase everything you had earlier. Instead use append.
function data_table() {
const input = document.createElement('input');
input.type = "submit";
input.id = "button-a";
input.value = "download xls";
document.querySelector('.bg').appendChild(input);
}
<div class="bg">
<input class="form-button" type="submit" onclick="data_table();" value="Calculate" />
</div>
Document is referred to the entire html page when you are trying to do document.write it will write on the entire page....
There can be couple of work arounds but i will suggest this one
Give class to the element you want to add element to.
Get element by the class you assign to the element in first step
var x = document.getElementsByClassName("example");
if you want to keep whats already there
x.appendChild("whatever you want to add goes here");
if you want to add only new element and discard everything previously present
x.innerHtml="whatever you want to add goes here";

How can I use the same fields for two different forms?

I'm trying to combine the login and register forms on a WooCommerce/WordPress site. The idea is that a single set of fields, username and password, could be submitted by two different forms. The first way I thought of is (simplified for clarity):
<form id="login">
<input id="username">
<input id="password">
<button type="submit">LOG IN</button>
</form>
<form id="register">
<div style="visibility:hidden!important;position:fixed!important;">
<input id="register_username">
<input id="register_password">
</div>
<button type="submit">REGISTER</button>
</form>
Basically, the layout hides the second pair of inputs but shows both buttons. Then, there's some JS that mirrors the values of corresponding fields:
var u = $('#username');
var p = $('#password');
var ru = $('#register_username');
var rp = $('#register_password')
$('#login').on('change blur focus click keyup',function(){
ru.val(u.val());
rp.val(p.val());
});
This seems to trigger a warning that an "invalid field is not focusable" - which I understand - but, can this be solved and done well? Is there a way to do this without JavaScript? Is there a better way altogether?
Let's assume I will show the hidden stuff in the case that there is no JS on the user's browser. Let's also assume I was given this design and asked to implement it, i.e. this is not a question about UX.
Just merge 2 forms into one and set 2 buttons
<form id="login">
<input id="username">
<input id="password">
<button name="submit" type="submit" value="login">LOG IN</button>
<button name="submit" type="submit" value="registration">REGISTER</button>
</form>
After submitting your form you need to check submit value like
if($_POST['submit'] == 'login')
then do code for login
else if($_POST['submit'] == 'registration')
then do code for registration
To reveal the hidden fields in the case of no javascript you would put the data between the following tags:
As far as the fields that are active when there is JavaScript, place that data within the JavaScript itself using document.write("fields here");.
The end result will be that these fields appear when JavaScript is enabled, and do not appear when JavaScript is disabled.
Hope this helps.

Show div depending on a search

I have a small problem with a script that I want to find and show different divs depending on a search. The original script is something I found and used for a contact list, and that I now want to configure to do something else.
Original code (JSFiddle)
My edited code:
$('.Fruit').hide();
$('#search').click(function() {
$('.Fruit').hide();
var txt = $('#search-criteria').val();
$('.Fruit').each(function() {
if ($(this).id.toUpperCase().indexOf(txt.toUpperCase()) != -1) {
$(this).show();
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<input type="text" id="search-criteria" />
<input type="button" id="search" value="search" />
<div class="Fruit" id="Apple">
<h3>Some text about apples</h3>
</div>
<div class="Fruit" id="Orange">
<h3>Some text about oranges</h3>
</div>
I don't know if you understand what I'm trying to achieve...? I have, in this case, two divs - Apple and Orange. By default both are hidden, but if I enter Apple for instance in the search field and push the search button, the div "Apple" will show, and if I instead search for "Orange" then obviously I want the "Orange" div to show. If I search for anything else nothing will show, as long as there's not a div with an id that matches the searchword.
So basically I'm trying to build a database of preloaded content that can be searched and shown on the fly without reloading the page.
The error is, as far as I can understand, when I try to address and compare the divs id with the searchword on row 6 in the JS. Does anyone know how to do this, and make this work? Or does anyone have another solution that can perform this task?
The issue is because jQuery objects do not have an id property. You need to use prop('id') or just this.id.
Also note that you can improve your logic by making the id attributes you match with lower case, then convert the input to lower case, then you can just use a normal selector, like this:
$('#search').click(function() {
var txt = $('#search-criteria').val();
if (txt)
$('.fruit').hide().filter('#' + txt.toLowerCase()).show();
});
.fruit {
display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<input type="text" id="search-criteria" />
<input type="button" id="search" value="search" />
<div class="fruit" id="apple">
<h3>Some text about apples</h3>
</div>
<div class="fruit" id="orange">
<h3>Some text about oranges</h3>
</div>

How to create a form with a variable number of inputs?

Take this code for example:
var add = function() {
var added = document.createElement("div");
document.getElementById("ID").appendChild(added);
added.setAttribute("id", "Task " + document.getElementById("ID").childElementCount);
added.appendChild(document.createElement("input"));
added.appendChild(document.createElement("br"));
};
<form id="ID">
Name:
<br>
<input type="text" name="name">
<br>
</form>
<button onclick="add()">Add</button>
Every time you click the button, a new input is created for the form.
Is this the best way of making the number of form elements dynamic?
I looked into using HTML templates, but it didn't seem like there was a way to edit the ID of each individual additional element, which would be necessary for my applications.
Also, a subquestion: I'm using AngularJS and can't figure out how to add the bs-datepicker directive to my elements with JavaScript. How can I do that?
Here's an example of bs-datepicker which I know works:
<input type="text" class="form-control"
ng-model="options.fromDate"
max-date="{{options.toDate}}"
start-date="{{options.currentDateValue.toString()}}"
start-week="1" placeholder="From" bs-datepicker>

Change Input field grabbing NAME

I've searched about all I can. I'm trying to change the text of an input field using its name. I have found many ways to do it by ID like:
<script>
function changeValue(o){
document.getElementById('type').value=o.innerHTML;
}
</script>
<button id="technician" onclick="changeValue(this)">Technician</button>
<button id="developer" onclick="changeValue(this)">Developer</button>
<input type="text" id="type" name="type" value="change" />
But what I need to accomplish is for inputs without ID's.
Something along the lines of:
<script>
function changeValue(o){
document.getElementsByName('NAME').value=o.innerHTML;
}
</script>
<button id="technician" onclick="changeValue(this)">Technician</button>
<button id="developer" onclick="changeValue(this)">Developer</button>
<input type="text" name="NAME" value="change" />
Is there any way of accomplishing this?
UPDATE
I'm trying to expand on the javascript you guys helped me with.
The Snippet:
<script>
function changeValue(o){
document.getElementsByName('NAME')[0].value=o.innerHTML;
}
</script>
<span onclick="changeValue(this)" style="cursor: pointer;">One</span>
<span onclick="changeValue(this)" style="cursor: pointer;">Two</span>
<img src='image.gif' onclick="changeValue(this.src)" />
<input type="text" name="NAME" value="SOMETHING">
The spans are working correctly, although I don't actually need them. I will have all images once I figure this out.
I have tried a few ways, but what I can find is not directly related to my use.
The end goal is to get the img src into the text input with js, preferably somewhat how it already exists. I feel it's really close.
getElementsByName() returns a collection. use [] to access individual elements
ex :
function changeValue(o){
document.getElementsByName('NAME')[0].value=o.innerHTML;
}
document.getElementsByName('NAME') returns a list of elements by name. You need to provide the index as
document.getElementsByName('NAME')[0].value=o.innerHTML
Use document.querySelector like so
document.querySelector('input[name="NAME"]').value = o.innerHTML;
jQuery way
$('input[name="NAME"]').val("im changed!")

Categories