I want to preface this with the fact that I am very very new to JavaScript. I appreciate your patience with me.
I'm trying to create a script that allows a user to input a name into a text-area, press submit and an image is displayed based on that name.
I managed to come up with this:
<html>
<body>
<form>
<input type="text" value="" id="imagename">
<input type="button" onclick="window.location.href='http://webpage.com/images/'+document.getElementById('imagename').value +'.png'" value="GO">
</form>
</body>
</html>
Which almost does exactly what I need -loads an image around what a user inputs. But what I want is not for the image to open in a new window, or download to my computer - I want it to display on the page when clicked as an image like the example here.
I'm sure that my inexperience with Javascript is the main cause of my being unable to figure this out. The script above is as far as I can get without screwing things up. Any help is appreciated.
When the button is clicked, get the value of the input and use it to create an image element which is appended to the body (or anywhere else) :
<html>
<body>
<form>
<input type="text" id="imagename" value="" />
<input type="button" id="btn" value="GO" />
</form>
<script type="text/javascript">
document.getElementById('btn').onclick = function() {
var val = document.getElementById('imagename').value,
src = 'http://webpage.com/images/' + val +'.png',
img = document.createElement('img');
img.src = src;
document.body.appendChild(img);
}
</script>
</body>
</html>
FIDDLE
the same in jQuery:
$('#btn').on('click', function() {
var img = $('<img />', {src : 'http://webpage.com/images/' + $('#imagename').val() +'.png'});
img.appendTo('body');
});
Are you after something like this:
<html>
<head>
<title>Z Test</title>
</head>
<body>
<div id="img_home"></div>
<button onclick="addimage()" type="button">Add an image</button>
<script>
function addimage() {
var img = new Image();
img.src = "https://www.google.com/images/srpr/logo4w.png"
img_home.appendChild(img);
}
</script>
</body>
Add a div with ID imgDiv and make your script
document.getElementById('imgDiv').innerHTML='<img src=\'http://webpage.com/images/'+document.getElementById('imagename').value +'.png\'>'
I tried to stay as close to your original as tp not overwhelm you with jQuery and such
You have to right idea generating the url based off of the input value. The only issue is you are using window.location.href. Setting window.location.href changes the url of the current window. What you probably want to do is change the src attribute of an image.
<html>
<body>
<form>
<input type="text" value="" id="imagename">
<input type="button" onclick="var image = document.getElementById('the-image'); image.src='http://webpage.com/images/'+document.getElementById('imagename').value +'.png'" value="GO">
</form>
<img id="the-image">
</body>
</html>
You were just missing an image tag to change the "src" attribute of:
<html>
<body>
<form>
<input type="text" value="" id="imagename">
<input type="button" onclick="document.getElementById('img1').src = 'http://webpage.com/images/' + document.getElementById('imagename').value +'.png'" value="GO">
<br/>
<img id="img1" src="defaultimage.png" />
</form>
</body>
</html>
First, I strongly suggest to use a Library or Framework to do your Javascript. But just for something very very simple, or for the fun to learn, it is ok. (you can use jquery, underscore, knockoutjs, angular)
Second, it is not advised to bind directly to onclick, my first suggestion goes in that way too.
That's said
What you need is to modify the src of a img in your page.
In the place where you want your image displayed, you should insert a img tag like this:
Next, you need to modify the onclick to update the src attribute. The easiest way I can think of is like his
onclick=""document.getElementById('image-placeholder').src = 'http://webpage.com/images/' + document.getElementById('imagename').value + '.png"
Then again, it is not the best way to do it, but it is a start. I recommend you to try jQuery and see how can you accomplish the same whitout using onclick (tip... check the section on jquery about events)
I did a simple fiddle as a example of your poblem using some google logos... type 4 o 3 in the box and you'll two images of different size. (sorry.. I have no time to search for better images as example)
http://jsfiddle.net/HsnSa/
Related
Im working on a simple commenting system for a website using the postmail API. The thing is that i want to give the user a better error when something goes wrong because postmail only changes the URL. For this is i check the URL of the page when the page loads and if that contains an error i want to change a element to that error. The only problem is that detecting it works fine and i can also create a alert with the error but the text wont change... Can anyone help me with this?
js:
<script>
function sending(){
document.getElementById("submit_form").value = 'Sending...';
};
if (window.location.href.indexOf("err") != -1){
alert("An error occured! Please make sure to check your input fields."); //this works fine
document.getElementById("ertext").innerHTML = 'Error!'; //this doesnt
};
</script>
HTML:
<form action="https://postmail.invotes.com/send"
method="post" id="email_form">
<h2>Feedback</h2>
<h4>Your Email:</h4>
<input type="text" name="subject" placeholder="aa#aa.aa" style="width: 80%;"/><br>
<h6>Your Message:</h6>
<textarea name="text" placeholder="Give some feedback" style="resize: none; width: 80%;"></textarea>
<input type="hidden" name="access_token" value="--" />
<input type="hidden" name="success_url" value="./comments.html" />
<input type="hidden" name="error_url" value="./comments.html?err=1" /><br><br>
<input id="submit_form" type="submit" value="Send" onclick="sending();" />
</form>
<p id="ertext"></p>
<br> <br>```
The Javascript code needs to be executed after the html document is loaded. As mentioned before you can achieve this by putting the script tag somewhere below all referenced elements in your DOM.
Another possibility is to put your JavaScript into a separate file "test.js" and then include it in the head of your document:
<script type="text/javascript" src="test.js" defer></script>
Using the defer attribute makes sure the script will be executed after the page finished parsing.
It depends on where you put the script. If you put it before the DOM element, document.getElementById("ertext") wouldn't find the element.
<script>
// before the DOM element
// Below line would raise TypeError: Cannot set property 'innerHTML' of null
document.getElementById('ertext').innerHTML = location.href;
</script>
<h1 id="ertext">the element</h1>
<script>
// after the DOM element
// You'd see `the element after` which indicates
// the script that is after the DOM element can find the element.
document.getElementById('ertext').innerHTML += ' after';
</script>
I was testing and trying to make an little form that when the user entered their name, it would take that name and display it on to the screen.
<html>
<head>
<center><h1>Test-Page</h1></center>
</head>
<body>
<div class="someRandomStuff">
<h2 id="testingID">What is your first name?</h2>
<form name="input" action="login.js" method="post">
Name: <input type="text" name="userID"/>
<input type="submit" value="Submit"/>
</form>
</div>
</body>
Here is the js file
function displaySystem(name) {
document.getElementById("testingID").innerHTML("Ah, hello there" + name)
}
I know that I could probably do this in one HTML file, however I want to try and make the js and HTML separate. ANY help is appreciated.
You don't send data to a JavaScript function, but a JavaScript function can retrieve form data.
For example, and input of type text can be retrieved using its value property:
var input = document.getElementById("userID");
var value = input.value;
I know that I could probably do this in one HTML file, however I want
to try and make the js and HTML separate.
Nice step. In fact, there's no practical difference in terms of retrieving form data or manipulating the document from an inline script or a script that's included using a <script src=... element. The main difference is a script embedded in the HTML document won't be cached, while a one included as a separate file will be cached (obviously, there're other reasons if we talk about good separation of concerns!).
use onkeypress event on textbox and pass this to display that value and use that parameter in function to display it
<div class="someRandomStuff">
<h2 id="testingID">What is your first name?</h2>
<form name="input" action="login.js" method="post">
Name: <input type="text" name="userID" onkeypress="displaySystem(this)"/>
<input type="submit" value="Submit"/>
</form>
</div>
//javascript function
function displaySystem(name) {
document.getElementById("testingID").innerHTML("Ah, hello there" + name.value)
}
I'm trying to take a user input, turn it into a JS variable, and use it in multiple places in the html.
I've included an alert function immediately after the user enters the input and that works, but I can't display the variable at the bottom.
Here's the code:
<body>
<div class="hero-unit">
<h1> Title </h1>
<p> This form description </p>
<form class="well" name="formInput" action= "#">
<label>Input</label>
<input Id="txtvarInput" class="span3" style="margin: 0pt auto;" type="text" placeholder="AAA, BBB, CCC..." data-provide="typeahead" data-items="10" data-source="["AAA","BBB","CCC","DDD","EEE","FFF","GGG","HHH","III","JJJ","KKK","LLL"]"/>
</label>
<div class="form-actions" "span3">
<input name="submit" type="submit" class="btn" value="Select" onclick="alert('you chose ' + theInput.value)"/>
<script language="javascript" type="text/javascript">
var theInput = document.getElementById('txtvarInput');
</script>
</div>
</form>
</div>
<div class="page-header">
<h1>Input:
<script language="javascript" type="text/javascript">
document.write(theInput.value);
</script>
</h1>
</div>
JavaScript works a bit differently than you might be imagining.
When you say...
document.write(theInput.value);
...right in the middle of some html element somewhere, it only calls that once when the page first renders.
If you want to call it when the text input changes or a button is clicked you'll need to put it in a function and call that function when some event happens on some element.
See this link to learn about events: http://www.w3schools.com/js/js_events.asp
HOWEVER, document.write() is a bit different where, when called from a function, it will overwrite the entire page!
So... in this case you will need to "append" a text element to the <h1> element that you are trying to update.
See this link to learn more about the document object model (DOM) and working with its elements: http://www.w3schools.com/jsref/dom_obj_element.asp
Once you're familiar with these principals you'll want to make your life a lot easier and your code more cross-browser friendly by checking out a framework for doing these things like jQuery: http://jquery.com/
UPDATE (ADDED VALUE):
For those interested, something like what is being asked here can be accomplished quite easily today in "pageless", JavaScript based web applications using AngularJS (http://angularjs.org/). Do read up on the documentation and the appropriate circumstances under which this technology can be utilized. Start with the FAQs (http://docs.angularjs.org/misc/faq) and move into the videos (http://www.youtube.com/user/angularjs).
In a document.onload function I would put the following:
theInput.onchange = function(event){
document.getElementById('h1Id').innerHTML = theInput.value
}
presumably you want the HTML to update everytime the user changes the input?
The update should happen after the button is clicked.
<html>
<body>
<div class="hero-unit">
<h1> Title </h1>
<p> This form description </p>
<form class="well" name="formInput" action= "#">
<label>Input</label>
<input Id="txtvarInput" class="span3" style="margin: 0pt auto;" type="text" placeholder="AAA, BBB, CCC..." data-provide="typeahead" data-items="10" data-source="["AAA","BBB","CCC","DDD","EEE","FFF","GGG","HHH","III","JJJ","KKK","LLL"]"/>
</label>
<div class="form-actions" "span3">
// UPDATED HERE
<input name="submit" type="submit" class="btn" value="Select"
onclick="alert('you chose ' + theInput.value);
document.getElementById('inputresult').innerHTML = theInput.value;"/>
<script language="JavaScript" type="Text/JavaScript">
var theInput = document.getElementById('txtvarInput');
</script>
</div>
</form>
</div>
<div class="page-header">
<h1 id="myh1">Input:</h1>
<!-- UPDATED HERE -->
<div id="inputresult">
</div>
</h1>
</div>
Provide semantic markup, including placeholders for your values, e.g.
Input: <span class="inp-reflector"></span>
<!-- Or, for HTML5+ -->
Input: <output class="inp-reflector"></output>
Procedurally attach one or more event handlers to your input:
var inp = document.querySelector('#input-id');
inp.addEventListener('input',update,false);
inp.addEventListener('change',update,false);
Have your event handler(s) retrieve the value of the input and change your page:
function update(evt){
var changedElement = evt.target;
var newValue = changedElement.value;
var outputs = document.querySelectorAll('.inp-reflector');
outputs.forEach(function(out){
out.innerHTML = newValue;
});
}
The answer intentionally uses JavaScript features from modern browsers only.
For a generic reflection system:
<input class="reflectable" data-reflect-to=".bar">
…
document.querySelectorAll('.reflectable').forEach(function(el){
el.addEventListener('change',reflect,false);
el.addEventListener('input',reflect,false);
});
function reflect(evt){
var outSelector = evt.getAttribute('data-reflect-to');
document.querySelectorAll(outSelector).forEach(function(o){
o.innerHTML = evt.target.value;
});
}
Inline script such as the following, will execute as soon as the browser renders them. So the script below executes as soon as the browser is rendering that particular script tag and way before the user has entered any input, therefore the global variable you have created is not populated with any data inputted by the user. You need to attach an event to the submit button on the page that sets the global variable and displays it on the page.
<div class="page-header">
<h1>Input:
<script language="JavaScript" type="Text/JavaScript">
document.write(theInput.value);
</script>
</h1>
</div>
I am trying to format a selected text to bold inside a textbox but not happening. However, it is hapenning in a span/div. My code
<html>
<head>
<title>Untitled Document</title>
<script type="text/javascript">
function FormatSelectedWord(txtBox,style)
{
var selectedText = document.selection
? document.selection.createRange().text
: txtBox.value.substring(txtBox.selectionStart,txtBox.selectionEnd);
if(selectedText!='')
{
var newText='<'+style+'>'+selectedText+'</'+style+'>';
txtBox.value=txtBox.value.replace(selectedText,newText)
spOutput.innerHTML=txtBox.value;
}
}
</script>
</head>
<body>
<input type="text" name="txtBox"> </input>
<input type="button" value="Bold" onclick="FormatSelectedWord(txtBox,'b')">
<span id="spOutput"></span>
</body>
</html>
Is it possible to do it insde a textbox. If so how?
Thanks
No, it's not possible to style the text in a text box. You can make your div or span contentEditable=true if you need formatted text that is editable.
Rather than re-invent the wheel, you're better off looking at implementing TinyMCE or some other, similar thing that does this - it's quite easy. It's very commonly sought after functionality, and it's called a "Rich text editor", for if you want to go Googling :)
Trying to add this kind of functionality yourself is a huge can of worms, and you really don't want to get involved :)
Here is an example of what I think you want: http://jsfiddle.net/6gQJC/1/
and here's what you asked: http://jsfiddle.net/6gQJC/
txtBox is undefined
So this:
<input type="text" name="txtBox"> </input>
needs to be
<input type="text" id="txtBox" name="txtBox"> </input>
and then
function FormatSelectedWord(txtBox,style)
{
var textbox = document.getElementById('textBox');
I have a textbox on my html page, I'd like to run the javascript code that people put it the textbox. How can I do that?
You can create a new script dynamically like found here
Here's a quick example you can copy and paste into an html file and see it work. You'll notice that once called, the page reloads and stalls out. This could be solved by using ajax and a seperate page the executes the code and returns a value or string or whatever it is your code should return.
<html>
<head>
</head>
<body>
<script>
function doIt() {
var headID = document.getElementsByTagName("head")[0];
var newScript = document.createElement("script");
newScript.type = "text/javascript";
newScript.innerHTML = document.getElementById("textarea").value;
headID.appendChild(newScript);
}
</script>
<textarea name="textarea" id="textarea">
alert("Alert");
</textarea>
<input type="button" value="Do It" onclick="doIt();" />
</body>
<html>
You can use document.getElementsByName
<input name="textbox" type="text" />
<input name="buttonExecute" onclick="execute(document.getElementsByName('textbox')[0].value)" type="button" value="Execute" />
something similar i found here
You could also create a JavaScript function to get the content using jQuery and execute the code you wanted but you must set an id to the textbox
<script>
$("#run").click(function () {
var element = $("input#textbox").val();
//code to execute
}
</script>
<input type="textbox" value="Type something" id="textbox"></input>
<button id="run">Run Code</button>
I think the easiest native JS way to do it is to use a textbox's value attribute and eval() its content, as it doesn't require to create any script elements (that would be sitting there until the page is reloaded) or big constructs:
function runIt() {
eval(document.getElementById('code-input').value);
console.log('Ran code from textbox!');
}
<textarea id="code-input" placeholder="Input any JS code here"></textarea>
<button onclick="runIt()">Run it!</button>
This example is a text box and with every click on the button "Run it!" the text that's inside of it is executed as JavaScript.
In fact this answer is just a complicated way to say: "Just eval() a textbox's value."