I have a problem to set an attribute on another element.
I'm using PHP code with JS and HTML and it looks like:
<textarea name='$id' id='$id' class='regular-text' cols='60' rows='1' tabindex='2'"
. "onkeypress =\"javascript:document.getElementById('content').setAttribute('onkeypress', document.getElementById('so_observer_heading_count').innerHTML = document.getElementById('content').value.length)\">$value</textarea>
You must know I have 2 elements. The first('content') one I use for writing a text and in the other one('so_observer_heading_count') there shall be updated the number of signs from the first element.
So my question is, how can I set an attribute on another element.
I have already checked that the name is correct and when i change the content of the textarea on the 2. element I get the right amount from the first element. But I want only to change content in the first element to refresh the amount.
And I don't want to change the code of the first element! And don't be confused by the textarea, in future this shall be a label or something else.
First of all:
Don't use the inline-eventbindings. Always use "real" javascript, (this way you also prevent the problem of escaping your quotes) this is far more cleaner and more maintanable.
Also you code has another problem: You have an eventhandler "keypress" on the textarea, which binds on every "keypress" another attribute to your content-element. This is not very performant and most likey won't work properly. This code should be everything you need:
document.getElementById('content').addEventListener("keyup",function(){
var obs = document.getElementById('so_observer_heading_count');
obs.innerHTML = this.value.length;
});
Here is a demo for you.
Edit: I changed the event from keypress to keyup to 1) count properly 2) take charakter deletion into account.
I'd say "setAttribute" won't work on a method. Try instead :
document.getElementById('content').onkeypress = function() { document.getElementById('so_observer_heading_count').innerHTML = document.getElementById('content').value.length };
Well, there are certainly more.. efficient ways of doing this, but the thing you forgot to do was escape your single quotes, so the js treats your event as a string, instead of parsing the end result:
<textarea name='$id' id='$id' class='regular-text' cols='60' rows='1' tabindex='2'"
. "onkeypress =\"document.getElementById('content').setAttribute('onkeypress', 'document.getElementById(\'so_observer_heading_count\').innerHTML = document.getElementById(\'content\').value.length;')\">$value</textarea>
Elsewise.. I would personally do this through an included js file that executes the above line on document load/ready, versus every time a key is pressed.
Update: slight edit so anything I removed from your above code was added back, incase you want to just straight-copy it in.
Related
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
So, here's a script that I've written to make some inputs dependent on an affirmative answer from another input. In this case, the 'parent' input is a radio button.
You can see that it hides parent divs of inputs when the document is ready, and then waits for the pertinent option to be changed before firing the logic.
If you'll look at the comment near the bottom of the javascript, you'll see what's been stumping me. If I remove the if statement, the change function does not fire. If I set the variable so that there is not an error logged in the console, then the change event does not fire.
If I change the jquery selector to $('select').change... the event fires, but obviously won't work on a radio button. Changing it to $('input').change... also fails.
<script type="text/javascript"><!--
$(function(ready){
$('#input-option247').parent().hide();
$('#input-option248').parent().hide();
$('#input-option249').parent().hide();
$('#input-option250').parent().hide();
$('#input-quantity').attr('type', 'hidden');
$('#input-quantity').parent().hide();
$('input[name="option\\[230\\]"]').change(function() {
if (this.value == '21') { //If yes, display dependent options
$('#input-option247').parent().show().addClass('required');
$('#input-option248').parent().show().addClass('required');
$('#input-option249').parent().show().addClass('required');
$('#input-option250').parent().show().addClass('required');
} else if (this.value == '22') { //If no, hide dependent options
$('#input-option247').parent().hide().removeClass('required');
$('#input-option248').parent().hide().removeClass('required');
$('#input-option249').parent().hide().removeClass('required');
$('#input-option250').parent().hide().removeClass('required');
}
});
//I don't know why this is necessary, but the input.change() event WILL NOT FIRE unless it's present. If I set the variable, then it breaks the change function above. If it's not here, it breaks the change function above. I'm stumped.
if(poop){}
});//--></script>
I'm really hoping that someone will see something rather obvious that my tired brain won't see. This is such a simple script, and I'm pulling my hair out over what seems like a rather annoying bug.
If you selector has special characters you need to use \\ before those characters.
$('input[name="option[230]"]')
should be
$('input[name="option\\[230\\]"]')
See http://api.jquery.com/category/selectors/
This may or may not be a good answer, but I managed to get the problem solved. I have another script on the page that is firing on the change event using this selector: $('select[name^="option"], input[name^="option"]').change(function() {
My best guess is that both functions cannot fire using a single change event from the same element. I moved the functional part of the code above to be within the second script, and it seems to be working as expected. If anyone wishes to contribute an answer that explains this behavior, I will accept it.
Curious problem. I need to empty a <textarea> then replace it with other content. The tests in the JSFiddle will work if nothing is manually typed, but as soon as anything is entered in the textarea by hand, the methods will cease to work.
http://jsfiddle.net/ecFjH/
I understand that I can simply just .val('New stuff here'), however I need HTML entities such as > and < to appear as < and >, which .val() will not accomplish.
It sounds like your real problem is that you want to decode HTML entities to render them in a text area. You could use the following to do this:
var content = 'text > HTML';
$('#myText').val($('<div/>').html(content).text());
However, you should only do this with trusted content. If the content for the textarea is not created by you, it could contain malicious HTML, which you would unsafely be creating on the page.
For a more thorough example, see this answer to essentially the same question; note that the accepted answer repeats the above, but the linked answer is safer.
Your text area has no html. use just $('#myText').val('Button 2 was pressed'); that will remove the previous content and put the text "Button 2 was pressed".
Check here (updated with < and >)
Often times, when I use struts 2 tags, the loading of a page will be incomplete apparently because of single quote or double quote characters from the struts 2 tag interfering with such characters from javascript.
One example I am very eager to get working is as follows:
var me = '<s:a href=\'http://www.google.com\'>Google Link</s:a>';
$('#appnSelect').html(me);
So what I am concerned about is when single and double quotes are inside that me string on the right side of line 1. Ultimately, I need to get <s:select> to work, but this problem seems to creep in with a number of tags like the above example. Replace the <s:a> tag with an <a> tag, and voila, it works. However, when the <s:a> tag gets expanded, the page will incompletely load.
Is there an easy solution somewhere I am missing? One thing I did try was with the theme attribute setting theme="simple" because sometimes that helps me when the output gets rendered incorrectly. That did not work in this case.
Generating HTML from tags like that in the middle of a JavaScript string constant is always going to be an ugly business. In addition to quote characters, you're also likely to get newlines. Strictly speaking you don't know what you're going to get, and you can't control it.
One thing that comes to mind is that you could drop the tags into dummy <script> blocks marked as a non-JavaScript type:
<script id='anAnchor' type='text/html'>
<s:a href='http://www.google.com'>Google Link</s:a>
</script>
The browser won't try to execute that. You can then do this in your JavaScript code:
$('#appnSelect').html($('#anAnchor').html());
What should work with very little thinking:
<s:a id="google" style="display: none;" href="www.google.com">Google Link</s:a>
Now just grab the the element using the id in your script. Might be better if you set up a class. There are id, style and class attributes for all struts2 tags.
I believe the issue is with your escaping of the single quotes inside the <s:a> tag. In my experience with using <s:url>, I've done the following:
var url = "<s:url value='/someAction.action' />"
I believe the same syntax should hold true for <s:a>.
Additionally, look in your JSP container's error log, and see if you can find an error relating to that <s:a> tag. That may provide some additional insight to the problem.
This is my answer, which will not be the best answer because Pointy's response pointed me in the correct direction. However, up votes still appreciated :)
First, you need the script blocks which are not rendered. I have 2 because a checkbox will toggle between which one is displayed:
<script type="myType" id="abc">
<s:select name="selectName" list="#list1" listValue="%{prefix + '-' + name}" theme="simple"/>
</script>
<script type="myType" id="abc2">
<s:select name="selectName" list="#list2" listValue="%{prefix + '-' + name}" theme="simple"/>
</script>
Next, I create a region which is blank in the html code
<div id="innerRegion">
</div>
Then, I need to put something on the screen when the page first comes up, so go with this:
<script type="text/javascript">
$(document).ready(function(){
$('#innerRegion').html( $('#abc').html() )
});
I needed to put this at the end of my document because onLoad was already being used by a parent page. So I am saying abc is the correct default.
Then I need logic to handle what happens when the checkbox is pushed:
var buttonPressed = false;
$(window).load(
function()
{
LocalInit();
});
function LocalInit() {
$('#myForm input[name=buttonValue]').change(
function()
{
buttonPressed = !buttonPressed;
if (buttonPressed == true)
{
$('#innerRegion').html( $('#abc2').html() )
} else
{
$('#innerRegion').html( $('#abc').html() )
}
$('#dataId').href = document.location.href;
}
);
}
I think what was tripping me up ultimately was that I was trying to force the s:select tag through jQuery functions when as you see above it did not turn out to be necessary. I could just write the s:select as normal.
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.