Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript change html <p> tag value

I have an HTML form that allows a user to type in the name of a faction and submit it with a button:

<form method="get">
    </br><button type="submit" onclick="createFaction()">create faction</button>
    <input placeholder="name" id="factionName" name="factionName"></input>
</form>

The reason it is GET at the moment is purely for testing.

I then have a JavaScript function that changes the name of this:

<p id="test1"></p>

to whatever the users input was. The JavaScript code is

function createFaction() {
    var name = document.getElementById('factionName'),
    factionName = input.value;

    document.getElementById('test1').innerHTML = name;
}

However, it doesn't work. Why?

like image 246
james clarke Avatar asked Aug 13 '17 14:08

james clarke


People also ask

How do I change text in P tag?

To change the text font in HTML, use the style attribute. The style attribute specifies an inline style for an element. The attribute is used with the HTML <p> tag, with the CSS property font-family, font-size, font-style, etc. HTML5 do not support the <font> tag, so the CSS style is used to change font.

Is there p1 p2 in HTML?

<p1> <p2> etc. tags don't really exist. There is only <p> tags. When you add numbers, you are creating your own custom tags and styling those need to be done differently if you want them to behave like a standard <p> tag.

Can we use JavaScript to modify HTML DOM?

With the HTML DOM, JavaScript can access and change all the elements of an HTML document.


1 Answers

First change type='button'. Instead use submit, type="submit". It will submit the page and you will not see changes done. The change is here:

<button type="button" onclick="createFaction()">create faction</button>

Then change name.value in JavaScript to get the value from the name object:

factionName = name.value;

function createFaction() {
    var name = document.getElementById('factionName'),
    factionName = name.value;

    document.getElementById('test1').innerHTML = factionName;
}
<form method="get">
    </br><button type="button" onclick="createFaction()">create faction</button>
    <input placeholder="name" id="factionName" name="factionName">
    </form>
<p id="test1"></p>

Another way to do this is,

function createFaction(faction) {
    document.getElementById('test1').innerHTML = faction;
}
<input onchange="createFaction(this.value)" onkeyup="createFaction(this.value)" placeholder="type something ..." id="factionName" name="factionName">
<p id="test1"></p>
like image 148
Niklesh Raut Avatar answered Sep 18 '22 02:09

Niklesh Raut