Appending an Array and String in javascript into a variable - javascript

How can you run a getelementbyid on an Array and a String in Javascript and set it as a variable that is not null for example foo["dog"] x = getelementbyid(foo[0]+"food") and now x = dogfood
<script>
var myrows = new Array();
$(function() {
$("#check").click(function(){
myrows=[]
$(".head input:checked").not("#selectall").each(function(){
myrows.push($(this).parent().attr("id"));
}).value;
alert(myrows);
});
$("#subbut").click(function(){
var x;
var r=confirm("Are you sure you?");
if (r==true){
x="You pressed OK!";
}else{
Object.cancel;
}
**alert( myrows[0]+"servername" + " before" );
for(var i =0; i< myrows.length; i++){
alert(myrows[i] +"rootname" +" in loop" );
var j= document.getElementById(xmyrows[i] +"rootname" );
alert(j+" after call" );
var y = document.getElementById(myrows[i]+"servername");
document.getElementById("id_rootname").value= j.textContent;
document.getElementById("id_servername").value= y.textContent ;**
$.post($("#forms").attr("action"), $("#forms").serialize(), function(data) {
});
}
});
});
</script>

I don't really understand what the array/string problem is, but from the comments it seems you're looking for a way to do dynamic form submission: Dan Davis has provided the nuts and bolts of the solution in his comment — for each form you need to submit dynamically (without a refresh), create an iframe, then set the respective form's target attribute to that iframe's ID:
<form id="form1" target="#form1Response">
...
</form>
<form id="form2" target="#form2Response">
...
</form>
<iframe id="#form1Response"></iframe>
<iframe id="#form2Response"></iframe>
You will then need to attach your server response callbacks to the various iframes' load events. Beware though: even an empty iframe fires a load event, so you will need to filter false positives (empty iframe contents) in your callback.
Another caveat: if your server responds with JSON, IE will prompt the user to save the response to the filesystem before your script can intercept — so make sure the MIME type heading is set to text/plain or text/html to make sure the response is loaded into the iframe's DOM.

This can happen because java script allows white spaces sometimes if a string is concatenated with a number. try removing the spaces and create a string and then pass it into getElementById.
example:
var str = myrows[i]+"rootname";
str = str.replace(/^\s+|\s+$/g,"");
var str1 = myrows[i]+"servername";
str1 = str1.replace(/^\s+|\s+$/g,"");
var j= document.getElementById(str);
var y = document.getElementById(str1);
document.getElementById("id_rootname").value= j.textContent;
document.getElementById("id_servername").value= y.textContent ;
}

Related

Display results from api after user input

I'm learning JS and I need some help figuring out why my info isn't getting populated in the html. I'm just trying to get the basic functionality to work, so that I can continue to expand on it.
User is supposed to input a 3 digit route value, which will then return all the route information from an api call. I was able to get the route info to display earlier when I got the api call set up, but I'm struggling to figure why it's not displaying now that I tried adding in a feature to allow the user to input the route. See attached pen
HTML
<div class='container'>
<h1 id='header'>Route Info</h1>
<input id="input" type="text" placeholder="Enter 3 digit route ex 005" >
<input type="button" value="Get Route" onclick="getRoute()">
<br>
<p id = 'p'><span id="routeInfo"></span></p>
</div>
Javascript
$(document).ready(function() {
var route = $('#input');
getRoute.click(function() {
var scriptTag = document.createElement('SCRIPT');
scriptTag.src = "https://wsdot.wa.gov/Traffic/api/Bridges/ClearanceREST.svc/GetClearancesAsJson?AccessCode=59a077ad-7ee3-49f8-9966-95a788d7052f&callback=myCallback&Route=" + route;
document.getElementsByTagName('HEAD')[0].appendChild(scriptTag);
var myCallback = function(data) {
var myarray = Array.prototype.slice.call(data);
document.getElementById("routeInfo").innerHTML = JSON.stringify(myarray);
}
});
});
It looks like you are jumping through a lot of hoops you don't need to. As long as you are using Jquery, you should look into getting the api data with an ajax request. It's much easier and more intuitive. Also you have a few problems such as trying to get the input value with var route = $('#input'); which return the actual input element. You are also processing the returned data in a way that won't work.
Here's a basic example to get you going on (IMO) a better track:
function getRoute() {
var route = $('#input').val();
var url = "https://wsdot.wa.gov/Traffic/api/Bridges/ClearanceREST.svc/GetClearancesAsJson?AccessCode=59a077ad-7ee3-49f8-9966-95a788d7052f&Route=" + route;
$.ajax({url: url, success: function(data){
var retValue = "";
var i = 0
for(i; i< data.length; i++) {
retValue += data[i].BridgeName + "<br>"
}
document.getElementById("routeInfo").innerHTML = retValue;
}});
}
If you intend functionality in the getRoute.click callback to run, you need to rewrite that as a method function getRoute(), or get the button element via jQuery and assign that to the variable getRoute. As it stands, you have the click method wired via the markup to a function named getRoute which does not exist. In the JS you are trying to register a click event to a jQuery object named getRoute which does not exist.
getRoute needs to be a global function for it to be called from html :
getRoute = (function() {
Also, myCallback needs to be a global function for it to be called from your loaded script (just remove the var):
myCallback = function(data) {

How to read <input type="hidden"...> in JavaScript on subsequent page?

One first page:
A form SUBMIT goes to a subsequent page.
VBscript can see the hidden value with ... Request("myName") ...
How do I do the same thing in JavaScript.
alert(window.location.search);
or
alert(window.top.location.search.substring(1));
return nothing.
Well, you dont. When you submit a form it sends the values to a server, and the "server-side" reads that in vbscript as Request (Requested). If you want to let the requested value accessible to the Javascript, your server-side (subsequent) page must write that Request data back to the client-side, in other worlds, you have to write the requested value directily in the HTML that will be send back to the client browser.
Ex: In your ASP (Server-Side Subsequent VBScript file) you should write
Response.Write ("<script type=""text/javascript"">alert('" & Request("Data") & "')</script>")
<input type='hidden' id='hiddenId'/>
jQuery:
var value = $('#hiddenId').val();
alert(value);
Or
var value = document.getElementById('hiddenId').value;
alert(value);
In your form, you have to have the method set to GET.
<form method="GET" action="somepage">
<input type=hidden name=myHiddenValue />
</form>
Then on the next page, you can parse the search part of the url with a function like this.
function parseSearch(search, key) {
search = search.substring(1), items=search.split("&");
for (var i=0; i<items.length; i++) {
var item = items[i], parts = item.split("=");
if (parts[0] === key) {
return parts[1] || true;
}
}
}
parseSearch(location.search, "myHiddenValue"); // returns the hidden value
live demo

Dynamically loaded form won't update correctly

I have a form which is loaded into the page using .load(). I want to update the form with the HTML I compute in str, but my code isn't updating the form correctly. Why?
if($(this).is('.step3')){
//Splits the comma seperated values into input fields
var active_fields = ($('#templateFields').val()).split(',');
$('#loadedcontent').load('template.html #step3',function(){
$('#steps').text('Step Three');
$('#start.btn').text('Save Template & Values').removeClass('step3').addClass('step4');
});
str = "";
for(var i = 0; i<active_fields.length; i++){
str += '<label>'+active_fields[i]+'</label><input name="'+active_fields[i]+'" type="text" class="span3">';
}
$('form#values.well').html(str);
}
You have to put the form modification in the load completion function like this:
if($(this).is('.step3')){
//Splits the comma seperated values into input fields
var active_fields = ($('#templateFields').val()).split(',');
$('#loadedcontent').load('template.html #step3',function(){
$('#steps').text('Step Three');
$('#start.btn').text('Save Template & Values').removeClass('step3').addClass('step4');
str = "";
for(var i = 0; i<active_fields.length; i++){
str += '<label>'+active_fields[i]+'</label><input name="'+active_fields[i]+'" type="text" class="span3">';
}
$('form#values.well').html(str);
});
}
The way you were doing it, your code to modify the form was running before the form finished loading so it wouldn't find the content and thus couldn't modify it.
Sorry, I figured i couldnt nest a form within a form. I think thats why it didnt work

Stop a page from refreshing after firing a function

I've been tasked with building a very simple app that that has a series of dropdowns in rows of 2, when 2 are selected, a simple functions concatenates the 2 values and gives an output next to them like so:
dropdown1 dropdown2 Output
What I'm trying to get is, once the second dropdown value is chosen the function runs and displays the output where it says output. But currently, what seems to happens is the output is displayed in a new window.
Here's what I have so far (HTML):
<form>
<select id="test">
<option>Arena/Quantum Barcelona LTBC</option>
<option>Arena/Quantum Spain LTES</option>
</select>
<select id="name" onchange="tryThis()">
<option>Name</option>
<option>Name1</option>
</select>
</form>
JavaScript:
function tryThis() {
var string, string1 = '';
var e = document.getElementById("test");
string = e.options[e.selectedIndex].text;
var a = document.getElementById("name");
string1 = a.options[a.selectedIndex].text;
document.write(string+'_'+string1);
}
Am I making this more difficult than it needs to be?!
That's because document.write clears the page before displaying something. You should never need to use that function.
Instead, you could append it to e.g. the body:
document.body.appendChild(
document.createTextNode(string + '_' + string2)
);
Have you noticed that your JS function is called tryThis() and on the event handler you're calling tryThsis()
However in your case I'd refrain from using document.write, good alternatives are appending to the body or having a DIV and changing the innerHTML of that DIV
First put an id on your form so that it is easier to access.
var a = (function () {
var myForm = document.getElementById("myForm"),
magic = function () {
var a = myForm.getElementsByTagName("select"),
b,
c = [];
for (b = a.length - 1; b > -1; b -= 1) {
c.push(a[b].value);
}
alert(c.join(" ") + " output");
};
myForm.onclick = magic;
}());
You were not specific as to what the extra "output" is supposed to be or how you want the data returned, but here you go. Instead of using an alert you could push the result into the value of a different form element. Do not use document.write as this cannot be deferred. If you attempt to defer a document.write operation it will replace the entirety of the body contents of the current page.

Take Postcode to New Field in New Window

I have a read only field on a html field which has a name of _Dataaddr_postcode I now need to capture this data and pass it into a new window which loads another file (proxcomp.asp) and use the data in a field on this page the field has an ID of inpAddr.
I have this code so far
<script type="text/javascript">
var pcodeStart = document.getElementbyId("_Dataaddr_postcode");
var newWindow;
function makeNewWindow( ) {
if (!newWindow || newWindow.closed) {
newWindow = window.open("../hpwprox/proxcomp.asp","sub","status=0,title=0,height=600,width=800");
setTimeout("writeToWindow( )", 50);
} else if (newWindow.focus) {
newWindow.focus( );
}
}
</script>
<input type="button" value="Create New Window" onclick="makeNewWindow();" />
Can someone tell me how to achieve this with some sample code?
Thanks
Justin.
Passing just that one field as a form input to the server-side script:
var genForm = document.createElement("form");
genForm.target = "sub";
genForm.method = "get"; // or "post" if appropriate
genForm.action = "../hpwprox/proxcomp.asp";
var genInput = document.createElement("input");
genInput.type = "hidden";
genInput.name = "inpAddr";
genInput.value = pcodeStart.value;
genForm.appendChild(genInput);
document.body.appendChild(genForm);
if(!newWindow || newWindow.closed) {
window.open("", "sub", "status=0,title=0,height=600,width=800");
} else if(newWindow.focus) {
newWindow.focus();
}
genForm.submit();
If you wish to use client-side code to set a textbox in the pop-up rather than server-side code, you need to do it from the pop-up window to avoid the delay you would add otherwise and the page's load time from "racing" each other. In JavaScript, global variables are properties of the window object they exist inside of, and window.opener gives the window that opened this one. Note that because of the same-origin policy, the two windows need to have the same protocol, hostname, and port number in their URLs.
// Using the variable referring to the text box:
document.getElementById('inpAddr').value = window.opener.pcodeStart.value;
// Or even using getElementById directly:
document.getElementById('inpAddr').value = window.opener.document.getElementById('inpAddr').value
You can omit the window. part of window.opener if you want to, provided that you are using no variable called opener.
Maybe doing this:
newWindow.document.getElementById('inpAddr').value = pcodeStart;
Or from the open window:
document.getElementById('inpAddr').value = opener.document.getElementbyId("_Dataaddr_postcode").value;
Please read this great article!

Categories

Resources