How to insert text into a form with JavaScript - javascript

I'm trying to create a simple extension for personal use. It's partially from laziness, and partially from an urge to learn. I've never made extensions before, but I've been looking at the documentation. Now I just need to write the code. What I'm trying to do, is when the browser loads a certain page, to insert text into a specific form. The form is as follows
<div id="set_tags" class="advanced_option">
<label for="post_tags" class="inline_input_label" id="post_tags_label"
onclick="Element.remove($(this))"
style="left:8px; right:auto; text-align:left">tags</label>
<input id="post_tags" name="post[tags]" type="text"/>
</div>
I haven't worked much with javascript, so is there a way to add the text "Music" to this when the page is loaded?

You can use the onload function to start your function.
http://javascript.about.com/library/blonload.htm
Since you are new to javascript you may want to get familiar with unobtrusive javascript (http://www.onlinetools.org/articles/unobtrusivejavascript/chapter4.html) which I find is a better way to write javascript, as you can then easily comment out javascript and see how it works when that is disabled. But, it would be easier to learn this in the beginning.
To get the input tag you can use document.getElementById() which would be something like:
var elem = document.getElementById('post_tags');
Then, to add text to this field there should be a value property in your input definition above, and you would just do:
elem.value = "Music";

document.getElementById("post_tags_label").appendChild(
document.createTextNode("Music"));
I'm assuming that you want to put it at the end of the element post_tags_label.

This is really easy to do if you use GreaseMonkey. It's perfect for personal changes you want to make to web pages, etc.

Related

Showing in html, the value calculated in a JavaScript function

I am just getting started with JavaScript so it is a fairly simple question..
I have a value "x" which was calculated/derived in a JavaScript function "y".
I wish to display this value in HTML. I am using Internet Explorer (yeah..) and the "" tag is not valid here...
Since it is a single vale I won't be using a dropdown box. The other alternative being "". Can I show this value in a label? If so how, if not what do I do?
Technically you can use any element you like. The usual DOM methods (document.createTextNode, someElement.appendChild, etc) will work.
A <label> almost certainly wouldn't be suitable though. It is designed to tell the user what to enter into an input or other form control.
Pick the element which has the semantics that best match that data you are outputting. (Keeping in mind that if nothing has suitable semantics then <div> and <span> don't have any so are the safe fallback).
Say you have value "X",
With the following Markup:
<label id="lblMyValue">
</label>
Your code, should look for the DomElement with that ID:
document.getElementById("lblMyValue").innerHTML= X;
I was also a beginner (and am still learning a lot), and I must give you the following advice: Start using JQuery. Even if it is not always wanted, coding with it when you can will really teach you the "ins and outs" as it were, of JavaScript.
Have Fun Learning.
You can display the calculated result in a variety of places, depending on what makes the most sense. If you want to show it in an element that contains HTML, you would use the innerHTML property. If you want to show it in some input element, you could use value instead.
var result = 2 + 2;
document.getElementById('infoSpan').innerHTML = result;
document.getElementById('infoTextInput').value = result;
<div>Result: <span id="infoSpan"></span></div>
<div>Result: <input id="infoTextInput" type="text" /></div>

Create new (not change) stylesheets using jQuery

We've got a little tool that I built where you can edit a jQuery template in one field and JSON data in another and then hit a button to see the results immediately within the browser.
I really need to expand this though so the designer can edit a full CSS stylesheet within another field and when we render the template, it will have the CSS applied to it. The idea being that once we've got good results we can take the contents of these three fields, put them in files and use them in our project.
I found the jQuery.cssRule plugin but it looks like it's basically abandoned (all the links go nowhere and there's been no development in three years). Is there something better or is it the only game in town?
Note: We're looking for something where someone types traditional CSS stylesheet data in here and that is used immediately for rendering within the page and that can be edited and changed at will with the old rules going away and new ones used in their stead. I'm not looking for something where the designer has to learn jQuery syntax and enter in individual .css("attribute", "value") type calls to jQuery.
Sure, just append a style tag to the head:
$("head").append("<style>p { color: blue; }</style>");
See it in action here.
You can replace the text in a dynamically added style tag using something like this:
$("head").append("<style id='dynamicStylesheet'></style>");
$("#dynamicStylesheet").text(newStyleTextGoesHere);
See this in action here.
The cleanest way to achieve this is by sandboxing your user-generated content into an <iframe>. This way, changes to the CSS won't affect the editor. (For example, input { display:none; } can't break your page.)
Just render out your HTML (including the CSS in the document's <head>, and write it into the <iframe>.
Example:
<iframe id="preview" src="about:blank">
var i = $('#preview')[0];
var doc = i.contentWindow || i.contentDocument;
if (doc.document) doc = doc.document;
doc.open('text/html',true);
doc.write('<!DOCTYPE html><html>...</html>');
doc.close();
If the user should be able to edit a whole stylesheet, not only single style attributes, then you can store the entered stylesheet in a temporary file and load it into your html document using
$('head').append('<link rel="stylesheet" href="temp.css" type="text/css" />');
sounds like you want to write an interpreter for the css? if it is entered by hand in text, then using it later would be as simple as copy and pasting it into a css file.
so if you have a textarea on your page to type in css and want to apply those rules when you press the button, you could use something like this (only pseudocode, needs work):
//for each css id in the text area
$.each($('textarea[name=cssTextArea]').html().split('#'), function({
//now get each property
$.each($(this).split(';'), function(){
$(elem).css({property:value});
});
});
then you could write something to go through each element that your designer typed in, and get the current css rules for it (including those that you applied using some code like the snippet above) and create a css string from that which could then be output or saved in a db. It's a pain and much faffing around with substrings but unfortunately I don't know of a faster or more efficient way.
Hope this atleast gives you some ideas

Fill forms in JavaScript

I'm currently a student in Software Engineering, and I'm trying to create a small program (I don't know if the word "macro" is appropriate for it) in HTML or JavaScript, to fill a form from a webpage.
The webpage has the following code, placed in the head section:
input type=password name=code size=8 maxlength=8
input type=password name=nip size=8 maxlength=8
input type=password name=naissance size=8 maxlength=8
I've been thinking of maybe using JQuery, as I've browsed a little bit on the internet to figure out how to do it, but I don't really know how to do that. I'm pretty sure the only way to do it is to modify the values of the fields "code", "nip" and "naissance", but how do I get access to them from an external file?
Please note that I have bases in HTML and JavaScript, but nothing amazing - I'm still learning :/
Since you're looking to use jQuery, this might be a good place to start:
http://api.jquery.com/attribute-equals-selector/
Next might be a good tutorial in jQuery to get you started. I'm going to assume you can find those on your own, and I'm going to jumpstart your work:
var selector = 'input[name="code"]'; // <-- we define the element we want to find here
// we will use that to select a jQuery element like this --> $(selector)
$(selector).val('CODE!!'); // <-- it's just that easy to set a value.
So if that's what it takes to set the value for code from javascript, you can guess what the other two would look like. I'll give you a hint on the second one:
$('input[name="nip"]').val('NIP!!');
Of course, all this assumes you do use jQuery in the browser to accomplish this
I believe what you are looking for is simply accessing the fields from javascript. You can include any external javascript on the HTML page:
<html>
<head>
<script src="http://someexternalurl.com/js/jsfile.js" type="text/javascript"></script>
...
Then in this javascript file you can access the elements as:
alert(document.getElementByName("nip").value);
document.getElementByName("nip").value = "abc";
Hope that helps.
You can accomplish you project by going through this links
w3school
tizag
jqueryui
jquery
Go through this links
with regards
Wazzy

Get values between DIV tags?

How do I get the values in between a DIV tag?
Example
<div id="myOutput" class="wmd-output">
<pre><code><p>hello world!</p></code></pre>
</div>
my output values I should get is
<pre><code><p>hello world!</p></pre>
First, find the element. The fastest way is by ID. Next, use innerHTML to get the HTML content of the element.
document.getElementById('myOutput').innerHTML;
document.getElementById("myOutput").innerHTML
innerHtml is good for this case as guys suggested before me,
If you have more complex html structure and want to traverse/manipulate it I suggest to use js libraries like jQuery. To get want you want it would be:
$('#myOutput').html()
Looks nicer I think (but I wouldn't load whole js library just for such simple example of course)
Just putting all above with some additional details,
If you are not sure about that div having some id is not there on html page then to make it sure please use.
var objDiv = document.getElementbyId('myOutput');
if(objDiv){
objDiv.innerHTML;
}
This will avoid any JavaScript error on the page.

Changing input text value with Javascript doesn't change display

I'm trying to change the value of a text input field based on user actions. I'm doing it like this:
document.getElementById(textFieldID).value = newValue;
It isn't quite working -- the original text in the field remains on the screen, unchanged. However, when I submit the form, it behaves as though the value was indeed changed correctly. (And a debug alert confirms that yup, I'm hitting that bit of the code and passing in the right field ID and text value.) Anybody have any insights? Is there something I need to be doing to redraw the input element?
Edit: Per Jeff B's request, and per the fact that this seems to have everybody stumped, here's some relevant bits of code:
<script LANGUAGE="JavaScript" TYPE="text/javascript">
function changeText(changeSelector)
{
var myindex = document.getElementById(changeSelector+"Recent").selectedIndex;
var SelValue = document.getElementById(changeSelector+"Recent").options[myindex].value;
document.getElementById(changeSelector).value = SelValue;
document.getElementById("historicalText").value = SelValue;
document.getElementById("historicalTextSelect").value = changeSelector;
}
</script>
<input onChange="updateScrollingPreview1217(this); return true;" type="text" id="crawlMsg1217" name="crawlMsg1217" size="60" maxlength="1000" value="">
<select id="crawlMsg1217Recent" name="crawlMsg1217Recent" onchange="javascript:changeText('crawlMsg1217');">
[options go here]
</select>
And that "onChange" handler isn't what's gumming up the works; I get the same behavior with or without it.
Edit 2: It looks like the problem is being caused by "JSpell", a third-party spelling checker our product uses. (I'm told that clients prefer using it to a spellcheck built into the browser; go figure.) It appears to be slightly misconfigured on my test machine, so I'm going to try straightening that out and praying that it makes the problems go away. If it doesn't ... should be interesting.
Edit 3: Yup. Fscking JSpell. Just posted a complete answer for the sake of posterity, will accept it tomorrow when I'm allowed. My thanks to everybody who tried to help; +1's all around, wish I could give more.
I have confirmed that the culprit is indeed JSpell, and that the precise trouble spot is this line:
window.onload=jspellInit;
Despite the prayers mentioned in Edit 2 above, making sure it was configured correctly did NOT make the problem go away. And this line is indispensable to JSpell's functionality. I don't know if JSpell always hoses Javascript functionality this way, or if there's some sort of perfect storm of factors that's causing it to pick a fight with my page, but that is indeed the source of my problems.
My thanks to everybody who tried to help. This was obviously a bit of a no-win in terms of getting the right answer, since it was caused by a component that was seemingly entirely unrelated and thus didn't get mentioned by me, but you at least confirmed that I was (in theory) doing things right and not simply going insane.
Is the document's id actually "textFieldID" or is "textFieldID" a javascript variable that contains the ID of the text input to change? If it is not a variable, I believe you should make it:
document.getElementById('textFieldID').value=newValue;
It's hard to debug this without the context, since the code you have ought to work fine. Can you confirm that you've got the right node by doing something like:
document.getElementById(textFieldID).style.border = "4px solid red";
What does any other element on the page have a name attribute that is the same as the id?
Internet Explorer 8 and later. In IE8
mode, getElementById performs a
case-sensitive match on the ID
attribute only. In IE7 mode and
previous modes, this method performs a
case-insensitive match on both the ID
and NAME attributes, which might
produce unexpected results. -
http://msdn.microsoft.com/en-us/library/ms536437%28VS.85%29.aspx
Try alerting your the nodeName and id ofr the returned element and make sure its the input you expect.
Use div element instead of textfield. I had same problem, my textfield which is changed with another script wasnt get the right value. you can easily use any div element like textfield with some CSS. than you can get the value from div using innerHTML.

Categories