Javascript body onload once - javascript

Im just new at using Javascript and I'm having trouble on pageload event. After submitting form1, form 2 should appear.
<html>
<head>
<script src="jquery1.9.1.js" type="text/javascript"></script>
<link rel="stylesheet" type="text/css" href="sCss.css">
</head>
<script type="text/javascript">
function hide( obj1 ) {
obj1 = document.getElementById( obj 1);
if ( document.cookie.indexOf('mycookie') == -1 ) {
document.cookie = 'mycookie = 1';
obj1.style.display = 'none';
} else {
obj1.style.display = 'block';
}
}
function show( obj2 ) {
var cookie = "test"
obj2 = document.getElementById( obj2 );
obj2.style.display = 'block';
document.cookie = 'mycookie = 1';
}
</script>
<body onload="hide('form2')">
<form id="form1" onsubmit="show('form2')">
<table id="table1" border="1" >
<tr>
<td>
<input type="text" name="txt1" id="txt1" />
</td>
<td>
<input type="submit" name="submit1" id="submit1" />
</td>
</tr>
</table>
</form>
<form id="form2">
<table id="table2" border="1" >
<tr>
<td>
<input type="text" name="txt2" id="txt2" />
</td>
<td>
<input type="submit" name="submit2" id="submit2" />
</td>
</tr>
</table>
</form>
</body>
</html>
Base on the code given. After clicking the submit button of form1, form2 appears and disappears right away.

I think you should abort the onload method of trying to do this. If you want to post to the same page maybe you should set your form to post with a query string ?submitted=true Then you could read this with JavaScript to determine if you should show your next form.
Have a look
<form id="form1" action="index.html?submitted=true" method="post" onsubmit="show('form2')">
<table id="table1" border="1" >
<tr>
<td>
<input type="text" name="txt1" id="txt1">
</td>
<td>
<input type="submit" name="submit1" id="submit1">
</td>
</tr>
</table>
</form>
See I've changed the action to reflect the current page (assuming it's index.html) and I've added a query string (?submitted=true) Once the form has been submitted you can use Javascript to parse this from the URL and show the second form.
You can create a Javascript function (taken from jquery get querystring from URL) to parse the query string for you.
// Read a page's GET URL variables and return them as an associative array.
function getUrlVars()
{
var vars = [], hash;
var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
for(var i = 0; i < hashes.length; i++)
{
hash = hashes[i].split('=');
vars.push(hash[0]);
vars[hash[0]] = hash[1];
}
return vars;
}
Now that you have this function you can make a call to the method onload or wherever you see fit and see if submitted has been set.
//Simple conditional to see if the query string 'submitted' is set to true
if(getUrlVars()["submitted"] == "true"){
//Hide Form1, Show Form2
};
While this is probably not the best method and some form of dynamic programming language would suit you better I always had fun learning and this will get you going.
Final Code:
<html>
<head>
</head>
<script type="text/javascript">
// Read a page's GET URL variables and return them as an associative array.
function getUrlVars()
{
var vars = [], hash;
var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
for(var i = 0; i < hashes.length; i++)
{
hash = hashes[i].split('=');
vars.push(hash[0]);
vars[hash[0]] = hash[1];
}
return vars;
}
function hide(obj1)
{
obj1 =document.getElementById(obj1);
obj1.style.display='none';
}
function show(obj2)
{
obj2=document.getElementById(obj2);
obj2.style.display='block';
}
function isItSubmitted(){
if(getUrlVars()["submitted"] == "true"){
hide('form1');
show('form2');
}
else{
hide('form2');
console.log('notsubmitted');
}
}
</script>
<body onload="isItSubmitted();">
<form id="form1" action="index.html?submitted=true" method="post" onsubmit="show('form2')">
<table id="table1" border="1" >
<tr>
<td>
<input type="text" name="txt1" id="txt1">
</td>
<td>
<input type="submit" name="submit1" id="submit1">
</td>
</tr>
</table>
</form>
<form id="form2">
<table id="table2" border="1" >
<tr>
<td>
<input type="text" name="txt2" id="txt2">
</td>
<td>
<input type="submit" name="submit2" id="submit2">
</td>
</tr>
</table>
</form>
</body>
</html>

Related

Don't send form data when to type no in confirm window

Type apple in the input whose name is goods,and type 9 in the input whose name is price,and click submit,now confirm window pop up,whatever your click yes or no,the data will send to price.php.
My expectation:
when you click yes ,the data will send to price.php,
when you click no ,the data will not send to price.php,what's wrong for my js?
ob = document.getElementById("submit");
function check(){
if(document.getElementById("price").value < 10){
var flag = window.confirm(" are your sure the price is less than 10 ?");
if(flag){
return true;
}else{
exit;
}
}
}
ob.addEventListener("click",check,false);
<form action="price.php" method="post">
<table>
<tr>
<td>goods</td>
<td><input type="text" name="goods"></td>
</tr>
<tr>
<td>price</td>
<td><input type="text" id="price" name="price"></td>
</tr>
<tr><td colspan=2><input type="submit" id="submit" value="submit"></td></tr>
</table>
</form>
The price.php is simple.
<?php
var_dump($_POST);
?>
The exit below can't prevent form data from sending to price.php.
if(flag){
return true;
}else{
exit;
}
It is no use either to change exit; into return false;.
It is no use either to change js into below.
ob = document.getElementById("submit");
function check(){
if(document.getElementById("price").value < 10){
var flag = window.confirm(" are your sure the price is less than 10 ?");
if(flag){
return true;
}else{
exit;
}
}
}
ob.addEventListener("submit",check,false);
The traditional way is same as The KNVB did,the key point is <form action="price.php" method="post" onsubmit="return check()"> ,to bind form's attribute onsubmit with function check.
DOM0 level event way,almost the same like the traditional way.
<html>
<body>
<form action="price.php" method="post" id="form">
<table>
<tr>
<td>goods</td>
<td><input type="text" name="goods"></td>
</tr>
<tr>
<td>price</td>
<td><input type="text" id="price" name="price"></td>
</tr>
<tr><td colspan=2><input type="submit" id="submit" value="submit"></td></tr>
</table>
</form>
<script>
var ob = document.getElementById('submit');
ob.onclick =function(){
if(document.getElementById("price").value < 10){
var flag = window.confirm(" are your sure the price is less than 10 ?");
if(flag){
return true;
}else{
return false;
}
}
}
</script>
</body>
</html>
What OP expect is the DOM2 level event way.
<html>
<body>
<form action="price.php" method="post" id="form">
<table>
<tr>
<td>goods</td>
<td><input type="text" name="goods"></td>
</tr>
<tr>
<td>price</td>
<td><input type="text" id="price" name="price"></td>
</tr>
<tr><td colspan=2><input type="submit" id="submit" value="submit"></td></tr>
</table>
</form>
<script>
var ob = document.getElementById('submit');
function check(event){
console.log(ob.type);
if(document.getElementById("price").value < 10){
var flag = window.confirm(" are your sure the price is less than 10 ?");
if(flag){
ob.submit();
return true;
}else{
event.preventDefault();
return false;
}
}
}
ob.addEventListener("click",check);
</script>
</body>
</html>
The key points in DOM2 level event way are:
1.when flag is true
if(flag){
ob.submit();
return true;
}
2.when flag is false
else{
event.preventDefault();
return false;
}
This is my solution:
<html>
<body>
<form action="price.php" method="post" onsubmit="return check()">
<table>
<tr>
<td>goods</td>
<td><input type="text" name="goods"></td>
</tr>
<tr>
<td>price</td>
<td><input type="text" id="price" name="price"></td>
</tr>
<tr><td colspan=2><input type="submit" id="submit" value="submit"></td></tr>
</table>
</form>
<script>
function check()
{
if(document.getElementById("price").value < 10){
var flag = window.confirm(" are your sure the price is less than 10 ?");
if(flag){
return true;
}else{
return false;
}
}
}
</script>
</body>
</html>
I tested it on Edge, IE11, Firefox, chrome browser, it works.
I found another solution:
<html>
<body>
<form action="price.php" method="post" id="form">
<table>
<tr>
<td>goods</td>
<td><input type="text" name="goods"></td>
</tr>
<tr>
<td>price</td>
<td><input type="text" id="price" name="price"></td>
</tr>
<tr><td colspan=2><input type="submit" id="submit" value="submit"></td></tr>
</table>
</form>
<script>
var ob = document.getElementById('form');
function check(event){
if(document.getElementById("price").value < 10){
var flag = window.confirm(" are your sure the price is less than 10 ?");
if(flag){
ob.submit();
return true;
}else{
event.preventDefault();
return false;
}
}
}
ob.addEventListener("submit",check);
</script>
</body>
</html>
A couple of things about the code:
exit - I've never seen before - is it javascript?
document.getElementById('price').value - returns a string - you should parse it (to a number) before comparing.
Use onsubmit="" attribute of the form - return true to allow form submission, false to block submission.
window.confirm already returns a boolean, just return that (instead of if statement).
Here's a bare-bones example:
function validate() {
const price = parseFloat(document.getElementById('price').value)
if (price < 10) {
return window.confirm("Are your sure the price is less than 10 ?")
}
return true // <- otherwise allow form submission
}
<form action="price.php" method="post" onsubmit="return validate()">
<input type="text" id="price" name="price">
<input type="submit" id="submit" value="submit">
</form>
Also, in general, try to condense your problem to the minimum code required to reproduce an issue.

I want to submit data from form to table using onclick button in Javascript

<html>
<head>
<title>Student form</title>
</head>
<body>
<div id="data">
Form : having 4 fields and 1 button to add data to table.
<form align="center"><h3><b>Student Form</b></h3><br>
name : <input type="text" id="Name"><br><br>
branch : <input type="text" id="branch"><br><br>
address : <input type="text" id="address"><br><br>
contact : <input type="text" id="contact"><br><br>
<button onclick="AddData()">Add</button>
</form>
</div>
<div id="tab">
<table id="list" cellspacing="3" cellpadding="3" border="1"><thead>
<tr>
<td>Name</td><td>Branch</td><td>Address</td><td>Contact</td>
</tr></thead>
<tbody></tbody></table>
</div>
Script : AddData() function submits data from form to the table and is invoked when button is clicked.
<script>
function AddData()
{
var rows="";
var name=document.getElementById("Name").value;
var branch=document.getElementById("branch").value;
var address=document.getElementById("address").value;
var contact=document.getElementById("contact").value;
rows+="<tr><td>"+name+"</td><td>"+branch+"</td><td>"+address+"</td>
<td>"+contact+"</td></tr>";
$(rows).appendTo("#list tbody");
}
</script>
</body>
</html>
Consider without jQuery. Change the "Add" button to type button (it's submit by default) so it doesn't submit the form. Then use DOM features to get the elements and their values, and to build the new row.
Be careful though, as a return in any of the inputs will submit the form so you may want to add a submit listener and prevent that, or use inputs without a form.
function addData(el) {
var table = document.getElementById('list');
var tr = table.insertRow();
el.form.querySelectorAll('input').forEach(function(el) {
var cell = tr.appendChild(document.createElement('td'));
cell.textContent = el.value;
});
}
<form align="center">
<h3><b>Student Form</b></h3><br> name : <input type="text" id="Name"><br><br> branch : <input type="text" id="branch"><br><br> address : <input type="text" id="address"><br><br> contact : <input type="text" id="contact"><br><br>
<button type="button" onclick="addData(this)">Add</button>
</form>
</div>
<div id="tab">
<table id="list" cellspacing="3" cellpadding="3" border="1">
<thead>
<tr>
<td>Name<td>Branch<td>Address<td>Contact
</tr>
</thead>
</table>
The only "modern" feature above is the use of forEach with a NodeList, and that can be replaced fairly easily with a for loop or [].forEach.call(...) to get compatibility back to IE 8.
Try this .
Add the query library link appentTo() its a jquery Object
Change the button type with submit
You need return the onsubmit for prevent the page refresh otherwise page was reloaded on every time submit
function AddData() {
var rows = "";
var name = document.getElementById("Name").value;
var branch = document.getElementById("branch").value;
var address = document.getElementById("address").value;
var contact = document.getElementById("contact").value;
rows += "<tr><td>" + name + "</td><td>" + branch + "</td><td>" + address + "</td><td> " + contact + "</td></tr> ";
$(rows).appendTo("#list tbody");
return false;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="data">
<form align="center" onsubmit="return AddData()">
<h3><b>Student Form</b></h3><br> name : <input type="text" id="Name"><br><br> branch : <input type="text" id="branch"><br><br> address : <input type="text" id="address"><br><br> contact : <input type="text" id="contact"><br><br>
<button type="submit">Add</button>
</form>
</div>
<div id="tab">
<table id="list" cellspacing="3" cellpadding="3" border="1">
<thead>
<tr>
<td>Name</td>
<td>Branch</td>
<td>Address</td>
<td>Contact</td>
</tr>
</thead>
<tbody></tbody>
</table>
</div>
you can pass event to AddDate(e) and use e.preventDefault().
<html>
<head>
<title>Student form</title>
</head>
<body>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="data">
<form align="center"><h3><b>Student Form</b></h3><br>
name : <input type="text" id="Name"><br><br>
branch : <input type="text" id="branch"><br><br>
address : <input type="text" id="address"><br><br>
contact : <input type="text" id="contact"><br><br>
<button onclick="AddData(event)">Add</button>
</form>
</div>
<div id="tab">
<table id="list" cellspacing="3" cellpadding="3" border="1"><thead>
<tr>
<td>Name</td><td>Branch</td><td>Address</td><td>Contact</td>
</tr></thead>
<tbody></tbody></table>
</div>
<script>
function AddData(e)
{
e.preventDefault();
var rows="";
var name=document.getElementById("Name").value;
var branch=document.getElementById("branch").value;
var address=document.getElementById("address").value;
var contact=document.getElementById("contact").value;
rows+="<tr><td>"+name+"</td><td>"+branch+"</td><td>"+address+"</td><td>"+contact+"</td></tr>";
$(rows).appendTo("#list tbody");
}
</script>
</body>
</html>

I'm trying to make text box in javascript, and to send the entered values in a textbox in a array to add them

Created textbox in javascript, need those value to pass in arrays to add them ?
how do I do that ?
I just want my code to be short and simple
I'm stuck!
Code:
<html>
<head>
<title> 2 NUM ADD VIA ARRAY </title>
</head>
<body bgcolor= "red" </body>
<script type = "text/javascript">
function sum()
{
var sum = [],i=0;
sum[i]= document.getElementById('i+1').value;
alert("sum =" + sum);
}
</script>
<table border=2>
<TR>
<TD>
<input type="text" id="1" /input>
</TD>
<TD>
<input type="text" id="2" /input>
</TD>
</TR>
</table>
<button name="btHello" onclick="sum();">sum</button>
</html>
Usage of Array in this case is not required according to me.I suggest you to do this even without using arrays. This makes your code simple and short
<html>
<head>
<title> 2 NUM ADD VIA ARRAY </title>
</head>
<body bgcolor= "red" </body>
<script type = "text/javascript">
function sum()
{
var sum= 0;
$('.textbox').each(function() {
sum += Number($(this).val());
});
alert(sum);
}
</script>
<form>
<table border=2>
<TR>
<TD>
Text 1 :<input type="text" class="textbox" id="1" />
</TD>
<TD>
Text 2 :<input type="text" class="textbox" id="2" />
</TD>
</TR>
</table>
Submit : <input type = "submit" name="btHello" onclick="sum();">
</form>
</html>
Hope my example helps. I suggest using jQuery. It makes it much easier.
function foo() {
var s = [];
$(".foo").each(function() {
s.push( $(this).val() );
});
s = s.join(" ");
alert("sum = " + s);
}
$("#btHello").on("click", function() { foo(); });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<table border=2>
<tr>
<td>
<input type="text" class="foo" /input>
</td>
<td>
<input type="text" class="foo" /input>
</td>
</tr>
</table>
<button id="btHello">sum</button>
I´m to totally sure what result you want, but this should help you on your way. If its not totally what you are after, please try to explain your goal a bit more. :)
Happy codin'
function sum()
{
var sum = [];
sum.push(document.getElementById('1').value);
sum.push(document.getElementById('2').value);
// sum of all values
totalSum = 0;
for (var i = 0; i < sum.length; i++) {
totalSum += parseInt(sum[i]);
}
alert("sum = " + totalSum);
}
<html>
<head>
<title> 2 NUM ADD VIA ARRAY </title>
</head>
<body bgcolor= "red" </body>
<table border=2>
<TR>
<TD>
<input type="text" id="1" /input>
</TD>
<TD>
<input type="text" id="2" /input>
</TD>
</TR>
</table>
<button name="btHello" onclick="sum();">sum</button>
</html>

values are automatically changed after click submit button

I have code here. There are no errors in this code, but when I was tried to execute this, the output is shown just for a fraction of second. After that, the fields are changed to null. I want all the values to be shown, even after clicking the submit button.
<script type="text/javascript">
function calcu() {
var h = parseInt(document.getElementById("height").value);
var w = parseInt(document.getElementById("weight").value);
var r = h + w;
document.getElementById("res").innerHTML = r;
if (r < 50) {
var x = document.getElementById("report");
x.innerHTML = "less 50";
}
if (r > 50) {
var xy = document.getElementById("report");
xy.innerHTML = "high 50";
}
}
<body>
<form onsubmit="calcu();">
<table>
<tr>
<td>Height:</td>
<td>
<input type="text" id="height">
</td>
</tr>
<tr>
<td>Weight:</td>
<td>
<input type="text" id="weight">
</td>
</tr>
<tr>
<td>
<input type="submit" value="CALCULATE">
</td>
<td>
<p id="res"></p>
</td>
</tr>
</table>
<p id="report">REPORT</p>
<p id="tip"></p>
</form>
Show Your Code First for more.
As much i can from your statement is that you have a button which is type submit and your values are not holding because when you click on submit type button it will post your data and find the next where it has to go in action attribute as if you have not given the action attribute (a/c to me ) so its reloading the page which refreshing the whole content that's why your page is not holding the data.
But if you want it to be hold make your button type simple "Button".
I think this will resolve your problem.
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<script type="text/javascript" >
function calcu() {
var h = parseInt(document.getElementById("height").value);
var w = parseInt(document.getElementById("weight").value);
var r = h + w;
document.getElementById("res").innerHTML = r;
if (r < 50) {
var x = document.getElementById("report");
x.innerHTML = "less 50";
}
if (r > 50) {
var xy = document.getElementById("report");
xy.innerHTML = "high 50";
}
}
</script>
</head>
<body>
<form id="form1" >
<table>
<tr>
<td>Height:</td>
<td>
<input type="text" id="height" />
</td>
</tr>
<tr>
<td>Weight:</td>
<td>
<input type="text" id="weight"/>
</td>
</tr>
<tr>
<td>
<input type="button" value="CALCULATE" onclick="calcu();" />
</td>
<td>
<p id="res"></p>
</td>
</tr>
</table>
<p id="report">REPORT</p>
<p id="tip"></p>
</form>
This will do good You are calling function on form submit which reloads the page so previous page does not exist thats why is not doing any good so your have to change your button type to button and on button click you can call the function you will get your desired result.

javascript window redirect doesn't fire up

This problem seems to be odd to me and I can't seem to fix it. I do have a simple HTML form; inside, I do have a textbox and a button as shown down here:
<form id="form1" method="get"> <!-- Note: No Action property -->
<div>
<h1>
Simple Test Form</h1>
<table border="0" width="400">
<tr>
<td align="right">
All of these words
</td>
<td>
<input name="txtAll" id="txtAll" type="text" value="testing keyword" />
</td>
</tr>
<tr>
<td colspan="2" align="center">
<input type="submit" name="Submit" value="Submit" onclick="myJS(this);" />
</td>
</tr>
</table>
</div>
</form>
MyJS file is as:
<script type="text/javascript">
function myJS(which) {
var CONSTANT_SITE_TARGET = "http://servername/redirect/target.aspx?text=";
//capture all values from the form
var allWords = document.getElementById("txtAll").value;
var morestring = ""; //More data manipulation here.....
var url = CONSTANT_SITE_TARGET + allWords + morestring;
window.open(url);
//window.location = url; //Doesn't work
//window.location.href = url; //Doesn't work
//self.location = url; //Doesn't work
//top.location = url; //Doesn't work
}
</script>
As you can see, it doesn't redirect to the designated URL in the javascript. When I use the window.open then it works. Note that in the < form... > tag, I don't put the action property in it. I don't want to open a new browser, just redirect to the new url within the same browser.
Is there a way to redirect it?
Don't use the form tags. Or, set the "type" attribute of your button to be "button", not "submit". The form submits when you click the button, but you don't want that to happen. Either removing the form or changing the button should fix improper redirection. When you don't specify an action, I'm pretty sure the default is the current URL.
Ok, just an idea. As you haven't set the action parameter, the default behaviour of a submit button is to reload the same page. You alter that behaviour by handling its onclick. Maybe there is a conflict that can be resolved by having return false; at the end of the click handler, which prevents the default action for that event.
Here
function myJS(which) {
var CONSTANT_SITE_TARGET = "http://servername/redirect/target.aspx?text=";
//capture all values from the form
var allWords = which.txtAll.value;
var morestring = ""; //More data manipulation here.....
return CONSTANT_SITE_TARGET + allWords + morestring;
}
<form id="form1" method="get" onsubmit="this.action=myJs(this)">
<div>
<h1>
Simple Test Form</h1>
<table border="0" width="400">
<tr>
<td align="right">
All of these words
</td>
<td>
<input name="txtAll" id="txtAll" type="text" value="testing keyword" />
</td>
</tr>
<tr>
<td colspan="2" align="center">
<input type="submit" name="Submit" value="Submit" />
</td>
</tr>
</table>
</div>
</form>
to elaborate on a comment:
<script>
window.onload=function() {
document.getElementById("Submit").onclick=function() {
var CONSTANT_SITE_TARGET = "http://servername/redirect/target.aspx?text=";
//capture all values from the form
var allWords = document.getElementById("txtAll".value;
var morestring = ""; //More data manipulation here.....
location = CONSTANT_SITE_TARGET + allWords + morestring;
}
}
</script>
<div>
<h1>
Simple Test Form</h1>
<table border="0" width="400">
<tr>
<td align="right">
All of these words
</td>
<td>
<input name="txtAll" id="txtAll" type="text" value="testing keyword" />
</td>
</tr>
<tr>
<td colspan="2" align="center">
<input type="button" id="Submit" value="Submit" />
</td>
</tr>
</table>
</div>
Try one the options for redirection below. I commented out three of them so that the code stays valid, but you may play around with either and see if it suits your needs.
var CONSTANT_SITE_TARGET = "http://servername/redirect/target.aspx?text=";
//capture all values from the form
var allWords = document.getElementById("txtAll").value;
var morestring = ""; //More data manipulation here.....
var url = CONSTANT_SITE_TARGET + allWords + morestring;
window.location.href= url;
//window.navigate(url);
//self.location(url);
//top.location(url);

Categories