Preventing reload from document.write

hari1

In the zone
Please see this html code:-

Code:
<html><head><title>title</title>

<script type="text/javascript">
function change_case()
{
document.form1.type.value=document.form1.type.value.toLowerCase();
}
</script>

</head>
<body onLoad="form1.type.focus();">

<form name=form1 method=post action=''>
<input type=text name=type>
<input type=submit value=Submit onclick="change_case();"> </form>
</body>
</html>

Whenever I enter text in the text box and press submit, the text case changes but immediately the page also reloads. How do I prevent this reload? Also is there anyway I can do the same thing without any submit button at all? Like as I type the text or paste from somewhere, simultaneously the text case also changes.
Thanks
 

krishnandu.sarkar

Simply a DIGITian
Staff member
Code:
<html><head><title>title</title>

<script type="text/javascript">
function change_case()
{
document.getElementById('txtName').value=document.getElementById('txtName').value.toLowerCase();
}
</script>

</head>
<body onLoad="form1.type.focus();">

<form name="form1" method="post" action="">
<input type="text" name="txtName" id="txtName" onblur="change_case();">
<input type="submit" value="Submit"> </form>
</body>
</html>

The Logic is the Submit button you created is not a simple button, in that case you would have used <input type="button">, but it's Submit, which is used to submit the whole form when pressed.

You can use something like LostFocus event on textbox. Means when the textbox gets focus the event "onfocus" gets fired and on lost focus "onblur" event gets fired.

In this way, when someone will type something and will move out from the textbox that event will get fired and will do it's Capitalization task.

Hope that helps.

NOTE : I have modified your code a little bit, because the way you were using is wrong. I have followed the best practises. Also you never used "" while declaring input type name, value, type etc. Which should be used.
 
OP
hari1

hari1

In the zone
@krishnandu.sarkar
I have figured out the way. Adding return false; to the script solves the problem. Thanks for suggestion.
 

krishnandu.sarkar

Simply a DIGITian
Staff member
You are right. But that would also prevent to submit the form.

In that case why are using Submit button? Instead you can use just a Button.

You said you want without any button click, that's why I suggested the above code.

Hope you understand what problem you'll get into if you add return false to the function.
 
Top Bottom