I'm using this to rescue the text in the form in case the user goes to another page without submitting. But how can I clear the form when the user presses the submit button?
function rescuefieldvalues(idarray){
for (var i=0; i<idarray.length; i++){
var el=document.getElementById(idarray[i])
if (!/(text)/.test(el.type)) //skip to next element if it isn't a input type="text" or textarea element
continue
if (el.addBehavior && !window.sessionStorage){ //use IE behaviors to store info?
el.style.behavior='url(#default#userData)'
el.load("userentereddata")
}
var persisteddata=(window.sessionStorage)? sessionStorage[idarray[i]+'data'] : (el.addBehavior)? el.getAttribute('dataattr') : null
if (persisteddata) //if rescued data found for this element
el.value=persisteddata
el.onkeyup=function(){
if (window.sessionStorage)
sessionStorage[this.id+'data']=this.value
else if (this.addBehavior){
this.setAttribute("dataattr", this.value)
this.save("userentereddata")
}
} //onkeyup
} //for loop
}
<form>
<p>Name: <input type="text"/></p>
<p>Address*: <input type="text" id="address" style="width:200px;" /></p>
<p>Feedback*:<br />
<textarea id="feedback" style="width:300px;height:150px">Your feedback here</textarea><br
/>
<input type="submit" /></p>
</form>
<script type="text/javascript">
rescuefieldvalues(['address', 'feedback']) //rescue data
</script>
You are setting your key/value pairs with:
sessionStorage[this.id+'data']=this.value
(just a note here, I would prefer the syntax: sessionStorage.setItem(key, value)).
Similarly, you should iterate over the keys that you've stored and clear them with:
sessionStorage.removeItem(key)
If you don't have the keys that you want to clear, you might iterate over sessionStorage properties as if it was a regular object.
You can also clear all your sessionStorage with sessionStorage.clear().
Of course you have to create a function that does this and bind it to the submit event of your form.
Related
Is there a way to get the object itself when a function receives a value from it?
Example:
<input id="field1" onblur="testFunction(this.value)" />
<input id="field2" onblur="testFunction(this.value)" />
<script>
function testFunction(x){
field_value_length = x.length;
field_object = ????;
}
</script>
When I blur the field, I apply it's length to "field_value_length" in testFunction(). Ok!
Is there a way to get the object itself (the input) where data in "x" came from, so I can get other properties from the form field that has sent data value to the function, like the "id" etc. just like it was sending testFunction(this) instead testFunction(this.value)?
What is sent to the function is the value from the input... Only.
But nothing prevents you from sending the input element, using just this.
<input id="field1" onblur="testFunction(this)" />
<input id="field2" onblur="testFunction(this)" />
<script>
function testFunction(x){
field_value_length = x.value.length;
field_id = x.id;
}
</script>
In HTML exists
required
attribute, which force user to enter some date before submit. But user can type only spaces. Is there attribute which check is typed content is whitespace before postback. In need attibute which works similar to string.IsNullOrWhitespace in c#.
It took me a while to get the Regex right, but the following creates a rule to only select if there's no whitespace:
<input type="text" pattern=".\S*" />
As #Paul S. noted, this isn't checking the first character, so the following will do that:
<input type="text" pattern="^.\S*" />
Also, this does indeed only work in HTML5 browsers, but since the question contained required, I'm assuming there if is some fallback kept in mind.
Using the pattern attribute, you can make it accept only spaces
<form action="?" method="post"> <!-- required for snippet -->
<input type="text" required pattern="\s*"/>
</form>
However, please note that required prevents the submission of empty input (i.e. your "null"), so to permit that remove required so that pattern is doing the requirement checking
<form action="?" method="post"> <!-- required for snippet -->
<input type="text" pattern="\s*"/>
</form>
Lastly, still perform validation on the server as you can never assume a client is a safe source, or conversely, always assume the client is trying to hack you
If you can't assume HTML 5 support, you can shim the behaviour using JavaScript, which would look something like this for required
if(!('required' in document.createElement('input'))) {
window.addEventListener('submit', function (e) {
var form = e.target,
inputs = form.getElementsByTagName('input'),
i;
for (i = 0; i < inputs.length; ++i)
if (inputs[i].getAttribute('required'))
if (!inputs[i].value)
e.preventDefault(); // + warn?
});
}
and for pattern
if(!('pattern' in document.createElement('input'))) {
window.addEventListener('submit', function (e) {
var form = e.target,
inputs = form.getElementsByTagName('input'),
i,
re;
for (i = 0; i < inputs.length; ++i)
if (re = inputs[i].getAttribute('pattern')) {
re = new RegExp('^' + re + '$');
if (!re.test(inputs[i].value))
e.preventDefault(); // + warn?
}
});
}
You could also set useCapture to true for the listener to skip ahead in the queue of handlers, letting you prevent the event reaching other handlers in the case of submission prevented
<
<form onsubmit="alert('Submitted.');return false;"> <input type="text" required="" pattern="(?:19|20)[0-9]{2}-(?:(?:0[1-9]|1[0-2])-(?:0[1-9]|1[0-9]|2[0-9])|(?:(?!02)(?:0[1-9]|1[0-2])-(?:30))|(?:(?:0[13578]|1[02])-31))" value="" name="dates_pattern2" id="dates_pattern2" list="dates_pattern2_datalist" placeholder="Try it out." autocomplete="off"> <input type="submit" value="»"> <datalist id="dates_pattern2_datalist"> </datalist> </form>
I want to remove an obj from my form and be able to add it back as it was onload. But when I try to add it back using the var I tried to save onload I get an error (it queries the current form which has its child removed).
How can I store all the children obj properties in their current form onload, immutably, so that I can be able to add them back after they have been removed from the document?
This would give me an error ("Argument 1 of Node.appendChild is not an object"):
var fullList2 = null;
window.onload = function () {
fullList2 = document.getElementsByName('person')[0].children;
document.getElementsByName('person')[0].removeChild(document.getElementsByName('person')[0].children[1]);
document.getElementsByName('person')[0].appendChild(fullList2[1]);
}
the form:
<form name="trans" id="trans" method=POST action=entertransaction.jsp>
<input type="text" onkeyup="update();" id="input1" value="" name="filterTxt" size="21" tabindex="1" style="width: 195px" />
<br />
<select id="person" name="person" size=10 tabindex="2" style="width: 200px">
<option value="0">Scott Ambler</option>
<option value="1">Andrew Binstock</option>
</select>
<br />
<input type=submit name=action value="Next ->" tabindex="3" />
</form>
Your fullList2 is just a reference to the child array of the person select element, when you remove childs from the person select you also remove them from the fullList2 array, that is why your approach does not work.
As for the solution: you will have to store the child elements by themselves. So your code would look something like (not tested just written from the top of my head):
var fullList2 = [];
window.onload = function () {
var person= document.getElementsByName('person')[0];
//Remove objects from the dom and store them in fullList2
fullList2.push(person.removeChild(person.childNodes[0]);
fullList2.push(person.removeChild(person.childNodes[1]);
//Add them back in
person.appendChild(fullList2[0]);
person.appendChild(fullList2[1]);
}
You are running into the problem that when you assign an object to a variable, you are not making a copy of the object. So, when you delete the object, the variable that was pointing at it no longer has something to point at. You need to make a clone of the object. So, see What is the most efficient way to deep clone an object in JavaScript?
I want to check a form if the input values are empty, but I'm not sure of the best way to do it, so I tried this:
Javascript:
function checkform()
{
if (document.getElementById("promotioncode").value == "")
{
// something is wrong
alert('There is a problem with the first field');
return false;
}
return true;
}
html:
<form id="orderForm" onSubmit="return checkform()">
<input name="promotioncode" id="promotioncode" type="text" />
<input name="price" id="price" type="text" value="€ 15,00" readonly="readonly"/>
<input class="submit" type="submit" value="Submit"/>
</form>
Does anybody have an idea or a better solution?
Adding the required attribute is a great way for modern browsers. However, you most likely need to support older browsers as well. This JavaScript will:
Validate that every required input (within the form being submitted) is filled out.
Only provide the alert behavior if the browser doesn't already support the required attribute.
JavaScript :
function checkform(form) {
// get all the inputs within the submitted form
var inputs = form.getElementsByTagName('input');
for (var i = 0; i < inputs.length; i++) {
// only validate the inputs that have the required attribute
if(inputs[i].hasAttribute("required")){
if(inputs[i].value == ""){
// found an empty field that is required
alert("Please fill all required fields");
return false;
}
}
}
return true;
}
Be sure to add this to the checkform function, no need to check inputs that are not being submitted.
<form id="orderForm" onsubmit="return checkform(this)">
<input name="promotioncode" id="promotioncode" type="text" required />
<input name="price" id="price" type="text" value="€ 15,00" readonly="readonly"/>
<input class="submit" type="submit" value="Submit"/>
</form>
Depending on which browsers you're planning to support, you could use the HTML5 required attribute and forego the JS.
<input name="promotioncode" id="promotioncode" type="text" required />
Fiddle.
Demo: http://jsfiddle.net/techsin/tnJ7H/4/#
var form = document.getElementById('orderForm'),
inputs=[], ids= ['price','promotioncode'];
//findInputs
fi(form);
//main logic is here
form.onsubmit = function(e){
var c=true;
inputs.forEach(function(e){ if(!e.value) {c=false; return c;} });
if(!c) e.preventDefault();
};
//findInputs function
function fi(x){
var f = x.children,l=f.length;
while (l) {
ids.forEach(function(i){if(f[l-1].id == i) inputs.push(f[l-1]); });
l--;
}
}
Explanation:
To stop submit process you use event.preventDefault. Event is the parameter that gets passed to the function onsubmit event. It could be in html or addeventlistner.
To begin submit you have to stop prevent default from executing.
You can break forEach loop by retuning false only. Not using break; as with normal loops..
i have put id array where you can put names of elements that this forum would check if they are empty or not.
find input method simply goes over the child elements of form element and see if their id has been metnioned in id array. if it's then it adds that element to inputs which is later checked if there is a value in it before submitting. And if there isn't it calls prevent default.
I've got a form that has multiple submit buttons. One for changing data in a database, one for adding, and one for deleting. It looks like this:
<form action="addform.php" method="post" id="addform" onSubmit="return validate(this)">
<select name="listings" id="listings" size="1" onChange="javascript:updateForm()">
<!-- Here I have a php code that produces the listing menu based on a database query-->
</select>
<br />
Price: <input type="text" name="price" id="price" value="0"/><br />
Remarks: <textarea name="remarks" wrap="soft" id="remarks"></textarea><br />
<input type="submit" value="Update Database Listing" name="upbtn" id="upbtn" disabled="disabled"/>
<input type="submit" value="Delete Database Listing" name="delbtn" id="delbtn" disabled="disabled"/>
<br />
<input type="submit" value="Add Listing to Database" name="dbbtn" id="dbbtn"/>
<input type="button" value="Update Craigslist Output" name="clbtn" id="clbtn" onClick="javascript:updatePreview();"/>
</form>
There are actually more elements in the form, but that doesn't matter. What I want to know is, for my validation method, how can I check which submit button has been clicked?
I want it to do the following:
function validate(form){
if (the 'add new listing' or 'update listing' button was clicked'){
var valid = "Are you sure the following information is correct?" + '\\n';
valid += "\\nPrice: $";
valid += form.price.value;
valid += "\\nRemarks: ";
valid += form.remarks.value;
return confirm(valid);}
else {
return confirm("are you sure you want to delete that listing");
}
}
I assume there must be some way to do this relatively easily?
Why don't you set a global variable specifying which button was last clicked? Then you can check this variable in your validate method. Something like:
var clicked;
$("#upbtn").click(function() {clicked = 'update'});
// $("#delbtn").click(function() {clicked = 'delete'});
// ...
function validate(form) {
switch(clicked) {
case 'update':
break;
// more cases here ...
}
}
You can, for example, attach a click event to every submit button that will save a pointer to it in a variable or mark it with a specific attribute / class (it that case you will have to remove that marker from all other submit buttons in the event handler) and then in the submit callback you will know which one was clicked
I think it's easier to just use a click event on each button and handle it individually.
$(function() {
$('input[name=someName]').click(someFunc);
});
function someFunc() {
// Your validation code here
// return false if you want to stop the form submission
}
You could have a hidden field on a form and set the value of that field on clicking the button and then pick it up in your validation routine. You can use jquery to achieve this, let me know if you require an example.
You can use ajax submission with jQuery, you can try something like this:
$('form#addform input[type="submit"]').on('click',function(e){
e.preventDefault();
var current = $(this); //You got here the current clicked button
var form = current.parents('form');
$.ajax({
url:form.attr('action'),
type:form.attr('method'),
data:form.serialize(),
success:function(resp){
//Do crazy stuff here
}
});
});