HTML button not functioning - javascript

I am working on a project in JavaScript, which prints out some names pulled from an XML file. I also have 3 textboxes and an update button so that if anyone types in a name in any of the textboxes, they will see the updated names when they hit the button. For example, if I originally have:
George
Mary
John
If the user types in Jane, it should change the output to:
Jane
Mary
John
However, the update button doesn't do anything when it is clicked on. Here is the code for my 3 textboxes and the button:
<div id = "Names">
<input type = "text" id = "nameOne" value = "Enter a name" onClick = "if(this.value == value){this.value = '';}" />
<input type = "text" id="nameTwo" value = "Enter a name" onClick = "if(this.value == value){this.value = '';}" />
<input type ="text" id = "nameThree" value = "Enter a name" onClick = "if(this.value == value){this.value = '';}" />
<input type = "button" id = "btnUpdate" value = "Update Names" onClick = "printNames()" /></div>
And here are the functions I am using:
function getXML(){
if(window.XMLHttpRequest){
xmlhttp = new XMLHttpRequest();
}
else{
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.open("GET","Names.xml",false);
xmlhttp.send();
return(xmlhttp.responseXML);
}
function printNames() {
var xml = getXML();
var txt = "";
$(xml).find("person").each(function () {
txt += "<div>" + $(this).text() + "</div>";
});
$("body").append(txt);
insertNames(name1, name2, name3);
}
function insertNames(name1, name2, name3) {
var xmlRequest = getXML();
var nameOneTxt = document.getElementById('nameOne').value;
var nameTwoTxt = document.getElementById('nameTwo').value;
var nameThreeTxt = document.getElementById('nameThree').value;
if (nameOneTxt != null || nameTwoTxt != null || nameThreeTxt != null) {
var x = xmlRequest.getElementsByTagName("person")[0].childNodes[0];
x.nodeValue = nameOneTxt;
var y = xmlRequest.getElementsByTagName("person")[0].childNodes[1];
y.nodeValue = nameTwoTxt;
var z = xmlRequest.getElementsByTagName("person")[0].childNodes[2];
z.nodeValue = nameThreeTxt;
}
printNames();
}
printNames();
</script>
The printNames() function reads the names from an XML file and outputs those names using jQuery. It then calls the insertNames() function which takes in 3 parameters (for the three textboxes I have.)
The insertNames function opens an XML connection, and then gets the values for each textbox. If the textbox is not null, then that means the user input a value, in which case, a call to the XML tag is made and updates the existing content to the user input. It then calls the printNames() function which outputs the new contents.
When I test this, I get the original names output, but the update button doesn't do anything. I tried adding a print statement to the insertNames function to find that the function never runs. What am I missing? Any help would be appreciated. Thanks.

I think it is when the function is being loaded. Check this
Fiddle.
I have reduced your printNames call to this
function printNames(){
alert(1);
}
If you leave it to run at default onLoad it doesn't work. If you change the load time to No wrap -in Body it works fine.
Haven't seen your code, but check where you are loading the function in relation to the onclick. The manual printNames() call at the bottom of the script will work whereas the onclick printNames() call will not.

Related

Text Box Search / Javascript Function Arrays **not corresponding**

I want the user to "Search" some "Authors" and if they select the one in the database they are sent to a corresponding HTML. Otherwise "No Author Found" displays...
For some reason I cannot wrangle it properly - pls help!
//Search by Author
function searchAuth() {
var search_string = document.getElementById('search_string').value;
var arrayelement = ["John","Stan","Henry","Paul","Samuel"];
for (i=0;i<arrayelement.length;i++) {
if (input == arrayelement.John) {
var itemLink = document.getElementById('demo').innerHTML =
"<a href='https://www.google.ca/?gws_rd=ssl'>Your link</a>";
} else if (input == arrayelement.Stan) {
var itemLink = document.getElementById('demo').innerHTML =
"<a href='https://www.google.ca/?gws_rd=ssl'>Your link</a>";
}else {
var itemLink = document.getElementById('demo').innerHTML =
"Author not found."
}
}
<!--Author-->
<h3>Search By Author</h3>
<form name="searchTest" onsubmit="return(searchAuth());" action="#">
<input type="text" id="search_string" />
<input type="submit"/>
<p id="demo"></p>
Perhaps you are trying to do things like these..
P.S this is just a demo, for you to start :)
EDIT: added few explanation on some stuffs you might get confuse with. :)
//events once textbox gets out focus
//the events varies on which or where do you want to add the event. it can be on click of a search button or submit button just like in your example.
document.getElementById('search-text-box-id').addEventListener("focusout", function() {
//searchString gets the textbox value.
var searchString = document.getElementById('search-text-box-id').value;
var searchList = ["John","Stan","Henry","Paul","Samuel"];
//Loop searchList
for (i=0; i < searchList.length; i++) {
//i which usually means the index or the key of the array's object(s).
var searchItem = "";
//searchList[i] loops its object by getting the index resulting to John, Stan and so on and so forth.
if (searchString == searchList[i]) {
searchItem = searchList[i];
document.getElementById('search-result-container').innerHTML = searchItem + " link";
//stop looping as the loop found a match.
return;
}
else {
searchItem = "Author not found.";
document.getElementById('search-result-container').innerHTML = searchItem;
}
}
});
<label for="search-text-box"></label>
<input type="text" id="search-text-box-id" name="search-text-box" />
<p id="search-result-container"></p>

Why doesn't my reset() function remove my red error lines?

function validate() {
var fname = document.getElementById("fname").value;
document.getElementById("errorfname").innerHTML = "";
if (checkfname() == true) {
alert("Entry submitted.");
} else {
return false;
}
}
function checkfname() {
var fname = document.getElementById("fname").value;
if (fname.length == 0) {
document.getElementById("errorfname").innerHTML = "Invalid first name. Cannot be empty.";
return false;
} else if (!isNaN(fname)) {
document.getElementById("errorfname").innerHTML = "Invalid first name. Cannot contain numbers.";
return false;
} else {
return true;
}
}
function addRow() {
if (validate() == true) {
}
}
<form>
First Name:
<input type="text" id="fname" name="fname" />
<p id="errorfname" class="red"></p>
<input id="submit" type="submit" value="Submit Entry" onclick="return addRow()" />
<input id="clear" type="button" value="Reset" onclick="reset()" />
</form>
<form>
<fieldset>
<label for = "firstnameinput">
First Name: <input type = "text" id = "fname" name = "fname" placeholder = "John"/>
<p id = "errorfname" class = "red"></p>
</label>
</fieldset>
<fieldset>
<label id = "submitbutton">
<input id = "submit" type = "submit" value = "Submit Entry" onclick = "return addRow();upperCase();"/>
</label>
<label id = "resetbutton">
<input id = "clear" type = "button" value = "Reset" onclick = "reset()"/>
</label>
</fieldset>
</form>
This is my simplified HTML file. It basically has an input and a paragraph below it to display an error message later on. For now it is set as "" in javascript. The HTML also has a submit button and a reset button. The purpose of the reset button is to clear all previously entered fields or any error message that has appeared.
function validate(){
var fname = document.getElementById("fname").value;
document.getElementById("errorfname").innerHTML = "";
if(checkfname() == true){
alert("Entry submitted.");
}
else{
return false;
}
function checkfname(){
var fname = document.getElementById("fname").value;
if(fname.length == 0) {
document.getElementById("errorfname").innerHTML = "Invalid first name. Cannot be empty.";
return false;
}
else if(!isNaN(fname)){
document.getElementById("errorfname").innerHTML = "Invalid first name. Cannot contain numbers.";
return false;
}
else{
return true;
}
}
function addRow(){
if(validate() == true){
event.preventDefault();
var fname = document.getElementById("fname").value;
firstNameArray.push(fname)
var row = document.getElementById('table').insertRow(-1);
var colNum = row.insertCell(0);
var colName = row.insertCell(1);
i++;
colNum.innerHTML = i;
colName.innerHTML = fname + " " + lname;
else{
return false;
}
reset();
}
Lastly, my reset() function below.
function reset(){
document.getElementById("errorfname").innerHTML = "";
document.getElementById("fname").value = "";
}
The problem is, for example, in the input box for fname, I enter John. When I press the reset button on my HTML which calls the reset() function, John in the box disappears so I got that going for me which is nice. However, lets say I purposely left the box blank to receive an error message, a red sentence below the box appears saying "Invalid first name. Cannot be empty." When I press the reset button to call onto the reset() function, this red error message does not disappear however, any current value inside the box disappears. This makes by reset() function work 50% only. I clearly stated for both to disappear in my reset() function.
TL;DR
I have a reset button in my HTML which calls a reset() function in my javascript. I have a name input box in my HTML and what the reset() function is supposed to do is to remove any current name which is inside the box as well as remove any error message that appears below. My reset() function is able to clear away any name inside the box currently but is unable to clear away the error message.
I created a fiddle to test your problem. I noticed the same thing. I changed the method reset() to resetTest() and it worked fine.
working fiddle
The reason changing the name worked is that onxyz= attribute event handlers are run (effectively) within a couple of with statements, one of which is with (theEnclosingFormElement). Form elements have a built-in reset method that clears all of their inputs to their initial values. So in this:
<input id = "clear" type = "button" value = "Reset" onclick = "reset()"/>
The reset being called isn't your reset, it's the form's reset, which doesn't (of course) do anything with errorfname. Changing the name removes the conflict.

javascript add two multipleevents on input field

I am trying to add two events on input field like onkeyup and onchange, the purpose is to avoid longpress of characters other than numbers..as the field is for zipcode. At present only one event is working either keypress/onchange.
I am adding my code for refrence any help would be appreciated.
function zipchange(obj, selector){
var code = obj.value;
var isnum = /^\d+$/.test(code);
if(!isnum)
obj.value="";
}//onchange
function autoZip(obj, selector){
var code = obj.value;
if(code.match(/\D/gi))
obj.value = code.replace(/\D/gi,'');
if(code.length>4 && code.indexOf('-')== -1){
var substr = code.substring(4);
substr=substr.replace(/\D/gi,'');
obj.value = code.substring(0,4)+'-'+substr;
}//onkeypress
//html
<input id="pincode" type="text" data-validate="validate[required]" name="address.pinCode" required="true" onkeyup="autoZip(this)" onchange="zipchange(this)" msg="Enter valid zip code" />
Answer:
function autoZip(obj, selector){
var code = obj.value;
if(code.match(/\D/gi))
obj.value = code.replace(/\D/gi,'');
if(code.length>4 && code.indexOf('-')== -1){
var substr = code.substring(4);
substr=substr.replace(/\D/gi,'');
var substr1 = code.substring(0,4);
obj.value = substr1+'-'+substr;
var isnum = /^\d+$/.test(substr1)
if(!isnum)
obj.value="";
}
Hi the above modified function did the trick..thanks for all the enlightned ones who helped me..
Well first of all onchange is triggered when you change the content of the text-box and when you loose focus from input type
Hence there is no use in using onchange event you have to implement your onchange logic in keyup event

Printing or Echoing message in html page from javascript

I have the following script
function validateEmailp() {
var messagemail = document.getElementById('emailerrorz').innerText;
var two = document.getElementById('email').value;
var first = two.split("#")[1];
var badEmails = ["gmail.com", "yahoo.com"]
if (badEmails.indexOf(first) != -1) {
document.getElementById("email").value = ""; //this works
messagemail = 'We do not accept free e-mails'; //this doesn't
return false;
}
return true;
}
and HTML
<td>{EMAILFIELD}<span id="emailerrorz"></span></td>
and {EMAILFIELD} is in PHP
<input id="email" class="txt" type="text" name="email" size="25" value="" maxlength="255" onblur="validateEmailp()"></input>
But it doesn't work for me on printing the error in the span id. It only works on resetting the value from there.
When you do var messagemail = document.getElementById('emailerrorz').innerText; your variable stores a string with that content.
When you var messagemail = document.getElementById('emailerrorz'); your variable stores a object/element and then you can use the property .innerText
So use:
var messagemail = document.getElementById('emailerrorz');
// rest of code
messagemail.innerText = 'We do not accept free e-mails';
Properties don't work this way. You want:
document.getElementById('emailerrorz').innerText = 'We do not accept free e-mails'
or
var messagemail = document.getElementById('emailerrorz');
....
messagemail.innerText = etc
http://jsfiddle.net/MJXEg/

call another function in a main function of javascript

<script>
function checkName(){
var tmpName = document.getElementById("name");
if( tmpName.value.length == 0 ){
alert( "Name cannot be empty" );
return false;
}
else
return true;
}
function confirmForm( formObj ){
var nameBool = new Boolean();
var errorName = "";
nameBool = checkName();
if( nameBool == false )
errorName = "Invalid data in input name !";
return window.alert( "You have this error : \n " + errorName + "\n" + errorID );
}
</script>
<form name=reviewform onsubmit="return confirmForm(reviewForm)" method=POST >
<p>Name : <input type="text" id="name" ></p>
<p>ID : <input type="text" id="id" ></p>
<input type="submit" value="Click here!">
</form>
my problem is why my function cannot run ??? isn't something wrong? can any senior teach me where the place i wrong at??
i already editited and plus that form name and the function how it's work
i don't know isn't my implementation wrong or what
Both functions, though they need some work, and you clearly need to brush up on your JS knowledge, can run, you just have to call them. As it stands, you've just defined 2 functions. Nothing else.
Other issues, line/line:
//second line:
var tmpName = document.getElementById("name");
Here, you can't be sure this element is already leaded, perhaps the DOM isn't ready yet, so be careful, just wrap your entire code in a handler:
window.onload = function()
{
//your code here, this gets executed after the page is fully loaded
};
Next, don't think of JS as some sort of Java-for-browsers, it's a completely different animal. Stuff like:
var nameBool = new Boolean();
var errorName = "";
Is best written as declaring variables, but not assigning anything:
var nameBool, errorName;
If you want to be sure the nameBool is a boolean, just assign like so:
nameBool = !!checkName();//double bang
It also looks like you're trying to validate a form or handle a submit event of sorts. Why not use addEventListener for that? or, if you insist:
document.getElementById('formId').onsubmit = function(e)
{
//get event object:
e = e || window.event;
//this references form, as does (e.target || e.srcElement), you can access the elements it contains, and check them one by one
};

Categories