I have a list of buttons in HTML. Depending on the button which is clicked, an AJAX call is supposed to be made and the data displayed. However JavaScript is not able to read the button. Here is the code in HTML
<ul>
<li><input type = "button" name = "lab" id = "map" value = "Computer Lab" onClick = "openPage(this)"></li>
<li><input type = "button" name = "lib" id = "map" value = "Library" onClick = "openPage(this)"></li>
<li><input type = "button" name = "mlib" id = "map" value = "Manuscript Library" onClick = "openPage(this)"></li>
<li><input type = "button" name = "radio" id = "map" value = "Agra ki Aawaz" onClick = "openPage(this)"></li>
</ul>
And here is the javascript code
function openPage(page){
try {
xmlHttp = new XMLHttpRequest ();
}
catch (e) {
try {
xmlHttp = new ActiveXObject ("Microsoft.XMLHTTP");
}
catch (el) {
try {
xmlHttp = new ActiveXObject ("Msxml2.XMLHTTP");
}
catch (el1) {
alert ("Your browser does not support AJAX! Please use a compatible browser!!");
}
}
}
xmlHttp.onreadystatechange = function () {
if (xmlHttp.readyState == 4 && xmlHttp.state == 200) {
var sp = documet.getElementByID ("mainText");
sp.innerHTML = xmlHttp.responseText;
}
};
var target = "";
var parent = "";
var page = "";
switch(page.name){
case 'lab':
target = "get_content.jsp";
parent = "kmi";
page = "lab";
break;
case 'lib':
targt = "get_content.jsp";
parent = "kmi";
page= "gen_lib";
break;
case 'mlib':
targt = "get_content.jsp";
parent = "kmi";
page= "man_lib";
break;
case 'radio':
targt = "get_content.jsp";
parent = "kmi";
page= "radio";
break;
}
xmlHttp.open("POST", target, false);
xmlHttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded;");
xmlHttp.send("parent=" + parent + "&page=" + page);
Now the problem is that page.name is coming as undefined.
I don't understand what is wrong with it and is it possible to create such a list of buttons and navigate using these?
Just above your switch statement, you have this:
var page = "";
since your function definition looks like this:
function openPage(page){
JavaScript drops the var (variable is declared already), and merely assigns "" (an empty string) to what used to be a reference to a DOM element. Fix the name conflict and you should be on your way
Related
So I am trying to make an edit function for a favorites bar. Editing one box is okay, but when I try to edit a different box, all the boxes that I clicked on previously gets edited as well. Here is a jsfiddle with the complete code: https://jsfiddle.net/1exrf9h8/1/
I am trying to understand why my editFavorite function is updating multiple boxes and not just one.
function clickEdit(input, title, url, plus, editIcon, anchorEdit, editBtn)
{
let i = editIcon.length - 1;
editIcon[i].addEventListener("click", function(event){
input.style.display = "block";
title.value = plus[i + 1].textContent;
url.value = anchorEdit[i].href;
console.log(i);
console.log(anchorEdit[i]);
editFavorite(anchorEdit[i], url, title, input, editBtn);
});
}
function editFavorite(changed, url, title, input, editBtn)
{
editBtn.addEventListener("click", function(){
changed.href = url.value;
changed.textContent = title.value;
input.style.display = "none";
});
}
There is a few problems in your logic, architecture and use of the event handler, Let's give it a shot in a more OOP way so you can actually make it to work and understand what is going on.
Every single favorite is an object by itself, that can spawn and update itself.
function favorite(newTitle, newUrl) {
this.element = container.appendChild(document.createElement("div"));
this.title = this.element.appendChild(document.createElement("h2"));
this.url = this.element.appendChild(document.createElement("h2"));
this.update = (newTitle, newUrl) => {
this.title.textContent = newTitle;
this.url.textContent = newUrl;
}
this.createButton = () => {
button = this.element.appendChild(document.createElement("button"));
button.append("Edit");
button.addEventListener("click", () => {
let titleInput = document.getElementById("title").value;
let urlInput = document.getElementById("url").value;
this.update(titleInput, urlInput);
})
}
this.update(newTitle, newUrl);
this.createButton();
}
Then let's have a simple form where we can take inputs, using the same for editing, and creating a new favorites.
<input id="title" type="text" name="title" placeholder="Title">
<input id="url" type="text" name="url" placeholder="Url">
<button id="submit">Create New</button>
Now the actual submit logic.
document.getElementById("submit").addEventListener("click", () => {
let titleInput = document.getElementById("title").value;
let urlInput = document.getElementById("url").value;
if (!titleInput.length || !urlInput.length) return;
let newFavorite = new favorite(titleInput, urlInput);
container.appendChild(newFavorite.element);
});
https://jsfiddle.net/p50L27us/48/
The problem is caused by editFavorite function. when you call editFavorite function automatically starts new listener. Evey click start new one.
The solution is " ,{once : true} "
function editFavorite(changed, url, title, input, editBtn)
{
editBtn.addEventListener("click", function(){
changed.href = url.value;
changed.textContent = title.value;
input.style.display = "none";
},{once : true});
}
I have a button calling a js function. Everything in the function runs but at the end I try to set the onclick value for the button and nothing happens. The catch block doesn't even generate an error
var nextButton = document.getElementById("next");
try{
if(tvalue == "trend"){
nextButton.onclick = "generateLocations()";
}
else if (tvalue == "stats"){
nextButton.onclick = "generateCategories()";
}
}
catch(err) {
document.getElementById("demo").innerHTML = err.message;
}
I have also tried setting the onclick value these ways
nextButton.onclick = function () { generateCategories(); };
nextButton.onclick = generateCategories;
the tvalue variable is set like this:
var t = document.getElementById("type");
var tvalue = t.options[t.selectedIndex].value;
Other test outputs have shown that this retrieves the value no problem
The relevant HTML:
<form id='fieldsets' action="../scripts/reportParse.php">
<fieldset>
<legend> Select Report Type </legend>
<select id="type" name="type">
<option value="trend"> Waitlists over Time </option>
<option value="stats"> Region Statistics </option>
</select>
</fieldset>
<button id="next" onclick="generateRegions()"> Next </button>
I've been trying solutions based on the following page:
Change onclick action with a Javascript function
and w3schools.com
Thanks for any help. I've been hung up on this for a little bit now
Edit: I've tried useing event listeners based on a comment below and am now getting the error "i is not defined'. which seems odd since i is not referred too inside the try block.
The whole function in case i've missed something stupid:
function generateRegions(){
var t = document.getElementById("type");
var tvalue = t.options[t.selectedIndex].value; // The value of the selected option
var names = ["Downtown", "Glenmore", "Mission", "Rutland"];
var regions = document.createElement("FIELDSET");
regions.setAttribute("id","Region");
var temp = document.createElement("LEGEND");
temp.innerHTML = "Select Region:";
regions.appendChild(temp); //creating the fieldset div and assigning its legend
for(var i = 0; i < 4; i++){
var templ = document.createElement("LABEL");
var str1 = "chk";
var str2 = i.toString();
var id = str1.concat(str2); //creating a dynamic ID so each checkbox can be referred to individually
templ.setAttribute("for",id);
temp = document.createElement("INPUT"); //creating the checkbox and assigning its values
temp.setAttribute("type","checkbox");
temp.setAttribute("name","region");
temp.setAttribute("value",names[i]);
temp.setAttribute("id",id);
regions.appendChild(templ);
templ.innerText = names[i]+':'; //creating and placing the label, then placing its checkbox
regions.appendChild(temp);
}
document.getElementById("fieldsets").appendChild(regions); //adding the fieldset to the overall form
var nextButton = document.getElementById("next");
try{
if(tvalue == "trend"){
nextButton.onclick = "generateLocations()";
}
else if (tvalue == "stats"){
nextButton.onclick = "generateCategories()";
}
}
catch(err) {
document.getElementById("demo").innerHTML = err.message;
}
//document.getElementById("demo").innerHTML = tvalue; //checking that the type variable is properly found
}
Try adding an event listener to your code so the JavaScript is separated from the HTML markup. Like so:
var nextButton = document.getElementById("next");
try{
if(tvalue == "trend"){
nextButton.addEventListener("click",generateLocations()) ;
}
else if (tvalue == "stats"){
nextButton.addEventListener("click",generaCategories()) ;
}
}
catch(err) {
document.getElementById("demo").innerHTML = err.message;
}
You can test if the event listener is working by adding a console log on the functions you are executing.
Source: https://www.w3schools.com/js/js_htmldom_eventlistener.asp
I have a requirement to capture into eVar a string of fields that have been changed when user updated their details.
I am using DTM and am thinking how to make it work.
Firstly I wrote this code and saved it as Data Element in the DTM:
var oldMobileNo = document.getElementById('mobileNumber').value;
var oldAnotherNo = document.getElementById('additionalTelephoneNumber').value;
var oldEmail = document.getElementById('emailConfirmed').value;
document.forms['editContactVO'].onsubmit = function(){
var newMobileNo = document.getElementById('mobileNumber').value;
if(oldMobileNo != newMobileNo) {
var MobileNo = "mobile number changed";
}
else {
var MobileNo = "";
}
var newAnotherNo = document.getElementById('additionalTelephoneNumber').value;
if(oldAnotherNo != newAnotherNo) {
var AnotherNo = "additional number changed";
}
else {
var AnotherNo = "";
}
var newEmail = document.getElementById('emailConfirmed').value;
if(oldEmail != newEmail) {
var Email = "email changed";
}
else {
var Email = "";
}
return MobileNo;
return AnotherNo;
return Email;
}
var Final = MobileNo + "," + AnotherNo + "," + Email;
return Final;
Then I tried to reference it with the event based rule set on the form submit button click. The rule definitely worked until I called this Data Element. The rule stopped working.
As far as I understand this code has to be set on the page with form to be able to capture original values and it should be active when the form is updated.
Is it possible to this via DTM? If yes, how to? Or may be somebody did it in the different way?
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.
I am trying to populate a <select> element via Ajax. It works great in FF, but I get an unknown runtime error in IE.
HTML:
<select id="emp_select" name="emp_select">
<option value=" ">Please enter a store</option>
</select>
Javascript:
$("#store").blur(function() {
populateDropdowns();
});
...
function populateDropdowns() {
var store = $("#store").val();
if (store.length != 4) {
alert("Store # must be 4 digits!");
$("#store").focus();
return false;
}
var xhrJSON = new XMLHttpRequest();
var xhrEmpSelect = new XMLHttpRequest();
var xhrMgrSelect = new XMLHttpRequest();
var jsonDone = false;
var empSelectDone = false;
var mgrSelectDone = false;
$("#processing-dialog").dialog({
width: 300,
height: 150
});
xhrJSON.onreadystatechange = function() {
if (xhrJSON.readyState == 4) {
if (xhrJSON.status == 200) {
var js = document.createElement('script');
js.type = 'text/javascript';
js.innerHTML = xhrJSON.responseText;
var scr = document.getElementsByTagName('script')[1];
scr.parentNode.insertBefore(js,scr);
jsonDone = true;
if (jsonDone && empSelectDone && mgrSelectDone) {
$("#processing-dialog").dialog("close");
$("#processing-dialog").dialog("destroy");
return true;
}
} else {
return false;
}
}
}
xhrEmpSelect.onreadystatechange = function() {
if (xhrEmpSelect.readyState == 4) {
if (xhrEmpSelect.status == 200) {
$("#emp_select").html(xhrEmpSelect.responseText);
empSelectDone = true;
if (jsonDone && empSelectDone && mgrSelectDone) {
$("#processing-dialog").dialog("close");
$("#processing-dialog").dialog("destroy");
return true;
}
} else {
return false;
}
}
}
xhrMgrSelect.onreadystatechange = function() {
if (xhrMgrSelect.readyState == 4) {
if (xhrMgrSelect.status == 200) {
$("#mgr_select").html(xhrMgrSelect.responseText);
mgrSelectDone = true;
if (jsonDone && empSelectDone && mgrSelectDone) {
$("#processing-dialog").dialog("close");
$("#processing-dialog").dialog("destroy");
return true;
}
} else {
return false;
}
}
}
var url = "ajax.cgi";
var JSONdata = "action=generateJSON&store=" + store;
var EmpSelectData = "action=generateEmpSelect&store=" + store;
var MgrSelectData = "action=generateMgrSelect&store=" + store;
xhrJSON.open("POST",url);
xhrJSON.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
xhrJSON.send(JSONdata);
xhrEmpSelect.open("POST",url);
xhrEmpSelect.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
xhrEmpSelect.send(EmpSelectData);
xhrMgrSelect.open("POST",url);
xhrMgrSelect.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
xhrMgrSelect.send(MgrSelectData);
}
The blur handler calls a function to populate (all) the different select elements, plus a JavaScript object that holds an associative array of all the employees to match up a name with an employee id that is returned as the values of the options in both select elements.
XHR Text returned (for xhrJSON, content-type=application/json):
var empArray = new Array({ id:"12345678", title:"The Title", code:"C123", name:"John Doe"},...);
XHR Text returned for (xhrEmpSelect, content-type=text/html):
<option value=" ">Select One</option>
<option value="John Doe">John Doe</option>
<option value="Joe Blow">Joe Blow</option>
...
<option value="other">Other...</option>
</select>
Similar text is returned for xhrMgrSelect, content-type=text/html
So in FF everything works great, the JS Object comes across and is inserted into the DOM and both <select> elements are populated as well. BUT in IE, I get an unknown runtime error in the xhrJSON.onreadystatechange handler where I try and set the js.innerHTML to the xhrJSON.responseText.
What am I doing wrong?
Try using js.text = xhrJSON.responseText; instead of innerHTML. I believe the issue you are encountering has to do with the fact that you can't insert HTML into a <script> block.
Since you are setting the script you should use innerText instead of innerHTML. Try this.
js.innerText = xhrJSON.responseText;
//Since FF do not sussport innerText but it does support textContent
js.textContent = xhrJSON.responseText;
I would advice you to migrate your code to jQuery which will be much simpler, readable, and easy to maintain without any worries of cross browser support. jQuery does everything for you.
To set the contents of a HTMLScriptElement object, (created using document.createElement('script');) you should use the setText method of the object instead of trying to set the innerHTML of the script.
js.setText(xhrJSON.responseText);
See the W3 specification from the link above.