Javascript innerHTML with onclick not working - javascript

I have some AJAX, it pulls in the following, which is added to a div using innerHTML.
Add
Then when I press the "Add" link, it will add "TEST" into textareax.
If I have it in the HTML of the document from the start, it works perfectly, but when I pull it in using AJAX and using innerHTML to add it to the div the "Add" link does not work.
I think it might be a problem because it has javascript in it and I am just adding it using innerHTML, but don't know how to solve this.

\r\n is a newline, but is parsed by JavaScript already. The innerHTML will be set to:
<a href="#" onclick="javascript:document.getElementById('textareax').value += '
TEST';">Add</a>
which does not work (a syntax error; JavaScript strings cannot have literal newlines).
You'd need to double-escape with \\r\\n so that it becomes \r\n when it is parsed by JavaScript (\\ becomes \ and the r will be unaffected). Then the \r\n will be kept in the onclick handler, so that the newline is indeed added to the textarea: http://jsfiddle.net/r6bhE/.

onclick="javascript:document[...] is incorrect syntax. The onclick attribute is a javascript event, and doesn't need the javascript scheme indication. You can just place the script directly into the attribute value:
Add
It's also a good idea to return a value when intercepting mouse events (true to pass the event on, false to cancel it).

Related

How to send text within a textarea having the attribute style="display: none;" through C# and Selenium

I need to write in the textarea with the simple sendkeys function in selenium.
This textarea (ID = 'txtSkillsTaught-Value') is followed by a script tag where the visibility of the textarea is hidden i guess due to which I am not able to write text.
tried the simple
driver.findelment(By.Id("txtSkillsTaught-Value")).sendkeys("text");
even tried switching to the iframe above but didnt worked
attached the image of HTML code
thanks,
Amey
In one hand if it is not visible maybe is not a good idea put text inside... But, in the other hand I need made things like that sometimes. I usually change the visibility for this element before send the keys with a javascript execution in my selenium code (I use java but for C# should be more or less the same):
executeScript("$('.yui-button.yui-link-button').find(\"textarea[id='txtSkillsTaught-Value']\").css({'opacity':'1', 'visibility':'visible', 'display':'block', 'position':'relative', 'transform':'none'})");
driver.findelment(By.Id("txtSkillsTaught-Value")).sendkeys("text");
That should work.
As per the HTML you have provided the <textarea> is out of the <iframe> but having the attribute style="display: none;". So to send a character sequence to the <textarea> you can use the following solution:
IWebElement element = new WebDriverWait(driver, TimeSpan.FromSeconds(10)).Until(ExpectedConditions.ElementToBeClickable(By.XPath("//td[#class='t-editable-area']//textarea[#class='t-content t-raw-content' and #id='txtSkillsTaught-value']")));
((IJavaScriptExecutor)driver).ExecuteScript("return arguments[0].removeAttribute('style')", element);
element.SendKeys("Amey");

JavaScript setAttribute on another element

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.

jquery postback failing

I'm trying to initiate a postback invoking the click function of a server-running element, as to run some C# code, in the event of a particular jquery dialog button click.
I am using a modal dialog with buttons as per this jQuery UI example. I have attempted using all of the different answers for javascript/jquery postback invocations in this question.
I've set a couple of breakpoints in my C# code to see if these postbacks are getting called, but nothing is getting hit.
I have this dummy element in my ascx file to use:
<a id="anchorId" runat="server" onclick="return true;" onserverclick="TryLogin"></a>
I've attempted to get this postback to occur a few different ways:
$("#anchorId").click(); //just simply does nothing
document.getElementById("anchorId").click(); //This one gives me a null javascript error
$("document").getElementById("#anchorId").click(); //tells me [object] doesn't have a getElementById
__doPostBack('<%=anchorId.UniqueID %>', '');//Also does nothing in the jQuery code, but works in standard javascript code
Lastly I did try retrieving the unique ID in the code behind as:
string id = anchorId.UniqueID;
and replaced in the javascript this way:
__doPostBack('Softening_Main$anchorId', '');//Still does nothing, and no javascript error
I really need some help here, any ideas?
There are couple of issues in your code.
$("document") will not select document instead will look for document tag element on the page. You should use $(document) removing the quotes.
Also getElementById is a JavaScript method of document object which is used to find element by id. When you use getElementById don't specify # in the id. # is used by jQuyer to differentiate between various selectors.
Remove inline onclick="return true;" from anchor and try this.
$("#anchorId").click(function(e){
__doPostBack('<%=anchorId.UniqueID %>', '');
return false;
});

Passing apostrophe to javascript function

I am not finding a solution on this one using JavaScript (to utilize localStorage) in a JSP.
Trying to pass something with apostrophe. I have done a .replaceAll() and replaced the ' with ' and it still passes it as an '.
I have also tried a .split("'") and replaced the apostrophe with:
(\' , ' , \', '' , ''' and '\'')
All of these just pass an apostrophe to the function (what I see when I hover over the link) like this:
Save job
With a and b being the two split substrings but with no effect. I do notice that spaces are converted into %20, but that's little comfort. Any other ideas?
Your JSP code is irrelevant. Decide what HTML you want to produce and produce it.
The following are all valid HTML markup:
<a href="saveJob('Bob\'s Question')"> …
<a href="saveJob("Bob&apos;s Question")"> …
<a href="saveJob('He said "Go Away"')"> …
<a href='saveJob("He said \"Go Away\"")"> …
… and the following are invalid:
<a href="saveJob('Bob's Question')"> <!-- JS string ends early -->
<a href="saveJob("Bob's Question")"> <!-- HTML attribute ends early -->
<a href="saveJob('Bob&apos;s Question')"> <!-- JS string ends early -->
<a href="saveJob('He said "Go Away"')"> <!-- HTML attribute ends early -->
You cannot use your HTML attribute delimiter in your attribute value except as an HTML entity. You cannot use your JavaScript string delimiter in your JavaScript string unless you escape it, even if you use an HTML entity to describe it.
In general, you should not be putting JavaScript in your HTML (you should attach event handlers to your markup programmatically, from script), and you especially shouldn't be abusing an HTML anchor as a JavaScript trigger (either use an HTML anchor to a valid URL and let JavaScript hijack the link if enabled, or use a <button> or other element to invoke script-only side effects).
As you've noticed, such manual string escape tasks can be quite tricky; covering apostrophes won't even get you all the way: what if there's a newline in the string? That would break the script as well.
I would recommend converting your data to a JSON object, perhaps using JSON-taglib. This should take care of all required escaping for you.
The Phrogz solution
<a href="saveJob("Bob&apos;s Question")">
works fine if you have only apostrophes in your text.
If your text contains both apostrophes and quotes, you can use a hidden div (div with style='display:none;') for the text, pass the id of the div to saveJob instead of passing the text itself, and get the text inside saveJob by using
document.getElementById(myId).innerHTML

Javascript beginner: how to replace a href text if it matches a specified string?

When someone posts a link to another page on my website, I'd like to shorten the a href text from something like: http://mywebsite.com/posts/8 to /posts/8 or http://mywebsite.com/tags/8 to /tags/8. Since I'm learning javascript I don't want to depend on a library like prototype or jquery. Is it recommended to use javascript's replace method?
I found w3schools' page here but my code was replacing all instances of the string, not just the href text.
Here's what I have so far:
<script type="text/javascript" charset="utf-8">
var str="http://www.mywebsite.com";
document.write(str.replace("http://www.", ""));
</script>
str = str.replace(/^http:\/\/www.mywebsite.com/, "");
someElement.appendChild(document.createTextNode(str));
Note that you're introducing a Cross-Site Scripting vulnerability by directly calling document.write with user input (you could also say you're not treating the URL http://<script>alert('XSS');</script> correctly).
Instead of using document.write, replace someElement in the above code with an element in your code that should contain the user content. Notice that this code can not be at the JavaScript top level, but should instead called when the load event fires.

Categories