0

In my main python file, I have the following code.

@app.route('/accounts/test/learn/medium')
def medium():
word = random.choice(os.listdir("characters/"))
return render_template('accounts/test/medium.html', word=word)

My HTML Template "Medium" has a div called "character" which contains the word.

<div id="character" style="font-weight:bold;color:red"  >{{ word }}</div>

My Javascript file, which I call body onLoad tries to set the png file for the word/character.

currentWord = document.getElementById("character").value
if(document.getElementById("characterPNG")!=null){
    document.getElementById("characterPNG").src = "../../../style/images/characters/png/" +currentWord+ ".png";

When I run the application, Python sets the word in my HTML I can see that, but JavaScript, can't see the value of character. It rather say's

Failed to load resource: the server responded with a status of http://path/undefined.png

Do you have any suggestions what might be wrong? Is it the sequence?

2
  • 1
    The JavaScript is running in the browser on the client side; you can't use a relative path for the image. You should use flask to supply the image URL with url_for. Commented Jan 8, 2017 at 15:30
  • I think the main issue is that the DIV-element does not have a value. He wants to read the HTML content (the innerHTML attribute) Commented Jan 8, 2017 at 16:02

2 Answers 2

1

According to this answer Get content of a DIV using JavaScript you should use innerHTML instead of value:

currentWord = document.getElementById("character").innerHTML
Sign up to request clarification or add additional context in comments.

Comments

0

As pointed out in the comments, I would make good use of url_for from Flask to generate urls for static files, as follows:

Quoting from Flask's doc:

Static Files

Dynamic web applications also need static files. That’s usually where the CSS and JavaScript files are coming from. Ideally your web server is configured to serve them for you, but during development Flask can do that as well. Just create a folder called static in your package or next to your module and it will be available at /static on the application.

So, after you create a static folder, just reference it in your template with url_for method pointing out as well the filename:

<img id="characterPNG" src={{url_for('static', filename=word+'.png')}}></img>

1 Comment

I totally aggree with you, but the question was about the undefined value

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.