Write to a text file using an HTA

hta
Jack picture Jack · Jan 14, 2013 · Viewed 9.7k times · Source

I am trying to create an HTA file that allows a user to add data to a text file. I am fairly Inexperienced in the area.

I need to accomplish a few things:

  1. Write the bit of data that is inputted to a text file (which my code does)
  2. Let the user chose from a drop-down list of available files to write to
  3. It would be nice if the data could be submitted onClick or by hitting Enter
  4. Clear the fields on submit
  5. Log every entry. No overwriting of data in the text file (my code overwrites)

example:

123
456
789

I apologize if my code looks choppy.

Any help or advice would be appreciated.

Thank you.

<html><head>
<SCRIPT LANGUAGE="VBScript">

    Sub Window_onLoad
        window.resizeTo 480,150
    End Sub 

</SCRIPT>
<script language="javascript">
function Writedata()
{
var fso = new ActiveXObject("Scripting.FileSystemObject");
var write_id;
write_id = document.getElementById('write_id').value ;
alert('The data has been written to \n' + write_id);
var s = fso.CreateTextFile(write_id, true);

s.WriteLine(document.getElementById('name_id').value);

s.Close();
}
</script>
</head>
<body>

<table>
<tr>
<td>Input: </td>
<td><input type="text" name="name" value="" id="name_id"></td>
<td><select><option name="write" value="C:\temp\test1.txt" id="write_id">Option1</option>    </select></td>
<td><input type="button" onclick="Writedata()" value="submit"></td>
</tr>
</table>

</body>
</html>

Answer

Teemu picture Teemu · Jan 14, 2013

Looks like you've edited your code. Though it can be more flexible:

var s = fso.CreateTextFile(write_id, true); maybe rather:

var s = fso.OpenTextFile(write_id, 2, true);

where 2 represents a bytecode: 1 = read, 2 = write, 8 = append.

write_Id should contain a full path to file, like D:/Foldername/filename.txt.


That's not how you should use select, rather give the id for select itself like this:

<select id="write_id">
    <option value="C:\temp\test1.txt">Option1</option>
</select>

Now the value of selected option is stored also as value of select, which you can read in your script exactly like you are doing now.

Also you can declare a variable and assign a value together in JS:

var write_id = document.getElementById('write_id').value;