DexJ
DexJ

Reputation: 1264

What is Issue with <form> tag?

here I have created reverse string and set it to "p" tag but when I click on Button it sets value inside "p" for second and then clear it

Q:I know it's because of "form" tag but why it's happening? Javascript:

function abc()
{
var str=document.getElementById("srcString").value; 
document.getElementById("ans").innerHTML=str.split("").reverse().join("");;
}

Html

<form method="GET">
<input type="text" id="srcString" placeholder="Enter something...">
<button onClick="abc()">click</button>
<p id="ans"></p>
<form>

Upvotes: 0

Views: 95

Answers (6)

ahalya
ahalya

Reputation: 192

Add button type property to avoid the page reloading and refreshing issue.

Upvotes: 0

Mathias
Mathias

Reputation: 5672

I think the easiest way of avoiding the form submitting and the page reloading is setting the button type to button instead of the standard type submit. jsFiddle

<form method="GET">
    <input type="text" id="srcString" placeholder="Enter something..." />
    <button type="button" onClick="abc()">click</button>
    <p id="ans"></p>
<form>

Upvotes: 1

Krimson
Krimson

Reputation: 7664

When you click the button, the <p> tag is set but then the form is submited, causing your page to refresh. A fix for this is to cancel the form submit.

Change your code to this:


JavaScript

function abc() {
    var str = document.getElementById("srcString").value;
    document.getElementById("ans").innerHTML = str.split("").reverse().join("");
    return false; //return false to cancel form submit
}

HTML

<form method="GET">
    <input type="text" id="srcString" placeholder="Enter something...">
    <button onClick="return abc()">click</button>
    <p id="ans"></p>
<form>

Upvotes: 0

webzar
webzar

Reputation: 114

use onsubmit="return false;"

<form method="GET" onsubmit="return false;">
<input type="text" id="srcString" placeholder="Enter something...">
<button onClick="abc()">click</button>
<p id="ans"></p>
<form>

Upvotes: 0

hazimdikenli
hazimdikenli

Reputation: 6019

Most probably you are reloading the page. try returning false from your abc function to cancel submitting of the form.

Upvotes: 0

gr33kbo1
gr33kbo1

Reputation: 309

My guess is that since the method is GET it is just refreshing the page, try POST instead

Upvotes: 0

Related Questions