using placeholders or title where value is empty - javascript

I am using the form where in a situation i have to use placeholder or title to insert the value in the database, i know we can use
$form.serialize which picks all the values of the form, but in my case value field is always going to be empty and i want to pick placeholders value and title value if placeholder is not defined just like serialization,
is there custom build jquery code or something already build in, how can i can use it just like $(form).serializePlaceholder or $(form).serializrtitle
well if some cases like IE8, placeholders are not supported, it should automatically pick title or i can define it in such a way that if placeholder is not defined, pick title

Try replacing empty values with their placeholder when the form is submitted, like so:
jQuery(function($) {
$('form').on('submit', function(e) {
e.preventDefault();
$(this).children('input, textarea').each(function() {
if(!$(this).val()) {
$(this).val($(this).attr('placeholder'));
}
});
$(this).submit();
});
});

An answer to your question lies in this bin I created. I think it solves your problem and if it does, I would like to ask you politely to remove the last comment you added on the thread you had with D4V1D.
Cheers!

Related

Working With Dynamically Created Inputs

I have a dynamic form that you can add elements. Like, you type a name, and then if you have to write a new name, you click on 'Add Name', and another textbox appears.
Their names are names[]. I can process those inputs with PHP on the server-side. However, I want to make a calculation with those inputs, like writing all of them on the page as the user types.
However, because those inputs, those textboxes are created dynamically, Javascript only selects the first textbox with the name name[].
Let me make it clear. This way it'll be better. I got a textbox. I input age in there. If I want to enter a new age, I click 'Add Age' button, and a new input box pops out. I write the new age value. And as I type, on a 3rd textbox, the average of those age values get printed. But because of those input boxes, with names ages[] are created on the execution time (not the compile time, I'm not sure these are the appropriate words for those. Probably not, because nothing is compiling? - or is it?), I can't process them.
What must I do to solve this problem?
I used both
$('input[name=ages\\[\\]]').change(function(){
console.log('1');
});
and
$('input[name=ages\\[\\]]').on('input', function() {
console.log('2');
});
but it didn't work.
Thanks in advance.
There's no need to escape the square brackets (though you should enclose the whole field name in double quotes). This works for me:
$('input[name="names[]"]').on('change', function(){
console.log($(this).val());
});
Here's a jsfiddle demonstrating: http://jsfiddle.net/t7J5t/
Your problem is actually probably related to the fact that you're adding the fields dynamically. The way you're using your selector will only work on the fields that already exist. Fields that are added after that selector will not be picked up. What you want to do, then, is put the selector inside the .on, like this:
$('.container').on('change', 'input[name="names[]"]', function(){
console.log($(this).val());
});
This will bind the listener to the container, not the fields (just make sure your fields get added inside of the container; you can call it whatever you want).
Incidentally, there's no reason you have to restrict yourself from using the name attribute of fields when using jQuery selectors. For example, you could use a class:
<div class="container">
<input class="age" name="ages[]">
<input class="age" name="ages[]">
<!-- ... as many more as needed, added dynamically is OK ... -->
</div>
<script>
$(document).ready(function(){
$('.container').on('change', 'input.age', function(){
console.log($(this).val());
});
});
</script>
Here's a sample of it in action, where you can dynamically add fields, and it calculates the average:
http://jsfiddle.net/t7J5t/1/
Try to use:
$(document).on('change', 'input[name=ages\\[\\]]', function() {
console.log('2');
});

Set and get value of input with jStorage

I'm using jStorage to store the value of an input, when I click the save button. Then I want to set the stored value as the current input value on page load. It ain't working too well though.
HTML
<input type='text' id='name'>
<div id="save">Save</div>
JS
$('#save').click(function() {
$.jStorage.set("key", $("#name").val());
});
var input_value = $.jStorage.get("key");
It's a little tangled up:
$.jStorage.set("key", $("#name").val());
var input_value = $.jStorage.get("key");
When you're passing a selector to jQuery you have to pass a valid string, not just the raw CSS selector syntax. That is, you've got to get the selector expression into JavaScript first, and you do that by creating a string constant.
edit — If you want your <input> to show the last-saved value when the page loads, you'd do something like this:
$(function() {
$('#name').val( $.jStorage.get("key") || "" );
});
Wrapping the activity in a $(function() { ... }) wrapper ensures that the code won't run until the <input> field has been seen and parsed by the browser, but still very soon after the user sees the page load (essentially immediately).
Adding the extra || "" bit after the jStorage call ensures that if the value is null or undefined the user won't see that. If there's no stored value, in other words, that'll have the input just be empty. You could put any other default value in there of course.

Using JQuery MaskInput Plugin with a SSN Field

I am trying to use the JQuery MaskInput plugin on a SSN field but I dont see anyway to make it display "***-**-****" after the user leaves the fields.
Did anyone get this working>
I havent tested this, but it may get you headed in the right direction. The masked input plugin has a completed function that can be called when the user has finished entering their value. You can use it to grab the value and store it in a hidden field to retain it and replace the current text with whatever you desire.
var $txt_SNN = $("#txt_SSN");
$txt_SNN.mask("999-99-9999", {
completed: function() {
$('#hdf_SNN').val($txt_SNN.val());
$txt_SNN.val("999-99-9999");
}
});
$txt_SNN.mask("999-99-9999").blur(function() {
$(this).attr('type', 'password');
});`
This should do it. Although I didn't test it.

JavaScript: True form reset for hidden fields

Unfortunately form.reset() function doesn't reset hidden inputs of the form.
Checked in FF3 and Chromium.
Does any one have an idea how to do the reset for hidden fields as well?
Seems the easiest way of doing that is having <input style="display: none" type="text"/> field instead of <input type="hidden"/> field.
At this case default reset process regularly.
This is correct as per the standard, unfortunately. A bad spec wart IMO. IE provides hidden fields with a resettable defaultValue nonetheless. See this discussion: it's not (alas) going to change in HTML5.
(Luckily, there is rarely any need to reset a form. As a UI feature it's generally frowned upon.)
Since you can't get the original value of the value attribute at all, you would have to duplicate it in another attribute and fetch that. eg.:
<form id="f">
<input type="hidden" name="foo" value="bar" class="value=bar"/>
function resetForm() {
var f= document.getElementById('f');
f.reset();
f.elements.foo.value= Element_getClassValue(f.elements.foo, 'value');
}
function Element_getClassValue(el, classname) {
var prefix= classname+'=';
var classes= el.className.split(/\s+/);
for (var i= classes.length; i-->0;)
if (classes[i].substring(0, prefix.length)===prefix)
return classes[i].substring(prefix.length);
return '';
}
Alternative ways of smuggling that value in might include HTML5 data, another spare attribute like title, an immediately-following <!-- comment --> to read the value from, explicit additional JS information, or extra hidden fields just to hold the default values.
Whatever approach, it would have to clutter up the HTML; it can't be created by script at document ready time because some browsers will have already overridden the field's value with a remembered value (from a reload or back button press) by that time that code executes.
Another answer, in case anyone comes here looking for one.
Serialize the form after the page loads and use those values to reset the hidden fields later:
var serializedForm = $('#myForm').serialize();
Then, to reset the form:
function fullReset(){
$('#myForm').reset(); // resets everything except hidden fields
var formFields = decodeURIComponent(serializedForm).split('&'); //split up the serialized form into variable pairs
//put it into an associative array
var splitFields = new Array();
for(i in formFields){
vals= formFields[i].split('=');
splitFields[vals[0]] = vals[1];
}
$('#myForm').find('input[type=hidden]').each(function(){
this.value = splitFields[this.name];
});
}
You can use jQuery - this will empty hidden fields:
$('form').on('reset', function() {
$("input[type='hidden']", $(this)).val('');
});
Tip: just make sure you're not resetting csrf token field or anything else that shouldn't be emptied. You can narrow down element's specification if needed.
If you want to reset the field to a default value you can use(not tested):
$('form').on('reset', function() {
$("input[type='hidden']", $(this)).each(function() {
var $t = $(this);
$t.val($t.data('defaultvalue'));
});
});
and save the default value in the data-defaultvalue="Something" property.
I found it easier to just set a default value when the document is loaded then trap the reset and reset the hidden puppies back to their original value. For example,
//fix form reset (hidden fields don't get reset - this will fix that pain in the arse issue)
$( document ).ready(function() {
$("#myForm").find("input:hidden").each(function() {
$(this).data("myDefaultValue", $(this).val());
});
$("#myForm").off("reset.myarse");
$("#myForm").on("reset.myarse", function() {
var myDefaultValue = $(this).data("myDefaultValue");
if (myDefaultValue != null) {
$(this).val(myDefaultValue);
}
});
}
Hope this helps someone out :)
$('#form :reset').on('click',function(e)({
e.preventDefault();
e.stopImmediatePropagation();
$("#form input:hidden,#form :text,#form textarea").val('');
});
For select, checkbox, radio, it's better you know (hold) the default values and in that event handler, you set them to their default values.
Create a button and add JavaScript to the onClick event which clears the fields.
That said, I'm curious why you want to reset these fields. Usually, they contain internal data. If I would clear them in my code, the post of the form would fail (for example after the user has entered the new data and tries to submit the form).
[EDIT] I misunderstood your question. If you're worried that someone might tamper with the values in the hidden fields, then there is no way to reset them. For example, you can call reset() on the form but not on a field in the form.
You could think that you could save the values in a JavaScript file and use that to reset the values but when a user can tamper with the hidden fields, he can tamper with the JavaScript as well.
So from a security point of view, if you need to reset hidden fields, then avoid them in the first place and save the information in the session on the server.
How I would do it is put an event listener on the change event of the hidden field. In that listener function you could save the initial value to the DOM element storage (mootools, jquery) and then listen to the reset event of the form to restore the initial values stored in the hidden form field storage.
This will do:
$("#form input:hidden").val('').trigger('change');
You can reset hidden input field value using below line, you just need to change your form id instead of frmForm.
$("#frmForm input:hidden").val(' ');

Delete empty values from form's params before submitting it

I have some javascript which catches changes to a form then calls the form's regular submit function. The form is a GET form (for a search) and i have lots of empty attributes come through in the params. What i'd like to do is to delete any empty attributes before submitting, to get a cleaner url: for example, if someone changes the 'subject' select to 'english' i want their search url to be
http://localhost:3000/quizzes?subject=English
rather than
http://localhost:3000/quizzes?term=&subject=English&topic=&age_group_id=&difficulty_id=&made_by=&order=&style=
as it is at the moment. This is just purely for the purpose of having a cleaner and more meaningful url to link to and for people's bookmarks etc. So, what i need is something along these lines, but this isn't right as i'm not editing the actual form but a js object made from the form's params:
quizSearchForm = jQuery("#searchForm");
formParams = quizSearchForm.serializeArray();
//remove any empty fields from the form params before submitting, for a cleaner url
//this won't work as we're not changing the form, just an object made from it.
for (i in formParams) {
if (formParams[i] === null || formParams[i] === "") {
delete formParams[i];
}
}
//submit the form
I think i'm close with this, but i'm missing the step of how to edit the actual form's attributes rather than make another object and edit that.
grateful for any advice - max
EDIT - SOLVED - thanks to the many people who posted about this. Here's what i have, which seems to work perfectly.
function submitSearchForm(){
quizSearchForm = jQuery("#searchForm");
//disable empty fields so they don't clutter up the url
quizSearchForm.find(':input[value=""]').attr('disabled', true);
quizSearchForm.submit();
}
The inputs with attribute disabled set to true won't be submitted with the form. So in one jQuery line:
$(':input[value=""]').attr('disabled', true);
$('form#searchForm').submit(function() {
$(':input', this).each(function() {
this.disabled = !($(this).val());
});
});
You can't do it that way if you call the form's submit method; that will submit the entire form, not the array you've had jQuery create for you.
What you can do is disable the form fields that are empty prior to submitting the form; disabled fields are omitted from form submission. So walk through the form's elements and for each one that's empty, disable it, and then call the submit method on the form. (If its target is another window, you'll then want to go back and re-enable the fields. If its target is the current window, it doesn't matter, the page will be replaced anyway.)
Well one thing you could do would be to disable the empty inputs before calling "serializeArray"
$('#searchForm').find('input, textarea, select').each(function(_, inp) {
if ($(inp).val() === '' || $(inp).val() === null)
inp.disabled = true;
}
});
The "serializeArray()" routine will not include those in its results. Now, you may need to go back and re-enable those if the form post is not going to result in a completely refreshed page.
Maybe some of the proposed solutions worked at the moment the question was made (March 2010) but today, August 2014, the solution of disabling empty inputs is just not working. The disabled fields are sended too in my Google Chrome. However, I tried removing the "name" attribute and it worked fine!
$('form').submit(function(){
$(this).find('input[name], select[name]').each(function(){
if (!$(this).val()){
$(this).removeAttr('name');
}
});
});
Update:
Ok, probably the reason because disabling fields doesn't worked to me is not that something changed since 2010. But still not working in my Google Chrome. I don't know, maybe is just in the linux version. Anyway, I think that removing the name attr is better since, despite what policy takes the browser about disabled fields, there is no way to send the parameters if the name attr is missing. Another advantage is that usually disabling fields implies some style changes, and is not nice to see a style change in the form a second before the form is finally submited.
There is also a drawback, as Max Williams mentioned in the comments, since the remove name attr solution is not toggleable. Here is a way to avoid this problem:
$('form').submit(function(){
$(this).find('input[name], select[name]').each(function(){
if (!$(this).val()){
$(this).data('name', $(this).attr('name'));
$(this).removeAttr('name');
}
});
});
function recoverNames(){
$(this).find('input[name], select[name]').each(function(){
if ($(this).data('name')){
$(this).attr('name', $(this).data('name'));
}
});
}
However, I think this is not a very common case since we are submitting the form so it is assumed that there is no need to recover the missing name attrs.
Your problem helped me figure out my situation, which is a bit different - so maybe someone else can benefit from it. Instead of directly submitting a form, I needed to prevent empty form elements from being collected into a serialized array which is then posted via AJAX.
In my case, I simply needed to loop through the form elements and disable all that were empty, and then collect the leftovers into an array like so:
// Loop through empty fields and disable them to prevent inclusion in array
$('#OptionB input, select').each(function(){
if($(this).val()==''){
$(this).attr('disabled', true);
}
});
// Collect active fields into array to submit
var updateData = $('#OptionB input, select').serializeArray();
Or serialize, clear empty key=value pairs with regex and call window.location:
$("#form").submit( function(e){
e.preventDefault();
//convert form to query string, i.e. a=1&b=&c=, then cleanup with regex
var q = $(this).serialize().replace(/&?[\w\-\d_]+=&|&?[\w\-\d_]+=$/gi,""),
url = this.getAttribute('action')+ (q.length > 0 ? "?"+q : "");
window.location.href = url;
});
Another approach I always recommend is to do that on server side, so you are able to:
Validate the input data correctly
Set default values
Change input values if needed
Have a clean URL or a friendly URL such as "/quizzes/english/level-1/"
Otherwise you will have to deal with text input, select, radio etc...

Categories

Resources