Marcus
Marcus

Reputation: 6717

HTML get the value of an image field and use that value as a src for an image field

I have a HTML input field like this

<input type="text" id="Bild"/>  

I want to get the value of the input field and store it in a String in my JSP page, something like this

<%
String theString= <input type="text" id="Bild"/>
%>

After that I want to use the string to as a source for my image field, like this

<img src= <%= theString %> >

I have no clue how to do this, and I've been staring at the screen for two hours not getting my head straight. How can I get the value of the input field to use for my image source?

I'm new to JavaScript so if I have to use this, please be very descriptive. Thanks.

Upvotes: 0

Views: 1447

Answers (3)

Dissident Rage
Dissident Rage

Reputation: 2716

Changes a pre-existing image's src when the byt button is clicked.

function bytUtBilden() {
    // select <input id="Bild"/>
    var bildenFalt = document.getElementById('Bild');

    // select <img id="bilden"/>
    var bilden = document.getElementById('bilden');

    bilden.src = bildenFalt.value;
}

function begynna() {
    // select element with id="byt"; when clicked, run bytUtBilden
    document.getElementById('byt').addEventListener('click',bytUtBilden,false);
}

// when DOM is loaded, run begynna()
document.addEventListener('DOMContentLoaded',begynna,false);

Edit: Changed it so that it updates when the button is clicked. Also bytUtBilden() can be run from anywhere and it will do the same thing.

Upvotes: 2

theferrit32
theferrit32

Reputation: 241

Is there a reason to be going through a middle-man? Just grab the value with a direct DOM query as long as you know that the text field does already contain a value:

document.getElementById('Bild').value

In this example I used a button as the action, but you don't need that for the value to be query-able

http://jsfiddle.net/Py2E2/

Upvotes: 0

Pranay Soni
Pranay Soni

Reputation: 1066

var path = $('Bild').val();
$('#imgid').attr('src',path);

Upvotes: 0

Related Questions