Modify underlying form.reset() values - javascript

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'));
});
});

Related

Change form parameter based on form selection

I have 3 different forms on a single page where the user can switch between using JS. The forms represent different information and only one can be submitted at a time where the user is then redirected to a different page based on the form they selected. The issue is that I have 2 input fields that are common to these forms so they are outside the forms. I am able to submit them alongside a form if I set the :
<input id="default" form="form1">
value.
So I figured it would be a simple thing to just add a function in each script where I hide/show the forms to also change that parameter to the form I want submitted however it doesn't seem to work.
function form2Search() {
$('#form2Section').show();
var input1 = document.getElementById('default');
input1.form = "form2";
}
I have something like this but it doesn't change the form parameter.
You need to actually give your input an ID of default so you can target it:
<input form="form1" id="default">
use setAttribute
function form2Search() {
$('#form2Section').show();
var input1 = document.getElementById('default');
input1.setAttribute("form", "form2");
console.log(input1.getAttribute("form"))
}
form2Search();
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input id="default" form="form1">

In a dynamically changing fields using jquery same field gets posted twice

I'm working on a form where I have a text field which will be changed on radio button selection.
$("#id_radio1").click(function() {
$("#multi_language").hide();
$("#single_language").show();
});
$("#id_radio2").click(function() {
$("#single_language").hide();
$("#multi_language").show();
});
Say suppose id_radio1 and id_radio2 are two radio buttons and selecting each changes the form fields differently. Now I was able to do it successfully.
My problem is when I submit the form after single language button is clicked the values are stored as multi as the values of the multi language hidden fields are submitted overridding the values of first.CAn I disable the other field without interference of the same on submission.
How can I correct this?
I'm new to such problem. I want the field to be submitted only once.i.e, if single language field is selected single should be posted and not multi(as it is working now) and when multilanguage is selected multi should be posted.How can I correct this now with the following code.
Fiddle
I have other fields common for both single and multi language in the same form as well, whose values are not changed on submission
Now, in the console I see there are two posts for the same fields in the response i.e. one for single language and other multi language.
You can format your html code as below just if you want to pass the value of the checked field to some other script
<form method="post">
<input id="id_radio1" type="radio" name="name_radio1" value="single" />
<label for="id_radio1">Single Language</label>
<input id="id_radio2" type="radio" name="name_radio1" value="multi" />
<label for="id_radio2">Multi Language</label>
<input type="submit" />
</form>
and in your Jquery Code, you can do this
$("form").on("submit", function(e) {
e.preventDefault();
console.log($("input:checked").val()); //do whatever you want with the checked value
})
Fiddle
You can use the disabled attribute to prevent an element from being sent like so:
$("#id_radio1").click(function() {
$("#multi_language").attr('disabled','disabled').hide();
$("#single_language").removeAttr('disabled').show();
});
$("#id_radio2").click(function() {
$("#single_language").attr('disabled','disabled').hide();
$("#multi_language").removeAttr('disabled').show();
});
Since they are no hidden fields but just hidden by css it should prevent it from being submitted
Why not just have one text input, then in your server-side code simply check which radio button was selected and set the value of the server-side variable accordingly before committing data.
e.g. In PHP for instance:
$language = $_POST['language'];
if($_POST['name_radio1'] == 'single'){
some_function_committing_single_language_value($language);
} else {
some_function_committing_multi_language_value($language);
}
Or have one text input and set the form's onsubmit handler with a Javascript function to insert a hidden field with a name such as 'language_single' or 'language_multi' based on the radio button selection, and set that hidden input's value to the textfield's value.

HTML : hiding input radios on form submit

I've got a HTML form that has two possible types ("id" or "profile")
<form action="process.php">
<input type="radio" name="type" value="id">
<input type="radio" name="type" value="profile">
<input type="text" name="value" value="input">
</form>
So essentially, my resulting URL is
/process.php?type=id&value=input
(or type=profile, depending on what the user picks)
What I want is my URLs to look something like
/process.php?id=input
or
/process.php?profile=input
I have two questions:
1) Is the following jQuery/JavaScript code "bad practice"? I really don't feel like I'm doing it correctly if I do it the following way (even though it works):
<input type="submit" onclick="formSubmit()">
<script>
function formSubmit() {
// if the first radio (id) is selected, set value name to "id", else "profile"
$("form input:text")[0].name = $("form input:radio")[0].checked ? "id" : "profile";
// disable radio buttons (i.e. do not submit)
$("form input:radio")[0].disabled = true;
$("form input:radio")[1].disabled = true;
}
</script>
2) Is there a way to do this without using htaccess rules or JavaScript?
Thanks!
As for your first question, I'd write my jQuery like this:
// store your form into a variable for reuse in the rest of the code
var form = $('form');
// bind a function to your form's submit. this way you
// don't have to add an onclick attribute to your html
// in an attempt to separate your pre-submit logic from
// the content on the page
form.submit(function() {
// text holds our text input
var text = $('input:text', form),
// radio holds all of our radio buttons
radio = $('input:radio', form),
// checked holds our radio button that is currently checked
checked = $('input:radio:checked', form);
// checking to see if checked exists (since the user can
// skip checking radio buttons)
if (checked) {
// setting the name of our text input to our checked
// radio button's value
text.prop('name', checked.val());
}
// disabling our radio buttons (not sure why because the form
// is about to submit which will take us to another page)
radio.prop('disabled', true);
});
As for your second question, you could always move this logic to the server side. It depends if you want the pre-processing logic to be done by the client, or by your server. Either way you should have logic on the server to validate the form. If your js errors out, it could send over the raw form data. Personally I'd put this logic on the server to avoid the overhead of checking to make sure it was pre-processed in the first place. You'll also be able to cut down on your js use which will save you some precious bandwidth.
You could try something like this:
<input type="radio" name="type" value="id" onclick="getElementById('textValue').setAttribute('name','id');">
<input type="radio" name="type" value="profile" onclick="getElementById('textValue').setAttribute('name','profile');">
<form action="process.php">
<input type="text" id="textValue" name="value" value="input">
<input type="submit">
</form>
Put the radio inputs outside the form, have the text input identified by an id so you can use the getElementById function (still needs to be checked if it is supported by the browser). This avoids loading jQuery if you don't need it on this page.
The result is the one expected by you.
But.. I would use server-side processing of the form.

Clear default values using onsubmit

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='';
}
}

Remove disabled attribute onClick of disabled form field

I have a form field that starts out disabled and has an onClick to enable it. The onClick doesn't fire (at least in FF) nor does a simple alert(1);.
The hacky version is to show a fake form field in its place that "looks" like it's disabled (grayed out style) and onClick, hide it and show the correct field enabled, but that's ugly.
Example Code
This works:
<input type="text" id="date_end" value="blah" onClick="this.disabled=true;">
This works:
<label for="date_end_off" onClick="document.getElementById('date_end').disabled=false">Test</label>
<input type="text" id="date_end" value="blah" onClick="alert(1);" disabled>
This fails:
<input type="text" id="date_end" value="blah" onClick="alert(1);" disabled>
This fails:
<input type="text" id="date_end" value="blah" onClick="document.getElementById('date_end').disabled=false" disabled>
I came across this thread in another forum so I assume I'll have to go about it a different way.
http://www.webdeveloper.com/forum/showthread.php?t=186057
Firefox, and perhaps other browsers,
disable DOM events on form fields that
are disabled. Any event that starts at
the disabled form field is completely
canceled and does not propagate up the
DOM tree. Correct me if I'm wrong, but
if you click on the disabled button,
the source of the event is the
disabled button and the click event is
completely wiped out. The browser
literally doesn't know the button got
clicked, nor does it pass the click
event on. It's as if you are clicking
on a black hole on the web page.
Work around:
Style the date fields to look as if
they are disabled.
Make a hidden "use_date" form field
with a bit value to determine
whether to use the date fields during processing.
Add new function to onClick of the date fields which will
change the style class to appear
enabled and set the "use_date" value
to 1.
Use readonly instead of disabled
For checkboxes at least, this makes them look disabled but behave normally (tested on Google Chrome). You'll have to catch the click and prevent the default action of the event as appropriate.
Using jQuery, I attach an event handler to the parents of my input controls.
<script type="text/javascript">
$(function() {
// disable all the input boxes
$(".input").attr("disabled", true);
// add handler to re-enable input boxes on click
$("td:has(.input)").click(function() {
$(".input", this).removeAttr("disabled");
});
});
</script>
All of my input controls have the class "input" and they exist in their own table cells. If you at least wrapped your input tags in a div, then this should work without a table as well.
Citing Quirksmode.org:
"A click event on a disabled form field does not fire events in Firefox and Safari. Opera fires the mousedown and mouseup events, but not the click event. IE fires mousedown and mouseup, but not click, on the form. All these implementations are considered correct."
Quirksmode's compatibility table is great to find out more about such problems.
I recently had a very similar problem and solved it by placing the input in a div and moving the onClick to the div.
<div onClick="myEnableFunction('date_end');">
<input type="text" id="date_end" value="blah" disabled>
</div>
Enabling a disabled element on click kind of defeats the purpose of disabling, don't you think? If you really want the behavior you're describing, just style it 'disabled' and remove those styles on click.
Don't implement the logic of the onClick event in the onClick's value of the input field. That's probably why it's not working in Firefox. Instead define a function as the onClick's value. For example:
<input type="text" id="date_end" value="blah" onClick="doSomething()" disabled>
<script type="text/javascript">
function doSomething()
{
alert("button pressed");
}
</script>
It will also be worth looking into JQuery. You can use it to add or remove attributes from elements and all kinds of other stuff. For instance you can remove the disabled from the the input field by writing a function like this:
<script type="text/javascript">
function doSomething()
{
alert("button pressed");
$("#date_end").removeAttr('disabled'); //removes the disabled attribut from the
//element whose id is 'date_end'
}
</script>
OR you can add it as follows:
$("#date_end").attr('disabled','true');
The Jquery site is here
You can add a div over the input that is disabled: check it out
<div onclick="javascript:document.forma.demo1.disabled=false;" style="border:0px solid black; padding:00px;">
<input type=text name="demo1" disabled style="width:30;">
</div>
In order to enable a disabled element on the client side, lets say in response to a checkbox checked or something, I ended up having to use a combination of JS and jQuery, see below:
//enable the yes & no RB
function enable()
{
var RBNo = "rbnBusinessType";
var RBYes = "rbnBusinessType";
//jQuery approach to remove disabled from containing spans
$("#" + RBYes).parent().removeAttr('disabled');
$("#" + RBNo).parent().removeAttr('disabled');
//enable yes and no RBs
document.getElementById(RBYes).disabled = false;
document.getElementById(RBNo).disabled = false;
}
After postback then, you'll need to access the request like the following in order to get at the values of your client side enabled elements:
this._Organization.BusinessTypeHUbZoneSmall = Request.Params["rbnBusinessTypeHUbZoneSmall"] == rbnBusinessTypeHUbZoneSmallYes.ID;
Inspiration taken from:
https://stackoverflow.com/questions/6995738/asp-javascript-radiobutton-enable-disable-not-included-in-postback-ajax for more information
If you simply want to prevent the user from typing data in your field, but instead want the field to populate on an event, my hack solution was to not disable the input field at all, but instead after running my onclick or onfocus functions, to call blur() so the user can not edit the field.

Categories