Form value to be empty if no change by user - javascript

I have a form with two inputs:
<input type="text" name="keyword" value="Search" onfocus="wipe(this)"/>
<input type="text" name="city" value="City" onfocus="wipe(this)"/>
and my JavaScript which gets rid of the pre-set value in form field as soon as you click it with your mouse is:
function wipe(obj)
{
obj.value="";
}
My question is, say the user doesn't type anything in the city field, how do I make it so that when the form is submitted the value for that field is empty and not the word City?

placeholder is a good attribute which can solve your problem its a past time history when we are used to using value for showing for which this textbox we have
<input type="text" name="keyword" placeholder="Search" />
if you still want to use java script modify your code something like this
<input type="text" name="keyword" value="Search" onfocus="wipe(this,'Search')" onblur="wipe2(this,'Search')"/>
<input type="text" name="city" value="City" onfocus="wipe(this,'City')" onblur="wipe2(this,'City')"/>
script function for second approch
function wipe(obj, str)
{
if(obj.value!=str){
obj.value="";}
}
function wipe2(obj, str)
{if(obj.value==""){
obj.value=str;}
}

You are using the wrong technique here. you should be using placeholder which is supported by most major browsers with the regular exception of IE. So if this is not a concern for you, you should definitely be using that. Especially, if you have a label element for that field. Otherwise you'd need to be checking for that input value on submission and see if it equals the string city

Just Declare a variable hasChanged and set it true when wipe function is called.Then call a function say 'SubmitFunction()'on the onclick function of Submit button.
<input type="text" name="keyword" value="Search" id="Search" onfocus="wipe(this)"/>
<input type="text" name="city" value="City" id="City" onfocus="wipe(this)"/>
<input type="submit" name="submit" value="submit" onclick="SubmitFunction();"/>
var hasChanged=false;
function wipe(obj)
{
hasChanged=true;
obj.value="";
}
function SubmitFunction()
{
if(hasChanged==false)
{
$("#City").val('');
}
}

at the time of submit why not check for value='city'
if(obj.value!='city')
{
//your code here
}
or if you have no problem in using jquery use watermark plugin this will handle browser compatibility problem also
Jquery Watermark

try this:
if($('input[name="city"]').val() && $('input[name="city"]').val() != 'city') { yourform.submit(); }

See How to prepopulate input text fields with prompting text which disappears on typing (jQuery) for some solutions to this. If you're okay with using HTML5, the best solution is probably to use "placeholder" instead of "value".

You should add one more attribute(eg. default <input type="text" name="keyword" default="Search" value="Search" onfocus="wipe(this)"/>) with value same as value attribute.
in on submit compare each form fields
function onSubmit(){
for (var fields in form)
if(form[fields].value== form[fields].getAttribute("default")){
form[fields].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

HTML5 Required input, removing and adding on the fly not working

I am trying to remove a required attribute from an input on the fly. The general idea is I have a field that is set to required, this field has custom validation with the pattern attribute. When the user clicks a button I am attempting to remove the required field.
I have put together a fiddle here:
https://jsfiddle.net/paulmatos/t1p1wub3/
HTML:
<form>
<input type="text" oninvalid='this.setCustomValidity("Enter a number in the Specified Range");' oninput="try{setCustomValidity('')}catch(e){}" pattern="[0-9]" required="required" name="password" id="password" />
<input type="text" required="required" name="temp" />
<input type="submit" class="btn btn-primary form-control" value="Submit" />
<div class="btn btn-default removeReq">Remove Required</div>
</form>
Jquery:
$('.removeReq').click(function() {
$('#password').removeAttr('required');
});
The issue I am experiencing has to do with the order of submission.
If you click remove required, and then submit the form you will see that it works as intended.
However, if you do those steps in reverse order, click submit first, then remove and try and submit again, you will notice I am still getting the validation error on the first input.
Is there anyway to get around this with this intended functionality, I am trying to get this to work just with the html5 validation.
I did have a look at the fiddle and the only way I could get the behaviour you wanted was by literally detaching, cloning and reinserting the field. Works tho.
$('.removeReq').click(function() {
var password = $('#password').removeAttr('required oninvalid oninput pattern').detach().clone();
$('form').prepend(password);
});
https://jsfiddle.net/t1p1wub3/2/
Think you are getting this due to the code in the oninvalid handler. Try this.
$('.removeReq').click(function() {
$('#password').removeAttr('required oninvalid');
});
You can try this instead of removeAtt():
$('.removeReq').click(function() {
$('#password').prop('required', false);
});

How to Submit a Javascript Value in an Input Field

Simply, how can I do this?
<input type="hidden" value="some javascript value" />
I have a form whereby when a user clicks on Add More, more input fields are added via javascript.
I'm also using javascript-declared values to track and limit the number of fields a user can add.
I need a way for my php code to retrieve these javascript values.
Use append
$('#hidden').val('my Text');
input field should be
<input type="hidden" id="hidden"/>
the question is a bit vague, but i will give it a go
try adding a name as an array and then you can use get or post
<input name="myjavascriptinputs[]" type="hidden" value="some javascript value" />
in your php you will be able to use
foreach($_GET['myjavascriptinputs'] as $ajavascriptinput)
From the button you must be calling a javascript to add these fields dynamically. Simply append the code to that function to hand over these values to the field.
<input id="myinputfield[]" type="hidden" value="" />
<script>
function addOneMore(){
var newField = // code to add one more field
newField.value = newValue;
}
</script>
Will solve your purpose.

Check if the name field in a form contains a number using javascript and the onchange event

im the definition of a rookie and i hav no idea what im doing. i have to create a function using javascript to perform a validation on the 'name' field in a form. The check will see if there is anything entered or if the name contains a number. On top of this i have to use a onchange event. I tried searching and i got answers put i saw the answers had jquery code in it and i cant use it in this question. Im clueless on what to do, can someone please help? Here is the form im working with
<form method="get">
<label for="name">Name</label>
<input type="text" id="name" placeholder="Name" onChange="" >
<br>
<label for="age">Age</label>
<input type="age" id="age" placeholder="Age">
<br>
<label for="location">Location</label>
<input type="location" id="location" placeholder="Location">
<br>
<button type="submit">Submit</button>
</form>
Here is a javascript function that takes an input parameter. It will check if the input value has any digit characters in it using regular expression. If it does it sends an alert and then removes all the digit characters (again using regular expression). It will then check if the input value is an empty string and send an alert if it is.
function checkName(input) {
// Check if input contains a digit
if (/\d/.test(input.value)) {
alert('Name contains a number');
// Remove all digit characters
input.value = input.value.replace(/\d/gi, '');
}
// Check if input is empty
if (input.value === '') {
alert('Name is empty');
}
return true;
}​
Add your function call to the onChange property of the input, passing in this object for the function's variable reference:
<input type="text" id="name" placeholder="Name" onChange="checkName(this)" >
Here is a demo showing this working:
http://jsfiddle.net/PMKsS/1/
Something to note. This function will only call when the name input value is changed, as that is what the onChange call will do. Therefore the name input will not be checked for being empty when the form submits.
Also, this is worth a read: Why is using onClick() in HTML a bad practice?. It explains about adding javascript event listeners through javascript rather than through an attribute and why doing the other way isn't great. Although it doesn't offer a way to do this in pure javascript.

JavaScript did not receive value in this.form

I am using a three part code below:
First part of the code: Basically a javascript function changeSearchEngine will be triggered when user select Google.
<p id="searchbox">This paragraph will change once javascript is triggered</p>
<form align=right>
<select name="searchengine" onchange="changeSearchEngine(this.form)">
<option value="google">Google</option>
</select>
</form>
This is my changeSearchEngine function in javascript.
function changeSearchEngine(form)
{
var searchEngine=form.searchengine.value;
if (searchEngine=="google")
{
var url_google='<form method="get" action="http://www.google.com/search" onsubmit="submitGoogle(this.form)" target="_blank"><input type="text" name="q" size="31" maxlength="255" value="" /><input type="submit" value="Google Search"/></form>';
document.getElementById("searchbox").innerHTML=url_google;
}
}
At this point of time, all is working well. When I select Google, the searchbox for google appears. I can search and everything.
Notice there is a onsubmit="submitGoogle(this.form)" right? I need to save what the user search terms into SQL table. So I have this javascript function below to capture what user have type:
function submitGoogle(form)
{
alert("Inside submitGoogle function");
var searchterm=form.q.value;
alert(searchterm); //to test. this part didnt capture the value.
}
I managed to invoke the submitGoogle function BUT however I can't retrieve the value of q despite using searchterm=form.q.value. What did I do wrong here?
In your onsubmit handler, you are passing this.form. But, this already refers to the form since it is the form itself that triggers the submit event. Form fields have a form property, but the form itself does not have a form property. So, just change your handler to pass this instead of this.form.
http://jsfiddle.net/fmqNj/
onsubmit="submitGoogle(this)"
Okay I found one possible solution. Let me answer my own question.
In changeSearchEngine(form) function, i change to this:
var url_google='<form method="get" name="googleform" action="http://www.google.com/search" onsubmit="submitGoogle(this.form)" target="_blank"><input type="text" name="q" size="31" maxlength="255" value="hello" /><input type="submit" value="Google Search"/></form>';
In submitGoogle(form) function, i change to this:
var searchterm=document.googleform.q.value;
But I still like others to comment on my solution whether it is not elegant or not within the practice. :D

Categories

Resources