Clear default values using onsubmit - javascript

I need to clear the default values from input fields using js, but all of my attempts so far have failed to target and clear the fields. I was hoping to use onSubmit to excute a function to clear all default values (if the user has not changed them) before the form is submitted.
<form method='get' class='custom_search widget custom_search_custom_fields__search' onSubmit='clearDefaults' action='http://www.example.com' >
<input name='cs-Price-2' id='cs-Price-2' class='short_form' value='Min. Price' />
<input name='cs-Price-3' id='cs-Price-3' class='short_form' value='Max Price' />
<input type='submit' name='search' class='formbutton' value=''/>
</form>
How would you accomplish this?

Read the ids+values of all your fields when the page first loads (using something like jquery to get all "textarea", "input" and "select" tags for example)
On submit, compare the now contained values to what you stored on loading the page
Replace the ones that have not changed with empty values
If it's still unclear, describe where you're getting stuck and I'll describe more in depth.
Edit: Adding some code, using jQuery. It's only for the textarea-tag and it doesn't respond to the actual events, but hopefully it explains the idea further:
// Keep default values here
var defaults = {};
// Run something like this on load
$('textarea').each(function(i, e) {
defaults[$(e).attr('id')] = $(e).text();
});
// Run something like this before submit
$('textarea').each(function(i, e){
if (defaults[$(e).attr('id')] === $(e).text())
$(e).text('');
})
Edit: Adding some more code for more detailed help. This should be somewhat complete code (with a quality disclaimer since I'm by no means a jQuery expert) and just requires to be included on your page. Nothing else has to be done, except giving all your input tags unique ids and type="text" (but they should have that anyway):
$(document).ready(function(){
// Default values will live here
var defaults = {};
// This reads and stores all text input defaults for later use
$('input[type=text]').each(function(){
defaults[$(this).attr('id')] = $(this).text();
});
// For each of your submit buttons,
// add an event handler for the submit event
// that finds all text inputs and clears the ones not changed
$('input[type=submit]').each(function(){
$(this).submit(function(){
$('input[type=text]').each(function(){
if (defaults[$(this).attr('id')] === $(this).text())
$(this).text('');
});
});
});
});
If this still doesn't make any sense, you should read some tutorials about jQuery and/or javascript.

Note: This is currently only supported in Google Chrome and Safari. I do not expect this to be a satisfactory answer to your problem, but I think it should be noted how this problem can be tackled in HTML 5.
HTML 5 introduced the placeholder attribute, which does not get submitted unless it was replaced:
<form>
<input name="q" placeholder="Search Bookmarks and History">
<input type="submit" value="Search">
</form>
Further reading:
DiveintoHTML5.ep.io: Live Example... And checking if the placeholder tag is supported
DiveintoHTML5.ep.io: Placeholder text

1) Instead of checking for changes on the client side you can check for the changes on the client side.
In the Page_Init function you will have values stored in the viewstate & the values in the text fields or whichever controls you are using.
You can compare the values and if they are not equal then set the Text to blank.
2) May I ask, what functionality are you trying to achieve ?

U can achieve it by using this in your submit function
function clearDefaults()
{
if(document.getElementById('cs-Price-2').value=="Min. Price")
{
document.getElementById('cs-Price-2').value='';
}
}

Related

Insert the value retrieved from localstorage to the input field

I am using localStorage where in I am able to store in previous page and retrive it in this page. (Checked it using alert).
name12=localStorage.getItem("content");
Now my requirement is to display it into the input field and make it non-editable.
Please help me out with it. I have tried different things but I am not able to get it right.
Used onblur="localStorage.setItem(this.name, this.value) in the input tag
and also tried to use
if name_2.value = name12; in script tag
To make a field uneditable, you can use the html attribute disabled on the input field. http://www.w3schools.com/tags/att_input_disabled.asp
To set a default value for a field, you can use the html attribute value. In your case since the value is dynamic, you probably want do not want to do that inline in the html. One possible solution is to set the value attribute through javascript like below.
<script type="text/javascript">
var name2 = document.getElementById("name_2");
name2.value = localStorage.getItem("content");;
</script>
Set the value of an input field
You have to assign the value to input using javascript.
<input username" id="name_2" type="text" placeholder="name" name="name_2" required="required" autofocus="autofocus">
<script>
var n = "5"; // read from storage here
var inpt = document.getElementById("name_2");
inpt.value = n;
inpt.disabled = true;
</script>
There are many places to find this information. Try reading the jquery documentation when you get stuck. For example, here is a page that describes how to set the value of an input element. StackOverflow also has many questions about this topic. A quick google search brings up this question about setting the value of input elements. We can also find SO questions about disabling input elements easily, like this one.
I encourage that you attempt to use more resources to find what you need before bringing your questions here.
Based on the answers to the questions I linked, we can set the input and then disable it to keep the value from changing:
$('#input').val(name12);
$('#input').prop('disabled', true);

Setting Default value of input textbox in Jquery EasyUI dialog

I have googled and looked throughout the whole documentation and could not figure out why value of input text is not shown. I am using FireFox latest version and below is what I have done so far.
<input name="amount" class="easyui-validatebox" id="d_amount" value="">
In regular html or php page we can give value="300" to set default value, but in EasyUI, it is not possible. So I was thinking possible alternative like below:
<script>
var m = '300';
document.getElementById("d_amount").value.innerHTML=m;
</script>
Nothing is shown and I am not getting any error. Any EasyUI expert, please help me.
NOTE: this input field is inside the dialog
To set the default value, you have to set the value attribute. However, that does not necessarily update the value property so you need to do both. So given:
<input name="amount" class="easyui-validatebox" id="d_amount" value="">
set the default value by setting the value attribute:
var input = document.getElementById('d_amount')
input.setAttribute('value', 'whatever');
now set the value property:
input.value = 'whatever';
Note that you can also get a reference to the input as a member of the form that it's in:
var input = document.formName.d_amount;
Use the below code
$("#d_amount").numberbox({
min:0,
precision:2,
value:300
})
Reference : numberbox
Or try this one
$("#d_amount").textbox({
buttonText:'Search',
iconCls:'icon-man',
iconAlign:'left',
value:"300"
});
Reference : textbox
use this code to set the value inside $(document).ready(function(){}
....
$("#d_amount").numberbox('setValue','300');
....
if still not working, just try to set name and id as the same name and id
<input name="d_amount" class="easyui-validatebox" id="d_amount" value="">
I am always working with this numberbox and it's working
I have found your thread because I am also having the same issue and I have just across this thing today. Your case is a little bit different (maybe) then my case because you want to set the default which can be changed by the user later (I believe). In my case, the value will be fixed (will not be changed) so I have applied a trick and hopefully it can give some ideas to you and others who are having same issue. Please refer below:
In first page says pageA.php:
<select name="myThing" id="myThing">
<option value="Your Desired Value" selected="selected">Something</option>
</select>
Still in the same page, under your $(document).ready( function(){ put the code below:
$("#myThing").val($("#myThing option:first").val());
That code is to make sure your desired value appears at the first row in the drop down. I say this because in EasyUI it seems when I use drop down and put single option, the first row will be blank and the second row will hold your input. So that is the trick to ensure your desired value appears on top and selected. Put the select under the form then during normal post, you will be able to get the value of it in the posted page. Enjoy. Thank you.
Suggestion: if your value can be changed by user, use placeholder and you can hide the default value from user using my trick.
try this
document.getElementById("d_amount").value=m;
you don't need innerHTML
I found the answer here. The trick is to use the code inside $(function(){});
$(function(){
var m=300;
$('#d_amount').textbox('setValue', m);
});
I too had this problem and it was solved using the following
First my input was in the form like this:
<input name="hostFirstName" id="hostFirstName" class="easyui-textbox">
I needed to load content from the db then pre-fill the input with this data so the user could edit the content.
I used the following javascript.
NOTE: i didn't hide this away inside an anonymous function() and it is working. I tested this first from the F12 console to make sure it was working before changing my code.
//populate with existing data
$('#hostFirstName').textbox('setValue', "Is this working?");
The docs on jeasyui.com don't provide this example when you look at the textbox api reference. But they do provide an example when looking at the combobox (http://www.jeasyui.com/documentation/index.php#) the combobox and textbox use the same setValue method.
Hopefully this works for you like it does for me.

Modify underlying form.reset() values

I'm using $('form-selector').get(0).reset() to reset form values to their original page load state.
After editing, the form will submit via $.ajax() and I'll have new "default" values on our server. The form element will still exist in the dom, and the user can submit again to update. I'd like the "default" (reset values) to reflect what's on our server (ignoring any other external updates). Is it possible to update the underlying values that form.reset() will change each form element to without a page refresh?
Cross-browser support would be nice, but since this is an internal app, Google Chrome only is sufficient.
HTML
<form>
<input type="text" value="foo" name="bar" />
<input type="submit" value="Submit" />
<Input type="reset" value="Reset" />
</form>
JAVASCRIPT
$(function(){
$('form').submit(function() {
// Omitting code that sends form values to the server
// TODO: update underlying form.reset()
// values to what's currently in each
// form element.
return false;
});
});
UPDATE
Ack! I failed to mention that I'm looking for something to handle all form element types.
i.e. input[type=text], input[type=radio], input[type=checkbox], select, textarea.
Would be especially awesome if it can handle HTML5 form elements as well...
i.e. input[type=date], input[type=number], input[email], input[url], input[type=range], input[type=color], etc.
Sorry for the confusion.
If you change attributes of the form elements directly, rather than using the .val() method, the new values will be reflected on a form reset. You'll need to treat text fields differently from radio buttons, checkboxes, etc.
$('input').attr('value', function() { return this.value });
$('textarea').prop('innerHTML', function() { return this.value });
$(':checked').attr('checked', 'checked');
$(':selected').attr('selected', 'selected');
$(':not(:checked)').removeAttr('checked');
$(':not(:selected)').removeAttr('selected');
Something like this:
$("#foo").prop("defaultValue", "bar");
As David Budiac mentioned in his comment, this doesn't work for select elements. Select elements have a separate property named defaultSelected.
More about the defaultValue property
I realize that these links go to Microsoft's site but they seem to work in pretty much all mainstream browsers.
Javascript does not know what the reset values are, so you'll have to define them either on page load or make hidden field(s) with the reset values. Then when you call reset, set them.
Let's say you have hidden fields for each field you have in your form, like text boxes (you can do similar ones for dropdowns and radio/select)
If you have 2 text fields (txtfield1 and txtfield2), you would also have hidden fields for them (called txtfield1-hdn and txtfield2-hdn respectively).
$('form-selector').get(0).reset(function() {
$('form-selector').find('input').each(function(){
$(this).val($($(this).attr('id') + '-hdn').val());
});
});
of if you have default values in the text field html then you can just do this:
<input id="Text1" type="text" value="myValue" />
$('form-selector').get(0).reset(function() {
$('form-selector').find('input').each(function(){
$(this).val($(this).attr('value'));
});
});

Custom form validation function on element with html 5

For a custom image selection tool I would like to create form validation based on html 5 form validation.
For example my form consists of the following elements:
<form class="cms-form" action="">
<table width="800">
<tr>
<td width="30%">Name:</td>
<td><input type="text" name="name" class="cms-input-text" maxlength="127" /></td>
</tr>
<tr>
<td>Image:</td>
<td><textarea name="icon" class="cms-input-file" data-file-resource="images" data-options="{"min":1,"max":3}">/location-to-image.png</textarea></td>
</tr>
<tr>
<td></td>
<td><input type="submit" value="Next"/></td>
</tr>
</table>
</form>
I have a Javascript that changes the textarea (.cms-input-file) into some html to add images and hides the original textarea.
It looks something like this:
<textarea name="icon" class="cms-input-file" data-file-resource="images" data-options="{"min":1,"max":3}" style="display: none;">/location-to-image.png</textarea>
<ul class="cms-input-file-list">
<li class="cms-input-file-item" data-image="/location-to-image.png">
<img src="/location-to-thumb.png" alt="" class="cms-input-file-item-thumbnail"/>
<span class="cms-input-file-item-title">location to image</span>
</li>
<li class="cms-input-file-add">Add</li>
</ul>
Since I have allot of existing forms using html5 form validation I would like to validate this element using the default form validation within html5 supported browsers, but using a hopefully existing event.
I'm looking for something like this:
$('.cms-input-file').on('customValidateFunction', function () {
var options = $(this).data('options');
if($(this).find('> li.cms-input-file-item').length < options.min)
{
return [false, 'Add more images.'];
}
if($(this).find('> li.cms-input-file-item').length > options.max)
{
return [false, 'Remove some images.'];
}
return true;
});
Does anyone know if something like this is possible using default html 5 events or how would I go about adding this event to the submit event? To actually trigger the default browser validation look and feel.
-- edit --
So far I have made an attempt to get this result using a div element which hides the original element. But now I need to add a pattern to the element to match according to my options. Is this possible?
Current progress: http://jsfiddle.net/jeffreydev/YyEVu/
If I understand correctly what you need, I think you can achieve what you are trying to do using the pattern attribute of any input element.
I've created a very simple form in jsfiddle illustrating this.
The idea is that you update the value of your input with whatever data you have in your model when adding or removing images. The example, just adds one letter f per icon. Then, you can create a regex to match the expected valid results. In the example, pattern="f{1,3}" means that to be valid, the content can be "f", "ff", or "fff" but nothing else, which means that it'll only accept from one to three files to be sent.
You would be using just default html5 form validation, but you may need a bit of tweaking to get it working.
However, if you try this way, you should keep a couple of things in mind:
As explained in the specs, the patttern is compiled as a JavaScript regular expression with the global, ignoreCase, and multiline flags disabled
Setting the disabled property of your input so that the user can't change it would take it out of the form, and thus it won't be validated
Applying certain styles as *display:none" to the input element can cause errors when the validation fails and the browser tries to gain focus on the element.
I hope you this helps
You can install a submit handler on the <form>, and dispatch a custom event from there.
That will look something like this:
$('form.cms-form').on('submit', function(evt) {
var frm = $(this);
var allElements = $(this.elements);
$('#errors').empty();
var errors = [];
var arg = {
reportValidationError : function( msg ) {
errors.push(msg);
},
form : this
};
console.log("all elements: ", allElements);
allElements.trigger('customValidate', [ arg ]);
if( errors.length !== 0 ) {
showValidationErrors(errors);
return false;
}
return true;
});
Then, you can "hook" the customValidate event, and install your own logic...
$('textarea[name=icon]').on('customValidate', function(evt, reporter) {
var options = $(this).data('options');
// ... your validation here ...
// for example:
var txt = $(this).val();
if( txt.length < options.min || txt.length > options.max ) {
reporter.reportValidationError('error: "icon" min/max exceeded!');
}
})
Here's an example at jsFiddle.
Edit
You can style the error reporting, and tweak the code, to look and behave however you want it to. Here's an example.
A very good jquery plugin to validate your forms is Mike Alsup one's.
You will find it here: http://jquery.malsup.com/form/
It is documented, ajax compatible.
It can do serialization for one field or for all fields inside the form, so it is a big advantage regarding your problem you could need to handle fields validation and error logic with your forms.
You could add the blockUI plugin of the same author to enhance user's experience, and don't have to manage double submission of the form when javascript is enabled.
http://jquery.malsup.com/block/
Answer from 2022: Yes, it is possible without jQuery etc.
Most browsers support Constraint Validation API (even IE 11 according to "caniuse")
The recommended practice is to listen to input/submit events and then set validity flags on the input-box.
<form>
<input type="text" required id="answer">
<input type="submit">
</form>
Validation JS:
const nameInput = document.querySelector("#answer");
const form = document.querySelector("form");
function validate(e) {
if (nameInput.value == "42") { //correct!
nameInput.setCustomValidity(""); // empty means "no error"
}
else {
nameInput.setCustomValidity("Wrong answer!"); //show error text
e.preventDefault(); //prevent form submit
}
}
nameInput.addEventListener("input", validate);
form.addEventListener("submit", validate);
The input event fires even when the value is changed programmatically
P.S. Codepen to play with: https://codepen.io/jitbit/pen/XWYZjXO

Show Input Box on Check

You can see in the paper form attached what I need to convert into a web form. I want it to show the check boxes and disable the input fields unless the user checks the box next to it. I've seen ways of doing this with one or two elements, but I want to do it with about 20-30 check/input pairs, and don't want to repeat the same code that many times. I'm just not experienced enough to figure this out on my own. Anyone know anywhere that explains how to do this? Thanks!
P.S. Eventually this data is all going to be sent through an email with PHP.
I don't think this is a good idea at all.
Think of the users. First they have to click to enter a value. So they always need to change their hand from mouse to keyboard. This is not very usable.
Why not just give the text-fields? When sending with email you could just leave out the empty values.
in your HTML :
//this will be the structure of each checkbox and input element.
<input type="checkbox" value="Public Relations" name="skills" /><input type="text" class="hidden"/> Public Relations <br/>
in your CSS:
.hidden{
display:none;
}
.shown{
display:block;
}
in your jQuery:
$('input[type=checkbox]').on('click', function () {
// our variable is defined as, "this.checked" - our value to test, first param "shown" returns if true, second param "hidden" returns if false
var inputDisplay = this.checked ? 'shown' : 'hidden';
//from here, we just need to find our next input in the DOM.
// it will always be the next element based on our HTML structure
//change the 'display' by using our inputDisplay variable as defined above
$(this).next('input').attr('class', inputDisplay );
});
Have fun.
Since your stated goal is to reduce typing repetitive code, the real answer to this thread is to get an IDE and the zen-coding plug in:
http://coding.smashingmagazine.com/2009/11/21/zen-coding-a-new-way-to-write-html-code/
http://vimeo.com/7405114

Categories