Print cross using javascript in html - javascript

I have this code on my external javascript
function cross()
{
var output2 = document.getElementById('output2');
var a = "*"
, b = " "
, i = 0
, j = 0
, k = 0
;
for(i = 1, k = input; i <= input; i++, k--)
{
for(j = 1; j <= input; j++)
{
if (j == i || j == k)
{
output2.value += a;
}
else
{
output2.value += b;
}
output2.value += '\n';
}
}
}
and this html button on my 1st page + text area on my 2nd page so the text area will show in second page (halaman.html) after I click the button on 1st page.
<!-- code page 1-->
<input type="button" value="Muncul page baru" onclick="cross();"><br />
<!-- code page 2-->
<textarea id="output2" rows="20" cols="90"></textarea>
The cross doesn't show on the 2nd page. What's wrong and what should I do?

JavaScript can not set the value of an element on a page that is not even created yet.
You can submit a form with the value, but you would have to use a GET request since JavaScript will not be able to access the POST data without some help a serverside language.
Other options is to use localstorage. Set it on the first page, read it on the second.

I think this is not possible to do. Because when you navigate to second page, there is no javascript available from previous page. You need to store your result in server state or pass the result through the querystring

The javascript only works on the first page. You could send a GET variable through the URL and check for that variable on the second page.
You could also put page2 on a iframe.

Related

Sending data and saving in a text field

I have a main page with a popup window.
<textarea class="form-control item"></textarea>
<button type="button" class="btn btn-primary" name="name">Send</button>
There is also a second page. (/conclusion/main)
<textarea id="retro" style="height: 200px; width: 800px"></textarea>
I enter the text in the window and send. The window should close and the text should be sent to the second page and the text should be saved in the field "textarea". Even if they close the page or reload, the text should remain in the second page.
This code allows you to save, but after closing the page, does not save
(function(){
var textarea = document.getElementById('retro');
if (localStorage.retro)
{
textarea.value = localStorage.retro;
}
textarea.onchange = function()
{
localStorage.retro = this.value;
}
})();
Sends from the first page to the second
function getParams(){
var idx = document.URL.indexOf('?');
var params = new Array();
if (idx != -1) {
var pairs = document.URL.substring(idx+1, document.URL.length).split('&');
for (var i=0; i<pairs.length; i++){
nameVal = pairs[i].split('=');
params[nameVal[0]] = nameVal[1];
}
}
return params2;
}
params = getParams();
name = unescape(params["name"]);
document.getElementById('retro').innerHTML = name;
There are some questions around what you are trying to do here. What I have done is broken this down into 2 parts
Passing the local storage between 2 pages and accessing it.
Decoding Parameters in the URL and assigning them
Some assumptions that I made:
I have noticed some of the classes from bootstrap so i assume that you have jQuery on the page and also you may know how to use it.
Using chrome for testing this
PART 1 - Passing localstorage between windows:
First thing to note is you may be better using a cookie library (js-cookie) or creating one yourself that you can access. As localstorage may well be insecure depending on what data you want to store in there.
With that out of the way, you were on the right track, just needed to add your event listener to 'input' as i think then every keystroke the data in local storage is being updated.
Page 1
HTML
<textarea id="retro" class="form-control item"></textarea>
<button type="button" class="btn btn-primary" name="name">Send</button>
JS (I would recommend place this at the bottom of you page for quick testing)
<script type="text/javascript">
var textarea = document.getElementById('retro');
textarea.addEventListener('input',function(){
localStorage.setItem('retro', this.value);
})
</script>
In Chrome developer tools if you watch the variable 'localstorage' then you will see this change as you key in the value.
What I have done here is bound the event listener to the text area so that any 'input' the value changes, furthermore is am setting the item in the localstorage
PAGE 2
HTML
<textarea id="retro" style="height: 200px; width: 800px"></textarea>
JS
<script type="text/javascript">
var textarea = document.getElementById('retro').value = localStorage.getItem('retro');
</script>
Here using the 'getItem' method for localstorage you can then retrieve it from the storage area and output it as the value of the textarea.
Obviously is the cache or localstorage is cleared then this value will disappear.
PART 2 - Decoding Parameters in the URL and assigning them
$.urlParam = function(name){
var results = new RegExp('[\?&]' + name + '=([^]*)').exec(window.location.href);
if (results==null){
return null;
}
else{
return results[1] || 0;
}
}
This function above will get you any parameter you want form the url I found this from here. This is using jQuery.
Here is how you would use it
// example.com?param1=name&param2=&id=6
$.urlParam('param1'); // name
$.urlParam('id'); // 6
$.urlParam('param2'); // null
Well I hope this answers your question on both parts, and helps you further, please add any comments if I have missed anything and I will be happy to update my answer

Javascript-Using Parsed Data From a Query String as a Heading

I am wondering how to take the information from a parsed query string and use it to display on the top of my page. Ignore the window.alert part of the code, I was just using that to verify that the function worked.
For example: If the user had choices of Spring, Summer, Winter, and Fall, whichever they chose would display a a header on the next page. So if (seasonArray[i]) = Fall, I want to transfer that information into the form and display it as a element. I'm sure this is easily done, but I can't figure it out. Thanks, in advance.
function seasonDisplay() {
var seasonVariable = location.search;
seasonVariable = seasonVariable.substring(1, seasonVariable.length);
while (seasonVariable.indexOf("+") != -1) {
seasonVariable = seasonVariable.replace("+", " ");
}
seasonVariable = unescape(seasonVariable);
var seasonArray = seasonVariable.split("&");
for (var i = 0; i < seasonArray.length; ++i) {
window.alert(seasonArray[i]);
}
if (window != top)
top.location.href = location.href
}
<h1 id="DynamicHeader"></h1>
Replace the alert line with:
document.getElementById("DynamicHeader").insertAdjacentHTML('beforeend',seasonArray[i]);

Read a hard coded csv file and iterate through each entry to detect empty values

I have written a script for iMacro that reads a CSV file to extract numerous login details in order for passwords to be updated. The majority of these login details then also need to be updated on a second website, but in order to do so I need to be able to determine which sites have login details for the second site, and if they do, then run the second part of the iMacro script.
The CSV file I am using is laid out like so;
USERNAME 1 HEADER, PASSWORD 1 HEADER, USERNAME 2 HEADER, PASSWORD 2 HEADER
username1.1, password1.1, username1.2, password1.2
username2.1, password2.1, username2.2, password2.2
username3.1, password3.1, , ,
username4.1, password4.1, username4.2, password4.2
A loop would be used to process one row at a time, with a if statement inside to determine whether or not a empty/null value is present. If the second username or password are empty/null then the second part of the iMacro script would be skipped and the loop incremented.
I've never really used Javascript before, but I've have a bit of a look around and found jQuery-CSV, which looks like it's what I need but I cannot for the life of me get it to work. I also found this, which goes into detail about how to input a file, but it doesn't say how to hardcode it to a local file.
Any help on this would be greatly appreciated.
Thanks!
Here you go
HTML
<textarea id="csv"></textarea>
<button id="run">Run</button>
<div id="result"></div>
JS
$("#run").click(function(){
var result = $.csv.toArrays($("#csv").val());
empty = "";
html = "<table>";
for(i = 0; i < result.length; i++){
html += "<tr>";
for(j = 0; j < result[i].length; j++){
html +="<td>"+result[i][j]+"</td>";
if(result[i][j].trim() == ""){
empty += "cell "+i+" "+j+" is empty";
empty += "<br />";
}
}
html += "</tr>";
}
$("#result").html(html);
$("#result").append(empty);
});
http://jsfiddle.net/4J8Jb/
EDIT:
and to read the csv from a file you can use $.get like so
$.get('/path/to/file.txt',function(data) {
if (data == "ON") {
var result = $.csv.toArrays(data);
....
....
....
} else {
//there is an error reading the file
}
});

Fill Array with div elements populated dynamically in codebehind. C#, javascript

I have a report populated as a table with a stringbuilder from the codebehind. The first TD of every row is a checkbox, the id of each checkbox is assigned dynamically:
sb.Append("<td><input type='checkbox' id='chkSelectAll_" + i + "' name='chk_" + i + "' onclick='JavaScript: chkAll_click(this);' /> </td>"
The aspx page uses a master page and
<asp:Content><div id='divMain'></div></asp:Content>
format other than a form to populate. The problem I am running in to is that I am having trouble finding all the elements (or any actually) of the div to work with. Here is the javascript I have been given. (Team project at work, I was just assigned 1 task on the project so changing anything is not an option.)
function divBatchBuild_click() {
debugger
var form = document.forms[0];
var visitList = '';
for (i = 0; i < form.elements.length; i++) {
if (form.elements[i].type == 'checkbox') {
//alert(form.elements[i].id.toString());
if (form.elements[i].checked == true &&
form.elements[i].id != 'chkSelectAll') {
var y = form.elements[i].id;
//alert('id=' + y[1].toString());
visitList = visitList + y[i].toString() + '|';
}
}
}
}
Apparently this worked on a previous project, but when used with this report the process never goes inside the if statement. Any help on what is going wrong is appreciated.
I think you want to first get the div, then get the elements in the div with the checkbox tagname. Something like:
var div = document.getElementById('divMain');
var elements = div.getElementsByTagName('checkbox');
for (i = 0; i < elements.length; i++) {

Confirm Delete pop up with Record Count

General Info:
Aspx page holds an Ascx User control. Inside the User control, the Repeater is contained inside a View, contained inside a Multiview.
Asp.Net 2.0 framework / C#
Details:
I have a repeater (inside an ascx user control) that shows records, and the first column is a checkbox. If checked, that row will be deleted.
OUtside the repeater, I have a button that will deleted all rows that are checked.
Everything works fine, but have been asked to add a pop up "confirm delete" message that includes the number of records that will be deleted if the user clicks "Ok" on the pop up.
Something like:
"You are about to delete 8 records".
Currently my button looks like this:
<asp:Button ID="btnDeleteAllRecords" runat="server" Text="Delete all Checked Records" Onclick="btnDeleteAllRecords_Click" OnClientClick="javascript:GetCbCount();" />
I have this javascript code block:
<script type="text/javascript">
function GetCbCount()
{
var cb = document.getElementById("rptrVoicemail").getElementsByTageName("input");
var cbCount;
for(i = 0; i < cb.lenght; i++)
{
if(cb[i].type == "checkbox")
{
if(cb[i].checked)
{
cbCount = cbCount + 1;
}
}
}
return confirm('You are about to delete' + cbCount + 'records.');
}
</script>
When I click my button I'm getting:
Error: 'document.getElementById(...)' is null or not an object
on this line:
var cb = document.getElementById("rptrVoicemail").getElementsByTageName("input");
Why is the JS not seeing my repeater? Is it because it's buried inside a MultiView? How can the JS be corrected so that the pop up will show the record count in the message?
UPDATE:
I changed the script to:
function GetCbCount(){
var inpt = document.getElementById("vmDiv");
var checkboxes = inpt.getElementsByTagName("input");
var cbCount;
for(i = 0; i<checkboxes.lenght;i++){
if (checkboxes[i].type == "checkbox" && checkboxes[i].checked){
cbCount = cbCount + 1;
}
}
return confirm('You are about to delete ' + cbCount + ' Voicemails.');
}
This should work:
document.getElementById('<%= rptrVoicemail.ClientID %>').getElementsByTageName("input");
Another approach is this little script that returns the ClientID. You could add it even to an included JS-file.
function GetClientId(strid)
{
var count=document.forms[ 0 ].length ;
var i = 0 ;
var eleName;
for (i = 0 ; i < count ; i++ )
{
eleName = document.forms [ 0 ].elements[ i ].id;
pos=eleName.indexOf( strid ) ;
if(pos >= 0) break;
}
return eleName;
}
Found here.
If you are using a master page or nesting controls (inside ascx, view, etc.) the framework will change the IDs that are rendered with elements.
If you do a "View Source" or use FireBug, you might see that rptrVoicemail became something like ctl00_ContentPlaceHolder1_someUserControl_ctl00_multiViewID_ctl28_rptrVoicemail.
You can use getElementById('<%= rptrVoicemail.ClientID %>') to get at the ID of the element as it would be rendered on the client.
Edit: To help debug, do something like this... you get the point.
var rptr = document.getElementById('<%= rptrVoicemail.ClientID %>');
rptr.borderColor = 'pink'; // draw a border to check it's the right element

Categories