1

i've just started learning JavaScript and came across a little problem.

var id;
function replay(id){
    document.getElementById(id).innerHTML='<form action="./replay.php?uid= method="get"><hr><input type="submit" name="qpost" class="replay_key" value="Post" style="background-color: #a9d22c;"></form>';  
}

i'm trying to add the variable "id" after but can't figure out the syntax

<form action="./replay.php?uid=

3 Answers 3

2

Like this:

document.getElementById(id).innerHTML='<form action="./replay.php?uid=' + id + '" method="get"><hr><input type="submit" name="qpost" class="replay_key" value="Post" style="background-color: #a9d22c;"></form>';

Essentially you want:

something = 'string literal' + variableName + 'another string literal';
Sign up to request clarification or add additional context in comments.

Comments

0

A string is a sequence of characters basically. One very useful thing you can do with strings is concatenate (join) them using the + operator:

var longString = 'This is ' + 'a long' + ' string'; // "This is a long string"

The easiest way to insert something in the middle of a string is to concatenate the begining of the string, your something and the end of the string:

var mySomething = 'a long';

var longString = 'This is ' + mySomething + ' string'; // "This is a long string"

You can do the same for your id:

var id;
function replay(id){
    document.getElementById(id).innerHTML='<form action="./replay.php?uid=' + id + '" method="get"><hr><input type="submit" name="qpost" class="replay_key" value="Post" style="background-color: #a9d22c;"></form>';  
}

Resulting HTML prettyfied(for id = 123):

<form action="./replay.php?uid=123" method="get">
  <hr>
  <input type="submit" name="qpost" class="replay_key" value="Post" style="background-color: #a9d22c;">
</form>

Notice how i also added the closing quotes after the id!

Comments

0
//var id;
// using id for example 12
var id = 12;
function replay(id){
    document.getElementById(id).innerHTML='<form action="./replay.php?uid=' + id + ' method="get"><hr><input type="submit" name="qpost" class="replay_key" value="Post" style="background-color: #a9d22c;"></form>';  
}

3 Comments

Won't that give ReferenceError: $ is not defined? Or an error about the missing closing )?
In other words, "Unless a tag for a framework/library is also included, a pure JavaScript answer is expected."
$(document).ready(function() { replay(id); } is just for fireing the function in Jquery Forgot Javascript was asked and not Jquery just delete the last 3 lines

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.