compare two fields in Flask Jinja2 - javascript

I am trying to compare two fields generated with Jinja, however, without the need of pressing the submit button.
I have used the included validators, standard if cases, etc. None of them work as expected, so I tried Javascript.
In general, I want to:
Compare two fields (domain/server). If their IP addresses are not exactly a 'Confirm' button should be shown.
In order to do that, I need to reload the server-side HTML.
Additionally, I am unable to figure out how to compare the two fields' IP addresses via Javascript.
Here is a sample code:
<div id="home" class="text-center">
Hello, {{ username }}
</div>
<body>
<input type="text" id="domain" size="30">
<input type="text" id="server" size="30">
{% if not compareArecords %}
<button type="button" class="btn btn-danger">Danger</button><br>
{%endif %}
</body>
<script>
document.getElementById("domain").addEventListener("keyup", compareArecords);
document.getElementById("server").addEventListener("keyup", compareArecords);
function compareArecords() {
var text1 = document.getElementById("domain");
var text2 = document.getElementById("server");
if (text1.value === text2.value)
return true;
else
return false;
}
</script>

What's typically done in order not to have to reload the html is to have the element hidden with css until you need to display it. In your example would be something like
<body>
<input type="text" id="domain" size="30">
<input type="text" id="server" size="30">
<button type="button" class="btn btn-danger hidden" id="btn-danger">Danger</button><br>
</body>
<script>
document.getElementById("domain").addEventListener("keyup", compareArecords);
document.getElementById("server").addEventListener("keyup", compareArecords);
function compareArecords() {
var text1 = document.getElementById("domain");
var text2 = document.getElementById("server");
if (text1.value === text2.value)
// Nothing to do here!
else {
var danger_btn = document.getElementById("btn-danger");
danger_btn.classList.toggle("hidden");
}
}
</script>
Css:
.hidden { display: none; }
It should be noted that you can also generate the Danger button entirely with javascript, and that's not overly complicated either, should you want to do that, but it has some drawbacks like separation of concerns.

Related

How to make a form switch dynamically using a type switcher button

I have to make a page, where there are 3 forms within it, but only one should be displayed. Also, these forms shouldn't be connected. For example if I would put in some kind of validation within all 3 of the forms, only the one I use should respond to the validation code, the other ones should stay idle untill I switch the form and use it. I have to make this without frameworks, plain, JS or PHP, HTML and CSS.
I have a page where I can switch forms, 1 is displayed, 2 are hidden. However, I made a validation class, and it is validating all 3 forms, since the 2 i'm not using are just hidden, not disabled so this is not working.
Any one know how I sould make these forms, so they would be independent from each other? I mean, how would they go about making this code, not making mine into account. I want to redo it and just add my other stuff on top of it.
if my deductions are correct on the little information given, here is probably what you are looking for
const
Bt_SwitchForm = document.getElementById("Switch-Form"),
FormX_Count = 3;
var
formActiv = 0,
formX = {};
function formX_Submit(e) {
e.preventDefault()
console.log('formX_Submit on =', this.id )
}
document.querySelectorAll('form').forEach( (elm, Item)=>
{
formX[elm.id] = { 'f' : elm, 'ref': Item }
elm.onsubmit = formX_Submit;
});
Bt_SwitchForm.onclick=()=>{
formActiv = ++formActiv % FormX_Count;
for(let elm in formX) {
formX[elm].f.className = formX[elm].ref===formActiv ? '': 'form_Off'
};
}
form {
display: block;
padding: 20px;
border: 1px solid grey;
width : 200px;
}
form.form_Off { display : none }
button { margin: 10px}
<form id="form1" class="">
<input type="text" id="inputTxt1" value="" placeholder="input form 1" >
<button type="submit">submit</button>
<button type="rest">reset</button>
</form>
<form id="form2" class="form_Off">
<input type="text" id="inputTxt1" value="" placeholder="input form 2" >
<button type="submit">submit</button>
<button type="rest">reset</button>
</form>
<form id="form3" class="form_Off">
<input type="text" id="inputTxt3" value="" placeholder="input form 3" >
<button type="submit">submit</button>
<button type="rest">reset</button>
</form>
<button id="Switch-Form">Switch Form</button>
I think it is useless for me to explain this code since you seem to live with a strong power of deduction. ;)

Python-requests module, post two "values" to renew&scrape website

The first part was already answered, however, EDIT isn't.
I am using python and the requests module to scrape a website. Therefore I have to “click” a Renew-Button, which is a link(href) wrapped in an image “pat_renewmark.gif”.
html
<form name="checkout_form" method="POST" id="checkout_form">
<input type="HIDDEN" id="checkoutpagecmd">
<a href="#" onclick="return submitCheckout( 'sortByCheckoutDate', 'bycheckoutdate' )">
<img src="/screens/pat_sortbychkout.gif" alt="SORT BY DATE CHECKED OUT" border="0">
</a>
<input type="HIDDEN" name="currentsortorder" value="current_duedate">
<a href="#" onclick="return submitCheckout( 'requestRenewSome', 'requestRenewSome' )">
<img src="/screens/pat_renewmark.gif" alt="RENEW SELECTED ITEMS" border="0">
</a>
</form>
javascript (submitCheckout)
function submitCheckout(buttonname, buttonvalue)
{
var oHiddenID;
oHiddenID = document.getElementById("checkoutpagecmd");
oHiddenID.name = buttonname;
oHiddenID.value = buttonvalue;
//c29364j/c1365070 - prevent the patron from submitting twice
var oButtonSpan;
oButtonSpan = document.getElementById("checkoutbuttons0");
if (oButtonSpan) oButtonSpan.style.display = "none";
oButtonSpan = document.getElementById("checkoutbuttons1");
if (oButtonSpan) oButtonSpan.style.display = "none";
document.getElementById("checkout_form").submit();
return true;
}
Apparently submitCheckout passes .name and value, which are both assigned to ”requestRenewSome”’, to the hidden input with theid=“checkoutpagecmd”`.
I’ve worked with the requests module before and I am able to handle a simple username&password input , for example:
html
<div class="formEntryArea">
<label for="extpatid">
<span class="formLabel">
Your username:
</span>
</label>
<input name="extpatid" id="extpatid" value="" size="20" maxlength="40">
<label for="extpatpw">
<span class="formLabel">
Your password:
</span>
</label>
<input name="extpatpw" id="extpatpw" type="PASSWORD" value="" size="20" maxlength="40">
</div>
python
import requests
with requests.Session() as c:
LOGIN_URL = "https://example.com"
USERNAME = “XXXXX”
PASSWORD = “YYYYY”
source = c.get(LOGIN_URL)
data_load = dict(extpatid=USERNAME,extpatpw=PASSWORD)
head_load = dict(referer=LOGIN_URL)
c.post(LOGIN_URL, data=data_load, headers=head_load)
However, here c.post is handling only one “value” per input (either USERNAME or PASSWORD) and no javascript code is included.
As it seems, for the problem above I somehow have to post the two attributes/strings
.name = 'requestRenewSome'
.value = 'requestRenewSome'
? Or is the approach completely different to the example I attached?
EDIT
The answer from matino (or the comment from t.m.adam) solves the problem! Unfortunately the User then has to approve that he is sure he wants to renew by clicking a YES button.
html
<form name="checkout_form" method="POST" id="checkout_form">
<input type="HIDDEN" id="checkoutpagecmd">
<input type="HIDDEN" name="currentsortorder" value="current_duedate">
<span id="checkoutbuttons0">
<input type="SUBMIT" name="renewsome" value="YES">
<input type="SUBMIT" name="donothing" value="NO">
</span>
</form>
I therefore added 'renewsome': 'YES'to the data_load dictionary, but thats not enough. I don't know the value for the hidden input/s? id=checkoutpagecmd and/or? name=currentsortorder but couldn't find any answer on how to proceed.
P.S. I know it's actually a knew question, and I'm going to separate it, if it's getting answered.
What the javascript code actually does is dynamically assigning name and value to the hidden input. So in the end there can be 2 cases:
<input type="hidden" id="checkoutpagecmd" name="sortByCheckoutDate" value= "bycheckoutdate">
or
<input type="hidden" id="checkoutpagecmd" name="requestRenewSome" value= "requestRenewSome">
Knowing that, you can send http request like this:
requests.post(url, data={'sortByCheckoutDate': 'bycheckoutdate'}) # 1st case
requests.post(url, data={'requestRenewSome': 'requestRenewSome'}) # 2nd case

Awesome fonts and javascript search function on click

I got this script to use it as a search engine, but when I tried to change the button to replace it with a CSS styled button (including fontawesome), the button doesn't call the results. I am a newbie and my javascript knowledge is limited.
<form name="searchengine">
<input type = text name ="keywords" placeholder ="Search..." style ="font-size:14px;hight:35px;width:240px;" value="" maxlength=40>
<input type = button name="go" Value=" 🔍 " style ="height:30px;width:35px;" onClick="search()">
</form>
I just adjusted the inline styling but I would like to replace it with this:
<form name="searchengine">
<input type="hidden" name="keywords" value="1">
<link href="//maxcdn.bootstrapcdn.com/font-awesome/4.1.0/css/font-awesome.min.css" rel="stylesheet">
<div class="box">
<div class="container-4">
<input type="search" id="keywords" placeholder="Search..." />
<button class="icon"><i class="fa fa-search"></i></button>
</div>
</form>
I know that there is no onclick function assigned on the second example but I have searched everywhere and couldn't find an answer, I have tried different ways to make it "clickable" but with no success. Below are some examples of what I have done. Most come from Stackoverflow.
<span onClick="myFunction()"><i class="fa fa-search"></i></span>
<i class="fa fa-search" onclick="search()"></i>
Thanks in advance for your help. Please let me know if you require the full script.
Here is the entire script. Thanks for your help.
<html>
<title>
Search Engine
</title>
<head>
<script>
title = new Object();
desc = new Object();
links= new Object();
matched= new Object();
keywords= new Object();
found= new Object();
var temp=0;
// actual location or the item to be searched // description of he location
// actual link
// percentage match found
// keywords as parsed from the input
// # of titles present in the database
title[0]=14
//no of keywords after parsing
keywords[0]=0
//no of matches found.
found[0]=0
<!-- Begin List of Searchable Items -->
<!--put the list of the links and descriptions here!!-->
title[1]="Introduction FAQs Java JavaScript beginner"
desc[1]="JavaScript Primer (Part 1 of 2) "
links[1]="http://www.javascriptkit.com/primer1.htm"
matched[1]=0
title[2]="objects document function parameter last modified date"
desc[2]="JavaScript Primer (Part 2 of 2) "
links[2]="http://www.javascriptkit.com/primer2.htm"
matched[2]=0
title[3]="alert confirm prompt box pop up dialog"
desc[3]="Creating Alert, Confirm, and Prompt Boxes"
links[3]="http://www.javascriptkit.com/alert.htm"
matched[3]=0
title[4]="event handler onClick onLoad onMouseover onMouseout onUnload"
desc[4]="Understanding Event Handlers in JavaScript"
links[4]="http://www.javascriptkit.com/event.htm"
matched[4]=0
title[5]="object model tree accessing forms "
desc[5]="Accessing and Validating Forms Using JavaScript (Part 1 of 2)"
links[5]="http://www.javascriptkit.com/form1.htm"
matched[5]=0
title[6]="form validation onBlur onSubmit"
desc[6]="Accessing and Validating Forms Using JavaScript (Part 2 of 2)"
links[6]="http://www.javascriptkit.com/form2.htm"
matched[6]=0
title[7]="date object write html setTimeout function"
desc[7]="Creating Time Dependent Scripts using JavaScript (Part 1 of 2)"
links[7]="http://www.javascriptkit.com/time1.htm"
matched[7]=0
title[8]="live clock watermark"
desc[8]="Creating Time Dependent Scripts using JavaScript (Part 2 of 2)"
links[8]="http://www.javascriptkit.com/time2.htm"
matched[8]=0
title[9]="image preload rollover effect filter"
desc[9]="Images and JavaScript- Apples and Apples (Part 1 of 2)"
links[9]="http://www.javascriptkit.com/image1.htm"
matched[9]=0
title[10]="rollover effect"
desc[10]="Images and JavaScript- Apples and Apples (Part 2 of 2)"
links[10]="http://www.javascriptkit.com/image2.htm"
matched[10]=0
title[11]="new window open secondary reload close toolbar menubar status bar "
desc[11]="Windows and JavaScript"
links[11]="http://www.javascriptkit.com/window.htm"
matched[11]=0
title[12]="frames access object multiple"
desc[12]="Loading Two frames with one link."
links[12]="http://www.javascriptkit.com/twoframes.htm"
matched[12]=0
title[13]="selection list options array text vale"
desc[13]="I'll hava a double combo please (Part 1 of 2)"
links[13]="http://www.javascriptkit.com/combos1.htm"
matched[13]=0
title[14]="combo link box jump"
desc[14]="I'll hava a double combo please (Part 2 of 2)"
links[14]="http://www.javascriptkit.com/combos2.htm"
matched[14]=0
<!-- End list of Searchable items -->
function search(){
// get the input from the input by the user and strip it into keywords //
var skeyword=document.searchengine.keywords.value.toLowerCase();
var check=1;
var pos=0;
var i=0;
var j=0;
var itemp=0;
var config='';
while (true)
{
if (skeyword.indexOf("+") == -1 )
{
keywords[check]=skeyword;
break;
}
pos=skeyword.indexOf("+");
if (skeyword !="+")
{
keywords[check]=skeyword.substring(0,pos); check++;
}
else
{
check--;
break;
}
skeyword=skeyword.substring(pos+1, skeyword.length);
if (skeyword.length ==0)
{
check--;
break;
}
}
// the keywords have been put in keywords object.
keywords[0]=check;
//alert(check);
// matching and storing the matches in matched
for ( i=1; i<=keywords[0];i++)
{
for (j=1;j<=title[0];j++)
{
if (title[j].toLowerCase().indexOf(keywords[i]) > -1 )
{
matched[j]++;
}
}
}
// putting all the indexes of the matched records in found
for (i=1;i<=title[0];i++)
{
if (matched[i] > 0 )
{
found[0]++;
// increment the found
found[found[0]]=i;
}
}
//alert("found 0 " + found[0]);
// sort the list as per max percentage of matches
for (i=1;i<=found[0]-1;i++)
{
for(j=i+1;j<=found[0];j++)
{
if ( matched[found[i]]< matched[found[j]] )
{
temp= found[j];
found[j]=found[i];
found[i]=temp;
}
}
}
config='toolbar=no,location=no,directories=no,status=no,menubar=no,scrollbars=yes,resizable=yes'
output = window.open ("","outputwindow",config)
output.document.write('<title> Atlantis Direct Search Result </title>');
output.document.write('<BODY bgcolor=#ffffff text=#000000 link=#990099 vlink =#339966 >');
output.document.write('<center> <h1> Search Results </h1></center>');
output.document.write('<hr>');
output.document.write(' The Keyword(s) you searched :: '.big() );
for (i=1; i<=keywords[0]; i++)
{
output.document.write( keywords[i].bold() +" "); }
output.document.write('<br>');
if (found[0]==0)
{
output.document.write('<hr>');
output.document.write("<b>No matches resulted in this search </b> <br>");
output.document.write("You may close the results and reduce the length/number of the keywords <br>");
}
else
{
output.document.write(" <hr> <b> The Results of the search are : </b> ");
output.document.write( found[0] +" Entries found ".italics());
output.document.write("<table border=1 width=100%>");
for (i=1; i<=found[0];i++)
{
output.document.write("<tr><td valign=topbgcolor=#9999ff>");
output.document.write("<h3>" +i +"</h3>"); output.document.write("<td valign=top>");
itemp=found[i];
output.document.write(desc[itemp].bold() +"<br>" +links[itemp].link(links[itemp])+"<br>");
temp= (matched[itemp]/keywords[0])*100
output.document.write("<i> Matched with keywords :: "+temp+" % </i>" );
matched[itemp]=0
}
found[0]=0;
output.document.write("</table>");
}
output.document.write ('This search was created by &copy Satadip Dutta 1997'); output.document.write ("<hr>");
output.document.write ("<form><center>");
output.document.write ("<input type='button' value='Start Another Search' onClick = 'self.close()'>") ;
output.document.write ("</center></form>");
output.document.close();
}
</script>
<head>
<body bgcolor="#ffffff">
<center>
<H1>Search Engine</H1>
</center>
<hr>
This is a search engine implemented in Javascript. You will need a
Java Script enabled browser to run this search.
<hr>
<P>
</P>
<TABLE BORDER=0 CELLSPACING=5 CELLPADDING=5>
<TR>
<TD WIDTH="20%" ALIGN="left">
This search is NOT case sensitive.
</TD>
<TD WIDTH="80%" ALIGN="left">
Put "+" between keywords in a list if using more than one keywords.
</TD>
</TR>
</TABLE>
<form name="searchengine">
<center>
Keywords:
<input type = text name ="keywords" placeholder ="Search..." value="" maxlength=40>
<input type = button name="go" Value="Go ahead and find" onClick="search()">
<br>
</center>
</form>
<hr>
<!-- you can write more text/instructions out here. -->
</body>
<html>
Some points to consider:
You forgot to set the type of your button to submit
Links are normally place on the <head>
You should give your form an action
<head>
...
<link href="//maxcdn.bootstrapcdn.com/font-awesome/4.1.0/css/font-awesome.min.css" rel="stylesheet">
...
</head>
...
<form name="searchengine" action="doSomething">
<input type="hidden" name="keywords" value="1">
<div class="box">
<div class="container-4">
<input type="search" id="keywords" placeholder="Search..." />
<button type="submit" class="icon"><i class="fa fa-search"></i></button>
</div>
</div>
Hope it helps.
This code works just fine. Your link is messed up, why is it just // instead of https://? Your links should be in the head, if they aren't they aren't loaded before the body, which causes a split second of unstyled content to show before it reaches the stylesheet. Your form should have an action to perform and your search button should be of the type submit so it's a submit button for the form.
The below code and jsfiddle work just fine if you want to try them out.
Also, Dreamweaver is not that impressive, I recommend getting Netbeans instead, it does the same job but for free (all you really want from your web IDE is code completion so you don't have to write as much, and both Netbeans and Dreamweaver does this equally well except that Netbeans is better for more all-around programming for all kinds of languages).
https://jsfiddle.net/vfmrc40k/
<html>
<head>
<!-- Links go in the head, they are not scripts and this makes them load before the body so that you don't get a split second of unstyled content showing -->
<link href="http://maxcdn.bootstrapcdn.com/font-awesome/4.1.0/css/font-awesome.min.css" rel="stylesheet">
<script>
function performSearch () {
alert('I am searching!')
// Use e.g. jQuery to get the value for the search box, it's easiest
}
</script>
</head>
<body>
<!-- Your form should have an action to perform, in this case a javascript function. It isn't just 'correct', it also makes it possible to press Enter to perform the search, because enter and the submit button both trigger the forms action. -->
<form name="searchengine" action="javascript:performSearch()">
<input type="hidden" name="keywords" value="1">
<div class="box">
<div class="container-4">
<input type="search" id="keywords" placeholder="Search..." />
<button type="submit" class="icon"><i class="fa fa-search"></i></button>
</div>
<!-- You forgot a </div> -->
</div>
</form>
</body>
</html>

How to only show a div if a certain entry field is filled in (but not submitted)?

Relatively new to html coding, and very new with javascript. On this page, I don't want the option to email an editor to become visible until a tripID is filled in (but form not submitted yet). Here is the form so far without that option added yet:
TripID:
<input type='text' id='atripid' name='atripid' size='6' maxlength='6' /><br><br>
Port:
<input type='text' id='aport' name='aport' size='6' maxlength='6' /><br><br>
<div id=acheckbox><br> E-mail editor? </b>
<input type='checkbox' name='acheck' onchange='copyTextValue(this);'/><br>
<div id='div' style='display:none'>
<br> <b>Subject:</b> <input type='text' id='asubject' name='asubject' size='70' maxlength='75'/><br><br>
<textarea name='aemailbody' cols='85' rows = '10'>Explain any packaging or labeling mistakes here...</textarea>
</div>
</div>
<script>
function copyTextValue(bf) {
if(bf.checked){
document.getElementById('div').style.display = 'block';
var atext = 'Frozen Sample Error Notice: '+ document.getElementById('atripid').value;
}else{
document.getElementById('div').style.display = 'none';
var atext = '';
}
document.getElementById('asubject').value = atext
}
</script>
</div>
Now to hide the email editor option until tripid is filled in, I got something like this to work on jfiddle:
<form action="">
tripid:<input type="atripid" id="atripid" value="">
port:<input type="aport" id="aport" value="">
</form>
<div id="acheckbox" style="display:none">
<br><br><br>
This is where the email options (subject and textbox) would appear.
</div>
<script>
$("#atripid").keyup(function(){
if($(this).val()) {
$("#acheckbox").show();
} else {
$("#acheckbox").hide();
}
});
</script>
But for some weird reason, it won't work anywhere else, so I can't figure out how to incorporate it into what I already have. Does anyone have any ideas that could help me? Thanks!
You can do something like this with pure javascript:
<input type="atripid" id="atripid" value="" onkeyup="keyupFunction()">
And define your keyupFunction().
See jsfiddle
The code you attempted on jsfiddle requires that you import jquery.js files. An alternate way of doung what you intend to do is
<input type='text' id='atripid' name='atripid' size='6' maxlength='6' onkeyup="toggleCheckBox(this)" />
<input type='checkbox' name='acheck' id="acheckbox" style="display:none;" onchange='copyTextValue(this);'/>
with js
function toggleCheckBox(element) {
if(element.value=='') {
document.getElementById('acheckbox').style.display = 'none';
}
else {
document.getElementById('acheckbox').style.display = 'block';
}
}
The issue is the .keyup() method, which is not consistent across browsers and does not account for other means of user input. You would rather, use an Immediately Invoked Function Expression (IIFE) that will detect the propertychange of the input field in question and then to fire the desired event if the condition is met. But for the purposes of simplicity, and the fact that I'm not as well versed enough in IIFE syntax, simply bind some events to the input field, like so:
$("#atripid").on("keyup change propertychange input paste", (function(e) {
if ($(this).val() === "") {
$("#acheckbox").hide();
} else {
$("#acheckbox").show();
}
}));
#acheckbox {
display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<form action="">
tripid:
<input type="atripid" id="atripid" value="">port:
<input type="aport" id="aport" value="">
</form>
<div id="acheckbox">
<br>
<br>
<br>This is where the email options (subject and textbox) would appear.
</div>

innerHTML won't change element

I have an div element ("main") on my page who's contents changes back and forth between two different screens (their id's are "readout" and "num"), the contents of which are stored as hidden div elements (using display:none). Each screen has a button which sets mainto the other hidden div.
Since I struggled to get javascript to put num.innerHTML into main on load, I've ended up putting virtually identical content to num (with a different form name) into main:
<p>Number of Passengers per Carriage:</p>
<form method="post" action="javascript:void(0);" name="applesForm" onSubmit="setPassengers();">
<input type="text" name="numApples" id="numPassengers" />
<br/><br/>
<input type="submit" name="Submit" value="OK!"/>
</form>
setPassengers() successfully sets main's contents to readout. readout successfully sets main's contents to num (virtually identical to the original content of main). But then it won't go back to readout.
Here are setPassengers() and setPassengersAgain(), which is the same but for a different form name:
function setPassengers()
{
passengers=document.applesForm.numPassengers.value;
document.getElementById('main').innerHTML=readout.innerHTML;
}
function setPassengersAgain()
{
passengers=document.applesFormAgain.numPassengers.value;
document.getElementById('main').innerHTML=readout.innerHTML;
}
So my question is:
1)Why isn't num changing to readout?
2)Is there a way to load num straight away on page load so as to simplify the code?
EDIT: I can use onload, which means that num is the only bit that's broken...
EDIT 2: Here are the hidden div's:
<div id="readout" style="display:none">
<p>Throughput per hour:</p>
<p id="output">--</p>
<p>Average Dispatch Time:</p>
<p id="avDisTime">--</p>
<form method="post" action="javascript:void(0);" name="dispatchForm" onSubmit="dispatch();i++;">
<input type="submit" name="Submit" value="Press on Dispatch!"/>
</form>
<br/>
<form method="post" action="javascript:void(0);" name="resetTimesForm" onSubmit="resetTimes();">
<input type="submit" name="Submit" value="Reset Times"/>
</form>
<form method="post" action="javascript:void(0);" name="resetAllForm" onSubmit="resetAll();">
<input type="submit" name="Submit" value="Reset All"/>
</form>
</div>
<!--back to default page-->
<div id="num" style="display:none">
<p>Number of Passengers per Carriage:</p>
<form method="post" action="javascript:void(0);" name="applesFormAgain" onSubmit="setPassengersAgain();">
<input type="text" name="numApples" id="numPassengers" />
<br/><br/>
<input type="submit" name="Submit" value="OK!"/>
</form>
</div>
You didn't post your HTML code, so I don't know how it looks like, but you could use somethin like:
HTML:
<button id="changeMain">Change #main</button>
<div id="main">
<div id="readout" class="screen show">
Readout
</div>
<div id="num" class="screen">
Num
</div>
</div>
CSS:
#main>.screen{display:none;}
#main>.screen.show{display:block;}
JavaScript:
var els=[document.getElementById('readout'),document.getElementById('num')],current;
function addClass(el,c){
var arr=el.className.split(' ');
if(arr.indexOf(c)>-1){return;}
arr.push(c);
el.className=arr.join(' ');
}
function delClass(el,c){
var arr=el.className.split(' ');
var i=arr.indexOf(c);
if(i===-1){return;}
arr.splice(i,1);
el.className=arr.join(' ');
}
document.getElementById('changeMain').onclick=function(){
if(!current){
for(var i=0,l=els.length;i<l;i++){
if(els[i].className.indexOf('show')>-1){
current=i;
break;
}
}
}
delClass(els[current],'show');
current=(current+1)%els.length;
addClass(els[current],'show');
}
DEMO: http://jsfiddle.net/CUgqh/
Explanation:
If you want some content insode #main, you should place inside it (hidden or shown). Then, we hide all .screen with #main>.screen{display:none;} except .screen.show: #main>.screen.show{display:block;}.
Then, JavaScript code:
First we create an array with the elements:
var els=[document.getElementById('readout'),document.getElementById('num')],current;
And a function which adds/removes a class c to the element el:
function addClass(el,c){
var arr=el.className.split(' ');
if(arr.indexOf(c)>-1){return;}
arr.push(c);
el.className=arr.join(' ');
}
function delClass(el,c){
var arr=el.className.split(' ');
var i=arr.indexOf(c);
if(i===-1){return;}
arr.splice(i,1);
el.className=arr.join(' ');
}
And we create an event to the button:
document.getElementById('changeMain').onclick=function(){
if(!current){
for(var i=0,l=els.length;i<l;i++){
if(els[i].className.indexOf('show')>-1){
current=i;
break;
}
}
}
delClass(els[current],'show');
current=(current+1)%els.length;
addClass(els[current],'show');
}
The code above does:
If it's the first time the current els' index (current) is undefined, we search which element has the class show by default.
It removes the class show to the current shown element, so it disappears.
It adds 1 to current (or it becomes 0 if it was the last els' element
It add class show to the current element, so it appears.

Categories