Show/hide forms using buttons and JavaScript - javascript

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>

Related

Button combination

I want to get input from the user in a type="number" text box.
the limitation is a number between 1994-1998.
I currently have two buttons. One "submit" button and a second ("button") button that goes to the next screen.
I want to make the 2 buttons one.
Which means that as soon as I click the "Move to Next page" button, the input is also checked.
And you can move to the next screen only with proper input.
would much rather do it only with HTML and less with JavaScript if possible.
If there is no option then it is also possible with JavaScript.
function check () {
console.log('Checked!');
}
<div>
between 1994 and 1998: <input id="section5input" type="number" name="quantity" min="1994" max="1998">
<input type="submit">
Calculate the answers!
</div>
</div>
<div class="box" id="section6">
<h1>fin!</h1>
<div class="question-text">
<input style="padding: 20px;" type="button" class="btn" onclick="check();">check!!!
</div>
</div>
From what I understand you want to go to next page only if input is correct then check this out. I have created a form and placed your html inside it. Now the submit button will only work if check function return true.
function check(){
//return true, if correct
//return false, if incorrect
return true;
}
<form action='yourURLforNextPage' method="POST">
Between 1994 and 1998:
<input id="section5input" type="number" name="quantity" min="1994" max="1998">
<input type="submit" onclick="return check();">
</form>
function check(){
let val = document.getElementById("section5input");
if((val.value!= "" && null) && (val.value> 1994 && val.value<1998) ){
//code to render to next screen
}
}

how do I make it so when I click a button from a foreach list, it only activates the button in that specific list?

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.

Add input to form if button is clilcked

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 make the show function in an if else override the hide function permanently?

in this code I want the show function (correct or incorrect answer) to last but it always reverts to hide
$("#correctOne").hide();
$("#incorrectOne").hide();
function myFunction() {
var inputOne = $("#inputOne").val();
if (inputOne == 10) {
$("#correctOne").show();
//confirm("Correct");
} else {
$("#incorrectOne").show();
//confirm("Incorrect");
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h1>What number am I thinking of?</h1>
<p>Divide me by four and my remainder is two. I am net if you see me through the looking glass.</p>
<form>
<input id="inputOne" type="text" placeholder="Answer Here">
<button onclick="myFunction()">submit</button>
</form>
<h2 id="correctOne">Yes!</h2>
<h3 id="incorrectOne">Nope!</h3>
Add a type to button in your button markup:
<button type="button" onclick="myFunction()">submit</button>
Why?
Because default functionality of the button is to submit the form and your form gets submitted when you click the button and due to postback your elements get hidden as doc ready fires again.
click button.
calls the function and executes the code.
form submission happens.
postback happens page again reloads.
hiding of elements again gets fired.
Even you can simplify this with .toggle(boolean):
$("#correctOne").hide();
$("#incorrectOne").hide();
function myFunction() {
var inputOne = $("#inputOne").val();
$("#correctOne").toggle(inputOne == 10); // .toggle(true) to show
$("#incorrectOne").toggle(inputOne != 10); // .toggle(false) to hide
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h1>What number am I thinking of?</h1>
<p>Divide me by four and my remainder is two. I am net if you see me through the looking glass.</p>
<form>
<input id="inputOne" type="text" placeholder="Answer Here">
<button type="button" onclick="myFunction()">submit</button>
</form>
<h2 id="correctOne">Yes!</h2>
<h3 id="incorrectOne">Nope!</h3>
You need first to hide both of them inside a function body.
$("#correctOne").hide();
$("#incorrectOne").hide();
function myFunction() {
$("#correctOne").hide();
$("#incorrectOne").hide();
var inputOne = $("#inputOne").val();
if (inputOne == 10) {
$("#correctOne").show();
//confirm("Correct");
} else {
$("#incorrectOne").show();
//confirm("Incorrect");
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h1>What number am I thinking of?</h1>
<p>Divide me by four and my remainder is two. I am net if you see me through the looking glass. </p>
<form>
<input id="inputOne" type="text" placeholder="Answer Here">
<button onclick="myFunction()">submit</button>
</form>
<h2 id = "correctOne">Yes!</h2>
<h3 id = "incorrectOne">Nope!</h3>

How to display diffrence divs according to radio selection

I have 2 radio buttons no one of them checked by default and I want if any one of them checked a Div appear according to what radio button was checked.
( Divs have different content )
and if the selection changed the one which appeared now disappear and the other appear.
and when one of them appear there are another 2 radio to do the same thing for another one div ( one to show and one to hide )
Here what I tried to do
JavaScript
function haitham()
{
if(document.getElementById('s').checked == true)
{
document.getElementById('StudentData').style.display = "block";
document.getElementById('GraduateData').style.display = "none";
}
else if(document.getElementById('g').checked == true)
{
document.getElementById('GraduateData').style.display = "block";
document.getElementById('StudentData').style.display = "none";
}
}
function info()
{
if(document.getElementById('y').checked == true)
{
document.getElementById('MoreInfo').style.display = "block";
}
else if(document.getElementById('n').checked == true)
{
document.getElementById('MoreInfo').style.display = "none";
}
}
HTML
<input class="margin2" id="s" type="radio" name="kind" value="student" onchange="haitham()"
required="required" />Student
<input class="margin2" id="g" type="radio" name="kind" value="graduate" onchange="haitham()"
required="required" />Graduate
<div id="StudentData">
content 1
<input class="margin2" id="y" type="radio" name="info" value="yes" onchange="info()"
required="required" />Student
<input class="margin2" id="n" type="radio" name="info" value="no" onchange="info()"
required="required" />Graduate
</div>
<div id="GraduateData">
content 2
</div>
<div id="MoreInfo">
content 3
</div>
the first work good but the other 2 radio did not work although it should be the same
Thank you ...
Your problem wasn't a javascript or html one, it was actually a CSS issue. Your code was fine, aside from the fact that the values for display are "none" and "block" not "" and "hidden". I modified your code and updated the fiddle.
Here's the link:
http://jsfiddle.net/8JpSQ/4/
Just add a clicked event to the radio buttons, and through a Javascript function change the attribute of the respective DIV to hidden when required. To show it instead, remove the attribute 'hidden'. Also, we'd probably be able to help more if you can post some code showing what you tried/what went wrong. But what I suggested should be the general approach to make what you want happen.
I have no idea what your HTML is, so here's what I have:
$('input[type="checkbox"]').click(function() {
$('.divWrapper > div').eq($(this).index()).fadeOut().siblings().fadeIn();
});
I'm assuming this is your structure:
<form>
<checkbox>
<checkbox>
...
</form>
<div class="divWrapper">
<div>
<div>
...
</div>

Categories

Resources