So i am trying to make a function that searches trough an xml file, my results are given but the page is refreshed and keeps loading. I figured this was because of a submit but i used return false and i still have the same problem. Can anyone help me?
Below is my code
<script type="text/javascript">
function loadXMLDoc(XMLname)
{
var xmlDoc;
if (window.XMLHttpRequest)
{
xmlDoc=new window.XMLHttpRequest();
xmlDoc.open("GET",XMLname,false);
xmlDoc.send("");
return xmlDoc.responseXML;
}
else if (ActiveXObject("Microsoft.XMLDOM"))
{
xmlDoc=new ActiveXObject("Microsoft.XMLDOM");
xmlDoc.async=false;
xmlDoc.load(XMLname);
return xmlDoc;
}
alert("Error loading document!");
return null;
}
</script>
</head>
<body>
<form id="oForm" name="oForm" onsubmit="search(); return false">
<input type="text" name="name" id="txt_name" size="30" maxlength="70">
<input type="submit" value="klik" onclick="search()"/>
</form>
<script type="text/javascript">
function search(){
name = document.oForm.name.value.toLowerCase();
xmlDoc=loadXMLDoc("data.xml");
var nodeList = xmlDoc.getElementsByTagName("article");
for (var i = 0; i < nodeList.length; i++) {
var titleNode = nodeList[i];
if(titleNode.getElementsByTagName("title")[0].childNodes[0].nodeValue.toLowerCase() == name){
document.write("<div style='width:450px;'>")
document.write("<p>"+titleNode.getElementsByTagName("title")[0].childNodes[0].nodeValue+"</p>");
document.write("<p>"+titleNode.getElementsByTagName("description")[0].childNodes[0].nodeValue+"</p>");
document.write("<p>"+titleNode.getElementsByTagName("urltext")[0].childNodes[0].nodeValue+"</p>");
document.write("</div>")
}
}
}
</script>
I would like to repeat that i do get results i only lose my layout and the page keeps loading. I made this for safari/safari mobile so i would apreciate it if someone could present a solution. I cant use any serversided scripts either since i need to be able to cache this offline so i figure it has to be javascript.
Ty in advance
EDIT
<input type="text" name="name" id="txt_name" size="30" maxlength="70">
<input type="button" value="klik" onclick="search();"/>
name = GetElementById("txt_name").value.toLowerCase();
Assuming the xml processing code works, do it like this - document.write WIPES the page
PS: Firefox MAY not work as expected due to linefeeds in the XML:
<html>
<head>
<script type="text/javascript">
function loadXMLDoc(XMLname) {
var xmlDoc;
if (window.XMLHttpRequest) {
xmlDoc=new window.XMLHttpRequest();
xmlDoc.open("GET",XMLname,false);
xmlDoc.send("");
return xmlDoc.responseXML;
}
else if (ActiveXObject("Microsoft.XMLDOM")) {
xmlDoc=new ActiveXObject("Microsoft.XMLDOM");
xmlDoc.async=false;
xmlDoc.load(XMLname);
return xmlDoc;
}
alert("Error loading document!");
return null;
}
var xmlDoc=loadXMLDoc("data.xml");
var nodeList = xmlDoc.getElementsByTagName("article");
function search(theForm) {
var name = theForm.myname.value.toLowerCase();
var html = "";
for (var i = 0; i < nodeList.length; i++) {
var titleNode = nodeList[i];
if (titleNode.getElementsByTagName("title")[0].childNodes[0].nodeValue.toLowerCase() == name) {
html += "<div style='width:450px;'>";
html += "<p>"+titleNode.getElementsByTagName("title")[0].childNodes[0].nodeValue+"</p>";
html += "<p>"+titleNode.getElementsByTagName("description")[0].childNodes[0].nodeValue+"</p>";
html += "<p>"+titleNode.getElementsByTagName("urltext")[0].childNodes[0].nodeValue+"</p>";
html+= "</div>";
document.getElementById("result").innerHTML=html
}
}
return false; // cancel the submit
}
</script>
</head>
<body>
<form id="oForm" name="oForm" onsubmit="return search(this)">
<input type="text" name="myname" id="txt_name" size="30" maxlength="70">
<input type="submit" value="klik"/>
</form>
<div id="result"></div>
</body>
</html>
try this:
<input type="submit" value="klik" onclick="return search()"/>
and in the search method:
function search() {
.....
return false;
}
EDIT 1:
you can also add an event for the form itself:
<form onsubmit="return false">
(http://www.w3schools.com/jsref/event_form_onsubmit.asp)
EDIT 2:
This works for me:
<form onsubmit="return false">
<input type="submit" value="Go" onclick="alert('yo');"/>
</form>
Related
How would I fix,"Expected End Of Statement" in the code below?
<script type="text/javascript">
function substitute() {
var myValue = document.getElementById('myTextBox').value;
if (myValue.length === 0) {
alert('Please enter a real value in the text box!');
return;
}
var myTitle = document.getElementById('title');
myTitle.innerHTML = myValue;
}
</script>
It keeps telling me line 57 which is this line:
<input type="submit" value="Click Me" onClick="substitute();">
Here is the complete HTA link:
http://pastebin.com/fMg5e4RN
Use <form onsubmit="return substitute()" and return true or false depending on validation. Remove type="javascript" or fix it as text/javascript
<script type="text/javascript">
function substitute() {
var myValue = document.getElementById('myTextBox').value;
if (myValue.length === 0) {
alert('Please enter a real value in the text box!');
return false;
}
// not sure what the following two lines are for
var myTitle = document.getElementById('title');
myTitle.innerHTML = myValue;
return true; // allow submit
}
</script>
and use
<form action="some action" onsubmit="return substitute();">
<input type="text" id="myTextBox"/>
<input type="submit" value="Click Me" />
</form>
The following code works as per my requirement in firefox. but coming to IE 8, except file browsing nothing happening. Can any one check it out for issues pls?any thing need to add in the first line?
thanks in advance.
the code is
<!DOCTYPE html>
<html>
<head>
<script>
function loadfile(input) {
var theRange = null;
var reader = new FileReader();
reader.onload = function(e) {
document.getElementById('mytext').value = e.target.result;
var msg = e.target.result;
}
reader.readAsText(input.files[0]);
}
</script>
<script type="text/javascript">
function check1()
{
var str = document.getElementById('mytext').value;
var names=document.getElementById('username').value ;
var n = str.search(names);
if(n==-1)
{
alert("not found");
}
else
{
alert("user name found");
var str1 = document.getElementById('mytext').value;
var str_array = str1.split(',');
var ind = str_array.indexOf(names);
//alert("I worked");
var kname = str_array[ind];
alert(kname);
var i=0;
for (i = ind; i< ind+8; i++ )
{
k=0;
}
var print = str_array[i];
var print_array = print.split('\n');
alert(print_array[0]);
}
}
</script>
</head>
<body>
Select the file to display:
<input type="file" onchange="loadfile(this)">
<br></br>
<textarea rows="20" cols="100" id="mytext"></textarea>
<br></br>
<form> Enter UserName: <input type="text" id="username" name="username"> <b></form>
<br></br>
<input type="button" onclick="check1();" value="Search" />
<pre id="output"></pre>
</body>
</html>
IE8 does not have support for FileReader.
A great site to find out if a browser supports certain features or not is http://caniuse.com/
In your case you could've searched for: http://caniuse.com/#search=filereader
i have a simple javascript i use to feed a DIV with content from a script using AJAX. This happens only after the user clicks a button. What i want after the user pressed the button (once) and the DIV is filled with de output of the script:
disable the button
have the DIV to reload the script's output every 5 seconds using AJAX
< script language="Javascript">
function xmlhttpPost(strURL) {
var xmlHttpReq = false;
var self = this;
// Mozilla/Safari
if (window.XMLHttpRequest) {
self.xmlHttpReq = new XMLHttpRequest();
}
// IE
else if (window.ActiveXObject) {
self.xmlHttpReq = new ActiveXObject("Microsoft.XMLHTTP");
}
self.xmlHttpReq.open('POST', strURL, true);
self.xmlHttpReq.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
self.xmlHttpReq.onreadystatechange = function() {
if (self.xmlHttpReq.readyState == 4) {
updatepage(self.xmlHttpReq.responseText);
}
}
self.xmlHttpReq.send(getquerystring());
}
function getquerystring() {
var form = document.forms['f1'];
var xword = form.xword.value;
qstr = 'addpost=' + escape(xword); // NOTE: no '?' before querystring
return qstr;
}
function updatepage(str){
document.getElementById("result").innerHTML = str;
}
</script>
<form name="f1">
<input name="xword" type="hidden" value="someword">
<input value="betaling gereed" type="button" name="btn" onclick='JavaScript:xmlhttpPost("script.php")'></p>
<div id="result"></div>
</form>
use setTimeout() javascript method as follows:
setTimeout ('xmlhttpPost("script.php")', 5000);
At the end of your updatepage() method, call this.
For example:
function updatepage(str){
document.getElementById("result").innerHTML = str;
setTimeout ('xmlhttpPost("script.php")', 5000);
}
To disable the button, you will need to add an id attribute to your button tag. Then you can disable like so:
document.getElementById('btn').disable();
To repeat the ajax call indefinitely:
var refresh = false,
btn = document.getElementById("btn");
btn.onclick = function(){
refresh = true;
this.disable();
fetchData("script.php");
}
function fetchData(strURL){
while(refresh){
setTimeout(xmlhttpPost(strURL), 5000);
}
}
And:
<form name="f1">
<input name="xword" type="hidden" value="someword">
<input value="betaling gereed" type="button" id="btn" name="btn"></p>
<div id="result"></div>
</form>
You are looking for JS Time Events?
w3shools jvascript time events
onclick="setInterval(func(), 5000)"
ok Edit:
i didnt test it, is to late
<input id="loadStuffButton" value="betaling gereed" type="button" name="btn" onclick='setInterval(xmlhttpPost("script.php"), 5000);'></p>
function xmlhttpPost(strURL) {
document.getElementById('loadStuffButton').disabled = true;
....
}
Edit 2: Test This
Quick and dirty without Ajax to show how setIntervalworks with 5 ms hehe
<form name="f1">
<input name="xword" type="hidden" value="someword">
<input id="loadStuffButton" value="betaling gereed" type="button" name="btn" onclick='setInterval(function(){xmlhttpPost("script.php")}, 500);'></p>
<div id="result">
test
</div>
</form>
<script>
i = 1;
function xmlhttpPost(strURL) {
document.getElementById('loadStuffButton').disabled = true;
updatepage(i++);
}
function updatepage(str){
document.getElementById("result").innerHTML = str;
}
</script>
This is an assignment from my class. What I need to do is create a registration page. When the user presses the submit button, I have take all the information on the form and write it to an existing XML file using Javascript. This is done on the client side, only through HTML, Javascript, and XML. By the way, my Professor purposely did not teach us how to do this because he wants us to research on it by ourselves. Also, I'm not too familiar with Javascript, especially with the built in functions, if possible please explain what each line or method of code is doing.
Let me begin, here's how my existing XML looks like:
<?xml version ="1.0" encoding="utf-8" ?>
<!--GGFGFGFVBFVVVHVBV-->
<PersonInfo>
<Person Usrname="Bob111" Pswd="Smith111" personid="111" FirstName="Bob" LastName="Smith" DOB="01/01/1960" Gender="M" Title="Hello1">
</Person>
<!-- several more lines of <person> here -->
</PersonInfo>
When saving the form data, it has to follow all the layout within , basically I would need Usrname, Pswd, personid, and so on.
Basically, from what I understand, I have to create the XML line "Person" from my registration page once I press submit. Then push it to the array that already have my XML information, then write over my XML document with the information on the array. My problem is, I have exactly no idea how to do that.
For those who wants to know how my registration page looks like, here it is:
<html>
<head>
<title>Registration</title>
<link rel="stylesheet" type="text/css" href="CSS_LABs.css" />
</head>
<body>
<div class="form">
<form id="Registration" action="" method="get">
Username:<input type="text" name="usrname" maxlength="10"/> <br/>
Password:<input type="password" name="pswd" maxlength="20"/> <br/>
<hr>
PersonID:<input type="text" name="PID" /> <br>
<hr>
First Name:<input type="text" name="fname"/> <br>
Last Name:<input type="text" name="lname"/>
<hr>
DOB:<input type="text" name="dob" /> <br>
<hr>
Gender:<input type="text" name="sex" /> <br>
<hr>
Title:<input type="text" name="title" /> <br>
<hr>
Secret Question:<br>
<select name="secret?">
</select> <br>
Answer:<input type="text" name="answer" /> <br> <br>
<input type="submit" value="submit" />
</form>
</div>
</body>
</html>
By the way, I know certain information on my HTML document may not be worded properly, so do hope you guys don't mind. Also, I would also have to fix up my XML later by putting the answer to the secret question within later.
Alright, thanks a lot in advance guys.
UPDATE!!!
Here we go, I finally figured out how to create an XML document with Javascript, here's the code:
var xmlDoc = new ActiveXObject("Microsoft.XMLDOM");
var fso = new ActiveXObject("Scripting.FileSystemObject");
var FILENAME = 'G:\\CST2309 - Web Programming 1\\Copy of Take Home Exam - Copy\\PersonXML2.xml';
function SaveXML(UserData)
{
var file = fso.CreateTextFile(FILENAME, true);
file.WriteLine('<?xml version="1.0" encoding="utf-8"?>\n');
file.WriteLine('<PersonInfo>\n');
for (countr = 0; countr < UserData.length; countr++) {
file.Write(' <Person ');
file.Write('Usrname="' + UserData[countr][0] + '" ');
file.Write('Pswd="' + UserData[countr][1] + '" ');
file.Write('PersonID="' + UserData[countr][2] + '" ');
file.Write('FirstName="' + UserData[countr][3] + '" ');
file.Write('LastName="' + UserData[countr][4] + '" ');
file.Write('Gender="' + UserData[countr][5] + '" ');
file.Write('DOB="' + UserData[countr][6] + '" ');
file.Write('Title="' + UserData[countr][7] + '"');
file.WriteLine('></Person>\n');
} // end for countr
file.WriteLine('</PersonInfo>\n');
file.Close();
} // end SaveXML function --------------------
function LoadXML(xmlFile)
{
xmlDoc.load(xmlFile);
return xmlDoc.documentElement;
} //end function LoadXML()
function initialize_array()
{
var person = new Array();
var noFile = true;
var xmlObj;
if (fso.FileExists(FILENAME))
{
xmlObj = LoadXML(FILENAME);
noFile = false;
} // if
else
{
xmlObj = LoadXML("PersonXML.xml");
//alert("local" + xmlObj);
} // end if
var usrCount = 0;
while (usrCount < xmlObj.childNodes.length)
{
var tmpUsrs = new Array(xmlObj.childNodes(usrCount).getAttribute("Usrname"),
xmlObj.childNodes(usrCount).getAttribute("Pswd"),
xmlObj.childNodes(usrCount).getAttribute("PersonID"),
xmlObj.childNodes(usrCount).getAttribute("FirstName"),
xmlObj.childNodes(usrCount).getAttribute("LastName"),
xmlObj.childNodes(usrCount).getAttribute("Gender"),
xmlObj.childNodes(usrCount).getAttribute("DOB"),
xmlObj.childNodes(usrCount).getAttribute("Title"));
person.push(tmpUsrs);
usrCount++;
} //end while
if (noFile == false)
fso.DeleteFile(FILENAME);
SaveXML(person);
} // end function initialize_array()
What this code here is doing is that, it takes my original XML file and loads it up into an array so it can create a new XML file. Basically I got the creating the XML file part down, but still need help with the rest of my stuff.
My goal is trying to take my form data and push it into my existing array, not overwrite it, add to it, so I can update my existing XML file with the new registration information. This is where I have absolutely no idea how to do. Some pointers would be nice.
By the way, my Professor purposely did not teach us how to do this because he wants us to research on it by ourselves.
Which should give you a hint about searching a bit more deeply. Anyhow, I'm not going to comment on every line, but I will offer some hints.
var xmlDoc = new ActiveXObject("Microsoft.XMLDOM");
That is a Microsoft proprietary way of creating an XML document and it is normally wrapped in try..catch as different ActiveXObjects are provided in different versions of IE. You also need to look for document.implementation.createDocument.
//DEFINE LOAD METHOD
function LoadXML(xmlFile)
{
xmlDoc.load(xmlFile);
You might want to check out the async parameter.
xmlObj = xmlDoc.documentElement;
}
//declare & initialize array
var arrPerson = new Array();
It is considered better practice to use an array literal: ... = [];
//initialize array w/ xml
function initialize_array()
{
LoadXML("PersonXML.xml");
var x = 0;
while (x < xmlObj.childNodes.length)
Getting the length of xmlObj.childNodes on every loop is inefficient, consider storing the length and comparing with that value.
{
var tmpArr = new Array(xmlObj.childNodes(x).getAttribute("Usrname"),
xmlObj.childNodes(x).getAttribute("Pswd"),
xmlObj.childNodes(x).getAttribute("FirstName"),
xmlObj.childNodes(x).getAttribute("LastName"),
xmlObj.childNodes(x).getAttribute("DOB"),
xmlObj.childNodes(x).getAttribute("Gender"),
xmlObj.childNodes(x).getAttribute("Title"));
It is very inefficient to access xmlObj.childNodes(x) repeatedly. Store a reference and reuse it.
arrPerson.push(tmpArr);
You could assign the values directly to arrPerson and get rid of tmpArr.
x++;
Using a plain for loop will increment x for you.
}
}
//Validation
function LogInVal(objtxt)
{
if(objtxt.value.length == 0)
{
objtxt.style.background = "red";
return 1;
}
else
{
objtxt.style.background = "white";
return 0;
}
}
Not all browsers will let you style the background color of input elements.
//main validation
function MainVal(objForm)
{
var errmsg = "empty field";
var errmsg2 = "Incorrect Username and Password";
You might want a better way of naming the error messages and relating them to other information for that message. An object might do the job.
var msg = "You have logged in successfully";
var errCount = 0;
var usrn = document.getElementById("usrname1").value;
var pswd = document.getElementById("pswd1").value;
errCount += LogInVal(objForm.usrname);
errCount/*1*/ += LogInVal(objForm.pswd);
initialize_array();
if (errCount != 0)
{
alert(errmsg);
return false;
}
else if(authentication(usrn, pswd) == true)
The function authentication() returns true or false, so you don't need to compare it to anything, you can just test the returned value (i.e. there is no need for == true above).
{
alert(msg);
return true;
setCookie('invalidUsr',' ttttt');
}
else
{
alert(errmsg2);
return false;
}
}
Instead of showing alert messages one at a time in an alert, consider putting them in the document adjacent to the elements they relate to. That way the user can see the messaeg while fixing the error.
Isn't it cheating to ask us? Your implementation will probably only work in IE, I'd recommend using jQuery as it is impressively powerful at parsing XML.
I'm not sure why he wants you to write out XML as it's not very intuitive coming from JavaScript. You can do something like this via jQuery
//I capture form submitevent
$('form').submit(function( ev ){
ev.preventDefault(); //I keep form from submitting
$( xmlDocument ).find('Person').attr({
username: $("input[name=usrname]),
password: $("input[name=pswd]),
//and so on
});
});
It's up to you on how you 'report' this xml file
Here i am sharing my experience in writing html form data to xml.
Create one html file in one location (D:\\HtmlToXml.html).
And open it with Internet Explorer.
Then after provide information and click on submit button, then one file is created in the same directory with name example.xml.
If once an xml is created, then next time onwards on submit button click data will append to same xml file.
<!DOCTYPE html>
<html>
<head>
<title>Display Emp Details</title>
<script type="text/javascript" language="javascript">
var xmlDoc = new ActiveXObject("Microsoft.XMLDOM");
var fso = new ActiveXObject("Scripting.FileSystemObject");
var FILENAME='D:\\example.xml';
function SaveXMLData()
{
validations();
}
function createfile()
{
var file;
var e1=document.getElementById('empName').value;
var p1=document.getElementById('empNumber').value;
var em1=document.getElementById('empEmail').value;
var d1=document.getElementById('empDate').value;
var tablemain = document.getElementById('tblmain');
if(fso.fileExists(FILENAME))
{
xmlDoc.load(FILENAME);
var lng;
lng=xmlDoc.getElementsByTagName("Details");
var xmlread= fso.OpenTextFile(FILENAME,1,true,0);
var x=xmlread.readAll();
var replace=x.replace('</Emp>','');
var sno=lng.length + 1;
file=fso.OpenTextFile(FILENAME,2,true);
file.writeLine(replace);
file.WriteLine('<Details category="'+sno+'">');
file.WriteLine('<SNo>'+sno+'</SNo>');
file.WriteLine('<Name>'+e1+'</Name>');
file.WriteLine('<PhoneNumber>'+p1+'</PhoneNumber>');
file.WriteLine('<Emailid>'+em1+'</Emailid>');
file.WriteLine('<Date>'+d1+'</Date>');
file.WriteLine('</Details>');
file.WriteLine('</Emp>');
alert('another file updated');
}
else
{
file= fso.CreateTextFile(FILENAME, true);
file.WriteLine('<?xml version="1.0" encoding="utf-8" ?>');
file.WriteLine('<?xml-stylesheet type="text/xsl" href="cdcatalog.xsl"?>');
file.WriteLine('<Emp>');
file.WriteLine('<Details category="1">');
file.WriteLine('<SNo>'+1+'</SNo>');
file.WriteLine('<Name>'+e1+'</Name>');
file.WriteLine('<PhoneNumber>'+p1+'</PhoneNumber>');
file.WriteLine('<Emailid>'+em1+'</Emailid>');
file.WriteLine('<Date>'+d1+'</Date>');
file.WriteLine('</Details>');
file.WriteLine('</Emp>');
alert('file updated');
}
<!-- displayData();-->
document.getElementById('empName').value='';
document.getElementById('empNumber').value='';
document.getElementById('empEmail').value='';
document.getElementById('empDate').value='';
addRow('tablemain');
file.close();
}
function validations()
{
var emp1=document.getElementById('empName').value;
var letters = /^[\s A-Za-z]+$/;
if(emp1!="")
{
if(emp1.match(letters))
{
allnumeric();
}
else
{
alert('Please input alphabet characters only');
return false;
}
}
else
{
alert('Please Enter Name.');
}
}
<!--For checking Email-->
function checkemail()
{
var email = document.getElementById('empEmail');
var filter = /^([a-zA-Z0-9_\.\-])+\#(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
if(email.value!="")
{
if (!filter.test(email.value))
{
alert('Please provide a valid email address');
return false;
}
else
{
DateValidation();
}
}
else
{
alert('Please Enter Email.');
}
}
<!--For checking Date Format-->
function DateValidation()
{
var date=/^(0?[1-9]|[12][0-9]|3[01])[\/\-](0?[1-9]|1[012])[\/\-]\d{2,4}$/;
var empDate=document.getElementById("empDate");
if(empDate.value!="")
{
if(empDate.value.match(date))
{
createfile();
}
else
{
alert("Please provide valid date : DD-MM-YY(YYYY)");
return(false);
}
}
else
{
alert('Please Enter Date.');
}
}
<!--For checking phone number-->
function allnumeric()
{
var numbers=/^\d{10}$/;
var empNumber=document.getElementById("empNumber");
if(empNumber.value!="")
{
if(empNumber.value.length=="10")
{
if(empNumber.value.match(numbers))
{
checkemail();
}
else
{
alert("Phone number should be numeric");
return(false);
}
}
else
{
alert('Phone Number should be like: 9876543210');
}
}
else
{
alert('Please Enter Phone Number.');
}
}
function addRow(id)
{
if(fso.fileExists(FILENAME))
{
xmlDoc.load(FILENAME);
var x;
x=xmlDoc.getElementsByTagName("Details");
var table = document.getElementById('tbl');
var nxtbtn= document.getElementById("btnnext");
var prvbtn=document.getElementById("btnprev");
nxtbtn.disabled=true;
prvbtn.disabled=true;
if(x.length >5)
{
nxtbtn.disabled=false;
}
var j=0;k=5;
if(k>x.length)
{k=x.length;}
var store=document.getElementById("txtstore");
var maxval=document.getElementById("txtmax");
if(id=="btnprev")
{
if((store.value % k)==0)
{
store.value = store.value - k ;
if(store.value>0)
{
j = parseInt(store.value);
k += parseInt(store.value);
}
}
else
{
store.value =store.value - (store.value % k) ;
if(store.value >0)
{
j = store.value - k;
k = store.value;
}
}
if(j > 0)
{
prvbtn.disabled=false;
}
}
if(id=="btnnext")
{
if(store.value==0)
{
store.value=table.rows.length;
}
else if(store.value <0)
{
store.value=maxval.value;
}
prvbtn.disabled=false;
if(store.value >=k)
{
j +=parseInt(store.value);
k +=parseInt(store.value);
if(k >= x.length)
{
k=x.length;
nxtbtn.disabled = true;
prvbtn.disabled = false;
}
}
}
table.innerHTML = "";
var rowCount = 0;
for (i=j;i<k;i++)
{
var row = table.insertRow(rowCount);
var cell1 = row.insertCell(0);
var element1 = document.createElement("input");
element1.type = "checkbox";
element1.id = "id2" ;
cell1.appendChild(element1);
// Create label
var label = document.createElement("label");
label.htmlFor = "id2" ;
cell1.appendChild(label);
var cell2 = row.insertCell(1);
cell2.innerHTML = x[i].getElementsByTagName("SNo")[0].childNodes[0].nodeValue;
var name = row.insertCell(2);
var elname =document.createElement("input");
elname.type = "text";
elname.readOnly=true;
elname.value=x[i].getElementsByTagName("Name")[0].childNodes[0].nodeValue;
name.appendChild(elname);
var phnno = row.insertCell(3);
var elphn =document.createElement("input");
elphn.type = "text";
elphn.readOnly=true;
elphn.value=x[i].getElementsByTagName("PhoneNumber")[0].childNodes[0].nodeValue;
phnno.appendChild(elphn);
var email = row.insertCell(4);
var elemail =document.createElement("input");
elemail.type = "text";
elemail.readOnly=true;
elemail.value=x[i].getElementsByTagName("Emailid")[0].childNodes[0].nodeValue;
email.appendChild(elemail);
var date = row.insertCell(5);
var eldate =document.createElement("input");
eldate.type = "text";
eldate.readOnly=true;
eldate.value=x[i].getElementsByTagName("Date")[0].childNodes[0].nodeValue;
date.appendChild(eldate);
rowCount +=1;
}
maxval.value=x[table.rows.length - 1].getElementsByTagName("SNo")[0].childNodes[0].nodeValue;
if(id=="btnprev")
{
store.value =store.value - 5;
}
else
{
store.value =parseInt(k);
}
}
}
</script>
</head>
<body onload="addRow('tbl')">
<form id="empForm" action="" method="get">
<p><b>Emp Registration:</b></p>
<table>
<tr>
<td>Name:</td>
<td><input type="text" id="empName" maxlength="25"/></td>
</tr>
<tr>
<td>Phone Number:</td>
<td><input type="text" id="empNumber" maxlength="10"/></td>
</tr>
<tr>
<td>EmailId:</td>
<td><input type="text" id="empEmail"/></td>
</tr>
<tr>
<td>Date:</td>
<td><input type="text" id="empDate" maxlength="10"/></td>
</tr>
<tr>
<td align="center">
<input type="button" value="Submit" onclick="SaveXMLData()"/></td>
<td>
<input type="button" value="Show Data" id="show" onclick="displayData(this.id)" style="display:none;"/></td>
</tr>
</table>
<!-- <table><tr><td><input type="button" onclick="displayData(this.id)" value="Prev" id="prev" disabled="disabled"></td>
<td><input type="button" onclick="displayData(this.id)" value="Next" id="next" disabled="disabled"></td></tr></table> -->
<div id='displaydatadiv'>
</div>
<!-- <INPUT type="button" value="Add Row" onclick="addRow('tbl')" /> -->
<div style="height: 135px; width:650px; background-color: Lavender;" >
<TABLE id="tbl" width="350px">
</TABLE>
</div>
<table id="tblmain" border="1" style="display:true" ></table>
<input type="button" id="btnprev" value="Prev" onclick="addRow(this.id)" disabled="disabled">
<input type="button" id="btnnext" value="Next" onclick="addRow(this.id)" disabled="disabled">
<input type="hidden" id="txtstore" style="display:none;">
<input type="hidden" id="txtmax" style="display:none;">
</body>
</html>
How can I validate if the user has selected a file to upload?
Edit: bumped
Check it's value property:
In jQuery (since your tag mentions it):
$('#fileInput').val()
Or in vanilla JavaScript:
document.getElementById('myFileInput').value
My function will check if the user has selected the file or not and you can also check whether you want to allow that file extension or not.
Try this:
<input type="file" name="fileUpload" onchange="validate_fileupload(this.value);">
function validate_fileupload(fileName)
{
var allowed_extensions = new Array("jpg","png","gif");
var file_extension = fileName.split('.').pop().toLowerCase(); // split function will split the filename by dot(.), and pop function will pop the last element from the array which will give you the extension as well. If there will be no extension then it will return the filename.
for(var i = 0; i <= allowed_extensions.length; i++)
{
if(allowed_extensions[i]==file_extension)
{
return true; // valid file extension
}
}
return false;
}
Building on Ravinders solution, this code stops the form being submitted. It might be wise to check the extension at the server-side too. So you don't get hackers uploading anything they want.
<script>
var valid = false;
function validate_fileupload(input_element)
{
var el = document.getElementById("feedback");
var fileName = input_element.value;
var allowed_extensions = new Array("jpg","png","gif");
var file_extension = fileName.split('.').pop();
for(var i = 0; i < allowed_extensions.length; i++)
{
if(allowed_extensions[i]==file_extension)
{
valid = true; // valid file extension
el.innerHTML = "";
return;
}
}
el.innerHTML="Invalid file";
valid = false;
}
function valid_form()
{
return valid;
}
</script>
<div id="feedback" style="color: red;"></div>
<form method="post" action="/image" enctype="multipart/form-data">
<input type="file" name="fileName" accept=".jpg,.png,.bmp" onchange="validate_fileupload(this);"/>
<input id="uploadsubmit" type="submit" value="UPLOAD IMAGE" onclick="return valid_form();"/>
</form>
In Firefox at least, the DOM inspector is telling me that the File input elements have a property called files. You should be able to check its length.
document.getElementById('myFileInput').files.length
I got this from some forum. I hope it will be useful for you.
<script type="text/javascript">
function validateFileExtension(fld) {
if(!/(\.bmp|\.gif|\.jpg|\.jpeg)$/i.test(fld.value)) {
alert("Invalid image file type.");
fld.form.reset();
fld.focus();
return false;
}
return true;
} </script> </head>
<body> <form ...etc... onsubmit="return
validateFileExtension(this.fileField)"> <p> <input type="file"
name="fileField" onchange="return validateFileExtension(this)">
<input type="submit" value="Submit"> </p> </form> </body>
Simple and powerful way(dynamic validation)
place formats in array like "image/*"
var upload=document.getElementById("upload");
var array=["video/mp4","image/png"];
upload.accept=array;
upload.addEventListener("change",()=>{
console.log(upload.value)
})
<input type="file" id="upload" >