clear input textbox value on load - javascript

I have the following form which is getting pre populated with values on load. I want to have empty input boxes on load using Javascript. However I do not have access to the <body> tag so <body onload="" will not work here. Is there any other way to clear the form fields on load?
<form method="POST" action="">
<input name="username" id="user" value="" /><br />
<input name="pwd" id="pass" value="" />
<input type="submit" value="Go" />
</form>

You can use window.onload instead.
function init() {
// Clear forms here
document.getElementById("user").value = "";
}
window.onload = init;
You could also use one of the nice wrappers for doing this in JQuery, Dojo, or you favorite Javascript library. In JQuery it would be,
$(document).ready(init)

Try something like:
window.onload = function(){
document.getElementById("user").value = "";
}
Here's an example

You can run a timeout that will clear the field values. like this:
var t=setTimeout(function(){CLEARVALUES},3000)

Maybe you can add a script tag just after the form.
<script type="text/javascript">document.getElementById("user").value = "";</script>
You can also use jQuery to subscribe to both an individual element's ready (or load) event or the document.

onload=()=>{
document.getElementById('user').value='';
}
or
onload=()=>{
document.getElementById('user').setAttribute('value','');
}

Related

Pass a javascript variable to another page when form is submitted. with just html and Javascript

Good day, I am trying to pass a java script variable along with 2 user inputs. I am unable to get the code to work the email and name go to HighScore.php just fine, but I keep getting zero for the hidden field. highscore1 is the name of the variable. I don't know J Query, so I need a HTML java-script solution. Thank you for looking.
<form method="post" name="form" action="HighScore.php">
<input type="text" placeholder="Enter Name" name="username">
<input type="text" placeholder="Enter Email" name="email">
<input type="hidden" name="highscore1" id="hidden_score" value= highscore1>
<input type="submit" name="add" value=Enter>
</form>
I think in your case, you should first use javascript to get/set hidden_score input, you can use it anywhere in your html page, as long as you ensure that input is fully rendered, you can simply add it inside of $(function() { /*you can put your code here*/ }) for jQuery version, and document.addEventListener('DOMContentLoaded', function(event) { /*you can put your code here*/ })for javascript version
<script>
document.getElementById("hidden_score").value = "Set value here";
</script>
And then, in your HighScore.php, you can use this for getting that value depend on form method: $_POST['hidden_score'] for post and $_GET['hidden_score'] for get
function setHighScore()
{
document.getElementById("hidden_score").value = "Set value here";
}
now you can call the above function on any event that meets your requirement

Jquery get input value from another text input value and set into hidden input value

I am new at Jquery. My User Story: I have two input form tag. One is hidden and One is Text. I need to take value from input text and set that value into hidden input and then submit the form with both value. Is it possible to do in Jquery. Here is my example code:
if ($_POST) {
$email = $_REQUEST['email'];
$username = $_REQUEST['username'];
echo "Email Value: " . $email ." And Username Value :" .$username;
}
var lap = $("emailId").val();
var test = $("userId");
test.val(test);
<form>
<input id="emailId" name="email" type="text" value="">
<input id="userId" name="username" type="hidden" value="">
<input type="submit" value="Submit" />
</form>
You don't need jQuery for this. I've provide a solution using jQuery as well as vanilla JavaScript.
jQuery Version
$(document).ready(function(){
$email = $('#email')
// Note that we are updating the hidden input value each time the
// text input value changes. We could do this less frequently by
// using the `input` or `change` event instead of the `keyup` event.
$email.on('keyup', function(e){
$('#userId').val($email.val())
});
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
<input type="text" name="email" id="email" />
<input type="hidden" name="userId" id="userId" />
<button type="submit" id="submit">Submit</button>
</form>
Vanilla JavaScript Version
document.addEventListener('DOMContentLoaded', function(e) {
var txtEmail = document.querySelector('#email')
var txtUserId = document.querySelector('#userId')
// Note that we are updating the hidden input value each time the
// text input value changes. We could do this less frequently by
// using the `input` or `change` event instead of the `keyup` event.
txtEmail.addEventListener('keyup', function(e) {
txtUserId.value = txtEmail.value
})
})
<form>
<input type="text" name="email" id="email" />
<input type="hidden" name="userId" id="userId" />
<button type="submit" id="submit">Submit</button>
</form>
A brief explanation of my method
Waiting for the HTML to load
Whether you're using jQuery or not, depending on how your JavaScript and HTML code is stitched together, sometimes you're HTML elements are not available when your JavaScript code runs (for example, if your JavaScript code is included in the <head> tag, which I think has become pretty uncommon these days). For this reason, I've gotten into the habit of making sure the document is ready before I reference any HTML elements. Using jQuery, this is done with the following code:
$(document).ready(function(){
// The code here (inside this function) will be executed after the HTML finishes loading.
})
With vanilla JavaScript, the code looks like this:
document.addEventListener('DOMContentLoaded', function(){
// The code here (inside this function) will be executed after the HTML finishes loading.
})
Making Updates As Soon As Possible
In addition, my code updates the hidden input value after the text input value has changed, rather than waiting for the form to be submitted. Either option may be perfectly acceptable for a given situation. I am in the habit of updating things like these as soon as possible; if in the future, I write some JavaScript code that is expecting the value of these to input controls to be equivalent, and that code runs before the form is submitted, I'll probably have a bug in my code. Hence, I find it safer to just update as soon as the change occurs.
As per jquery documentation You forgot to use # in your both selectors. You should use:
var lap = $("#emailId").val();
var test = $("#userId");
test.val(lap);

How to autosubmit a form in javascript?

I have a form with an input text field which imports data every couple of seconds and display it in the form field , let us say :
<input name="code" id="code" type="text" size="64" maxlength="128" />
and a submit button and my form has the formname form1.
I want the submit button to be clicked as soon as the data in the form field is changed.
I did try to do the following. In the header I did add the follwoing javascript:
<SCRIPT LANGUAGE="javascript">
function send_data()
{
document.form1.submit();
}
</SCRIPT>
and on the form :
<input name="code" id="code" type="text" size="64" maxlength="128" onchange="send_data();" />
but it didn`t work..
Any help ?
Thanks
Something like this would work:
<form action="#">
<input type="" id="input" />
<button type="submit"></button:>
</form>
<script>
function send_data() {
document.forms[0].submit();
}
window.onload = function(){
var input = document.getElementById('input');
input.onchange = send_data;
}
</script>
But I'd add a few caveats:
I'm assuming there is only one form on the page. You would be safer assigning and ID to your form and using getElementById and referencing that instead of document.forms[x]
The change event will only happen after you lose focus on the input, which I probably what you want? Just making sure it's expected behavior
Without knowing why you need to do this, I'd note that it could potentially be very annoying to the user, as submission will trigger a new page load. You may be better off doing a submission via ajax so as not to disrupt the user's browsing. If you do this, I strongly recommend a JS library to handle this.

adding inputs to html form, using javascript

I have an html form that I would like to add inputs fields to using javascript. Originally I had the input fields by themselves underneath the 'body', and the following was able to add the fields:
// Create number input field
var phoneInput = document.createElement("INPUT");
phoneInput.id = "phone" + instance;
phoneInput.name = "phone" + instance;
phoneInput.type = "text";
// Insert that stuff
document.body.insertBefore(document.createElement("BR"), element);
document.body.insertBefore(phoneLabel, element);
document.body.insertBefore(phoneInput, element);
I then added a 'form' element around the original inputs in the html file.
<body>
<form action=searchform.php method=GET>
<LABEL for="phone1">Cell #: </LABEL>
<input id="phone1" type="text" name="phone1">
<input type="button" id="btnAdd" value="New text box" onclick="newTextBox(this);" />
</form>
</body>
Now the button doesn't add new text boxes. Have I structured this incorrectly?
Thanks!
This is because you are appending the elements to the body, which means that insertBefore cannot find element (because it's in the <form>, not the <body>), so it never gets inserted.
A quick way to fix this would be to use document.body.firstChild.insertBefore. However, if the form is no longer the first element in the body, this will no longer work.
A cleaner, better way would be to give your form an ID (e.g. <form id="myform">), and then access the form using: document.getElementById("myform").insertBefore. Then you can place your form anywhere, and it will still be accessible using the ID.
Easiest would be to use jQuery. Add an ID to your form, for easier reference:
<form id="myform" action="action" method="GET">
<input type="hidden" name="a" value="1"/>
<input type="hidden" name="b" value="2"/>
</form>
<script type="text/javascript">
$("#myform").append('<input type="hidden" name="c" value="3"/>');
</script>
You can later change the value of your new input, by easily referring to it:
$("#myform input[name='c']").val(7);
Gve the form an id
<form id="myForm" action="searchform.php" method="GET">
Create the JavaScript elements just as you used to, then you can just add the elements like so:
var f = document.getElementById('myForm');
f.appendChild(document.createElement('br'));
f.appendChild(phoneLabel);
f.appendChild(phoneInput);
(insertbefore would work on f as well, although I think this is more readable.)

How to get element using javaScript

I want to get value of input element using javaScript.
I am new to all this Please help me.
You can use
var stringVal = document.getElementById('youInputID').value;
Other users have answered the question above already. I would also like to recommend looking at one of the javascript libraries. They make this kind of work much easier. My current favorite is jquery. It is amazingly powerful - every day I find some new feature or trick that makes javascript programming easier.
To solve this in jquery you can use:
The line below will create an alert box for the value of an input tag with the id of email using jquery:
alert($("#email").val());
Here is a complete example:
<html>
<head>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
$(document).ready(function(){
alert($("#email").val());
});
</script>
</head>
<body>
<form method="POST" action="go.php" id="login_form">
<input type="text" class="inputtext" title="Email" id="email" name="email" value="your#emailaddress" />
</form>
</body>
</html>
Your Javascript should look similar to this:
var elm = document.getElementById('myElement');
var value = elm.value;
And your HTML:
<input type="text" id="myElement" value="My Value" />
Try this:
<input type="text" id="testid" value="" />
Now you can get the value of above text box like this:
document.getElementById('testid').value;
Other way:
document.form_name_here.element_name.value;
Simply run an alert to check if value comes:
alert(document.getElementById('testid').value);
var txt = document.getElementById('ID-OF-FIELD');
var value = txt.value;

Categories

Resources