Proper way to retrive HTML textbox data using JavaScript - javascript

Assuming I have a simple HTML page like the following:
<html>
<head>...</head>
<body>
<input type="text" id="mytextarea" />
<input type="button" id="button1" onClick="..." />
<input type="button" id="button2" onClick="..." />
</body>
</html>
What is the best way to access the text in the text-field with id="mytextarea" in a JavaScript function, without creating code heavily coupled to the HTML page, given the knowledge that button1 and button2 cause different manipulations on the text?
Just as an example, assume I am expecting a binary number in the text field, and button1 will convert it to an integer decimal number, but button two will convert it to a fractional decimal number. How can I handle this without tightly coupling the JavaScript code to the HTML page? Is there some way to send the data in mytextarea down to the JavaScript code, without having to use a document.getElementById('mytextarea') in the JavaScript functions themselves?
Perhaps I should clarify,
I am not looking for an alternative to using getElementById, I am looking for a way to write JavaScript code that can use a text-field in an HTML page without being coupled to it. In other words, I would like to know how to write JavaScript functions and HTML pages in such a way that (1) the JavaScript functions can perform work on data in the HTML page and (2) the JavaScript function can be be moved to another HTML page and used there, without changing said function.

I think this is what you want:
First you create an object called Textarea that lets you pass a textarea element as an argument:
function Textarea(textarea) {
this.container = textarea;
this.value = textarea.value
};
Then you can add methods shared by every instance of the Textarea object:
Textarea.prototype.ChangeValue = function(){
console.log( 'Please add your ' + this.value );
};
In this way, you can pass mytextarea and modify it as you want. This allows to reuse properties and methods in your object in other textareas or other projects where you need it.
t = new Textarea(document.getElementById('mytextarea'));
t.ChangeValue();
Demo: http://jsfiddle.net/SQ2EC/

Since you need some way to inform the functions about the elements to be operated on, there are two simple options. You can pass a reference to an element as a parameter when calling a function, as in
onclick="manipulate(document.getElementById('mytextarea'))"
Or you could pass just the id attribute value:
onclick="manipulate('mytextarea')"
in which case the function would need to use document.getElementById(), but on its parameter, not a wired-in string.
The first approach is more flexible in the sense that it lets you construct a reference in some other way too, e.g. document.getElementsByTagName('textarea')[0].
You could combine the approaches, by writing the function so that it can handle both kinds of parameters. It could e.g. first check whether its argument is of string type and use document.getElementById() on it if it is, otherwise expect it to be a reference to an element. And you should probably have some sanity checks in the function, testing that what you get or construct is really a reference to a textarea element.

I dint get what exactly you want to do but here you can get value of textbox on it's change event
<script>
$(document).ready(function () {
$('input[id$=mytextarea]').change(function () {
alert($(this).val());
.............
now you have got the value so convert it to decimal and do other stuff
});
});
</script>

Related

Change Spotfire Document Properties value using javascript

I want to Change the value assigned to a Document Property in spot fire. Lets say i have created a new document property called "Test1" as a string and assign it a value "a". Is there are way to change this value using Javascript every time i load the spotfire dashboard ?
I'm unaware of a way to use JavaScript for this, but you can assign a string document property via custom expression (if it's a List Box) or run an IronPython script each time the value changes. So, you could set the expression to the current date, datetimenow() and then every time it's loaded the IronPython script would fire. However, I don't see why you'd need the property control for this.
I suppose it really depends on what you want the document property to be set to. Is it data from your tables? Output from complex code? These are all things to consider.
1) Create an input type property control using the Document Property you want to change.
2) Edit Html to assign parent element an id say "testInput". And add the script as shown below in the Edit HTML window.
<span id="testInput"><SpotfireControl id="7db34e6c423240f59fc99e6b80fa23ec" /></span>
<script>
$("#testInput input").val("after");
$("#testInput input").focus();
$("#testInput input").blur();
</script>
3) This script will change the document property value to "after" whenever you open a file.
As you comment seemed to suggest, something you can do is write this code in Python and attach the script to an action control, e.i. a Link or a Button. Something simple like: Document.Properties["Test1"] = newValue
or even: Document.Properties[changingProperty] = newValue
allowing the code to be more reusable.
Then you insert Javascript into the Text Area as well to the effect of: $("#VeryLongSpotfireControlID").click();
Which should simulate clicking on action control, which in turn triggers the Python script to update the value. Just be careful not to use this approach when it would result in reloading the text area HTML, as this will re-trigger the Javascript, thus creating an endless loop.
I believe I have found a possible solution/work-around for the issue, entirely based on pure JavaScript (since TIBCO removed jQuery starting from Spotfire X). The solution is to force a simulated Enter Keystroke while focusing the input box to trigger updating the Document Property. (No data function and R needed)
HTML (SpotfireControl Element is an single line input-box for a Doc. Prop.):
<div id="container"><SpotfireControl id="b8534f13dc62416db6d4eaab16030f5e" /></div>
JS (focus and blur might no longer be needed for this solution, but I'm still keeping them just in case):
const inputConfirmationEvent = new KeyboardEvent("keypress", {
    keyCode: 13,
    bubbles: true,
    cancelable: false
});
var elem = document.querySelector("#container input");
elem.value = "stringValue";
elem.blur();
elem.focus();
document.querySelector("#container input").dispatchEvent(inputConfirmationEvent);
Hope it helps someone.
Best,
Aaron

accessing form variables (e.g. input tags) in javascript function: Is it better to pass the value or use a selector to acces it? (javascript/jQuery)

I am currently passing all variables to the function. I'm just wondering if there's a negative to this method or is it better to just access the form variable via a jQuery selector e.g. $("#namefield").val().
Maybe passing the value is better from a security/readability POV?
I did search the net but came across nothing on this topic.
Here is a sample code to what I'm using now.
<form>
<input id="myname" name="myname" type=text">
</form>
<script>
doSomething($("myname").val());
function doSomething(myname) {
console.log(myname);
//console.log($("#myname").val());
}
</script>

Taking Values of a Form and Using Them for Comparison in Javascript

I'm attempting to create an HTML-based game. The game is supposed to use a or tag to accept data from the user. I'd like to then assign the data entered to a variable in Javascript for comparison. The comparison would then be used to alter the page, bringing the next part of the game into view. How would I assign the value of the input that the user types into to a Javascript variable for comparison?
I thought something along the lines of:
function(){
document.getElementByID("submit");
}
would work for this situation, but I'm not sure.
The code I already have is rather simple, as you can see here: Fiddle
I'm pretty new to JS/jQuery, so forgive me if this question is just incredibly easy to answer!
There are many ways to do this.
It seems like the way you are going is using a button to say "read my input now".
In that case, you can add an event handler to the button to read what is in there.
See the following:
<h3>You've entered a dungeon. Do you want to CONTINUE or EXIT?</h3>
<div id="actionInterface">
<input type="text" id="myInput" value="User"/>
<button id="clickMe">Enter Option</button>
</div>
<script>
var myVar;
$("#clickMe").click(function(){
myVar = $("#myInput").val();
alert(myVar);
});
</script>
This will put the value of an object into a variable:
function(){
var x = document.getElementById("my_object").value;
}

Can't pull input-field value located beyond form tag

Problem
I use popup calendar, which is launched via href. I need to pass 'document.tstest.timestamp' (date input field) parameter into javascript function. And all worked well, BUT:
I want to include this tag-file into another form, so I can't use form
<form name="tstest">
in my tag file. As a result, without form I can't find document.timestamp input-field (as I understand due window.object hierarchy)
My tag file:
<form name="tstest">
<input type="Text" id="time_stamp" name="timestamp">
<a href="javascript:show_calendar('document.tstest.timestamp',
document.tstest.timestamp.value);"> showCalendar</a>
</form>
<script>
function show_calendar(target, value) {
............
}
</script>
Help me, please, to find out solution.
Your element has an id attribute on it so you can just use document.getElementById() to get a reference to it. I'd suggest modifying your show_calendar function to either take the id or a reference to the element directly, though, since you'll likely need to reference it again inside of that function.
You should be able to do the following anywhere on the page and get the element:
var elem = document.getElementById("time_stamp");
var myVal = elem.value;
This would work too
<a href="javascript:show_calendar('document.tstest.timestamp',
document.getElementById('time_stamp').value);"> showCalendar</a>
Don't use document.tstest as syntax instead use document.getElementById("time_stamp")
Also remember an id is unique so don't put 2 elements with a same I'd on a same page

javascript not getting value of input box

I seem to be having trouble with passing the value of an input box to anything else in my javascript.
It's not producing any errors - and I remember reading somewhere that you can have issues if the document hasn't finished loading - but I'm pretty sure it has!
The code in question is as follows in the javascript:
var address = getElementById(addyInput).value;
document.getElementById('add').innerHTML = address;
And in the HTML
<form>
<input name="addyInput" placeholder="Don't forget postcode!">
</form>
<button id="start" onclick="initialize()">Start!</button>
<p>Address Test
<div id="add"></div>
</p>
I know that the button itself is working as it fires the rest of my code fine without the offending code - however the moment I uncomment that little block at the top, it just does nothing. (no errors etc)
Any help on that one would be hot! Thanks :)
Update:
I now have it working! Thanks muchly for all the help!!
Your form needs to look like this (add an id attribute):
<form>
<input id="addyInput" name="addyInput" placeholder="Don't forget postcode!">
</form>
And the first line of Javascript needs to look like this (since getElementById is expecting an ID rather than a name).
var address = getElementById('addyInput').value;
Additionally, getElementById expects the id argument to be a string (hence the quotes). If you pass it addyInput without quotes, it'll try to interpret addyInput as a variable which has a value of undefined and you won't get back the DOM element you want.
Or, if you were using jQuery, you could leave the form markup as-is and change the Javascript to this:
var address = $('input[name=addyInput]').val();
Make sure to specify and id on the input. You only have a name.
You need to add the id "addyInput" to your form input rather than just the name.
getElementById expects a string.
var address = getElementById('addyInput').value;
If you put this directly into a script section in the head, then you will have a problem because the page is not loaded completely but the code is executed already.
And of course you should define an id for the input element as the others already said.
what you are getting is an array, you need to fetch your array into some readable data. Try something like:
$value = array_shift( $yourarray );
or if it's a multi value array you can just loop it to fetch out the values.

Categories