Sorry. Let me rephrase:
I want js to change to class of a input field if it is left empty; Here is my code to detect a empty field:
function validateForm()
{
var ctrl = document.forms["form1"]["username"];
var x=ctrl.value;
if (x==null || x=="") {
////////////CHANGE INPUT CLASS/////////////
}
else {
document.getElementById('username').style.backgroundColor="#FFFFFF";
}
}
i would have to css classes:
.inputfield {
background-color:white;
}
.inputfieldempty {
background-color:red;
}
To prevent submitting you need to call a function for the onsubmit event of the form (e.g. onsubmit="return checkFields()". In the function you will do the validations and return true or false depending on that. If the function will return false then the form will not be posted.
As part of your validations when you determine that a field's value is empty you can do the desired css changes as well. I don't know if you use vanilla javascript or a library such as jQuery in order to give more specific details.
Have a look at this tutorial for the excellent jQuery Validation plugin, which does exactly what you need and you don't even have to fiddle with cross-browser concerns.
If you don't want to use the plugin, I still recommend at least to use jQuery. Here's another tutorial that goes through all the necessary steps.
This post should take care of adding your CSS classes: Change an element's class with JavaScript
This post should take care of preventing forms to submit: https://developer.mozilla.org/en/DOM/event.preventDefault
Related
I am not very proficient in CSS or JavaScript yet and need some help. I am doing maintenance on a jsp page that has an input field which acts as a parameter in some search functionality. I added a JavaScript function that allows the user to press the enter key and fire off the search functionality, using the "onkeypress" event. The input field has three CSS classes on it. One of those CSS classes is keeping the JavaScript function from being called. I know this because removing the class allows the JavaScript to run. As soon as I put it back, the JavaScript won't run.
Here is the JavaScript, the CSS class (.personSearch) and the input field respectively.
function searchKeyPress(e) {
if(typeof e == 'undefined' && window.event) {
e = window.event;
}
if(e.keyCode == 13){
document.getElementById('searchButton').click();
}
}
.personSearch {
background-image: url(./../images/icons/personSearch.png);
background-position:center right;
background-repeat:no-repeat
}
<input class="fillWidth personSearch allowManualInput"
name="scrName"
id="personSearch-scr"
type="text"
onkeypress="searchKeyPress(event);"/>
Like I said above, when I actually remove the personSearch class from the input field, the JavaScript runs great. However, when I leave it, the JavaScript won't fire.
Thanks for any help!
It doesn't work because there is no element with an id="searchButton" defined in the HTML code.
<button id="searchButton" onclick="alert('here');">Click</button>
Working fiddle: http://jsfiddle.net/m7qov85g/
I have some fields with class="required" which has custom css.
When i submit the form, i see an custom error message which aplies the required fields the css:
$(".required").addClass('required-fields');
Now, when i complete some fields (not all required) and i submit again de form, maybe what i need to see is: in the fields which have data (not empty), should go another css. Like border green or something like that.
Is it possible to do with a for maybe?
You could try something like this:
$('.required').removeClass('ok').filter(function(){
return !!$(this).val();
}).addClass('ok');
It filters all required fields with a value and adds class 'ok';
http://jsfiddle.net/cHPS2/
You can check if the input has a value. For example if($("#nameInput).value) will be true if its not blank. You can add a class to those inputs.
for(var i=0;i<inputs.length;i++){
if(inputs[i].value){
//enter add class code here
}
}
You have to pass on every input with a Jquery selector like
var $fields = $('.field');
And check if the field is required or not and if a value is given or not like :
$fields.each(function ($field) {
if ($field.hasClass('required') && !$field.value) {
$field.addClass('required-fields');
}
else {
$field.addClass('green-fields');
}
});
It's a rapid draft :)
Form validation with user feedback is a sufficiently common requirement that you may wish to consider using a plugin rather than coding a custom solution (reinventing the wheel) each time:
http://jqueryvalidation.org/documentation
You may try something like following (Can't be more pecific because you didn't provide HTML):
$('.required').not('[value=""]').css(...);
Using css() you may change the look of your elements.
Update:
To add a class to them try this:
$('.required').not('[value=""]').addClass('className');
To remove a class and then add another class (Also you may use toggleClass) try this:
$('.required').not('[value=""]').removeClass('className').addClass('className');
An Example.
Try this:
$('input.required:text').filter(function() {
return $(this).val() == "";
}).css(...);
Cannot get this to work. First time using variables passed into functions. Unchecking radio button should disable form field and vice versa. lineid variable distinguishes this radio/text input pair from 10 others.
My code:
<script type="text/javascript">
function disablefield(lineid){
if (document.getElementById(lineid).checked == true){
document.dupedit.lineid.disabled = false;
} else {
document.dupedit.lineid.disabled = true;
}
}
</script>
Subset of my HTML.
You need to pass a string into your disablefield function, so put the value in quotes when you pass it in. Something like:
<input onclick="disablefield('2671997')" />
This is because document.getElementById expects a string, not an integer.
Secondly, to enable/disable the field, you need to use disabled = true; rather than = 'disabled'.
document.dupedit.lineid is looking a for a field with name "lineid", which doesn't exist in your form. I would suggest giving the field an id and using document.getElementById again instead.
If you want to continue using the name attribute, you will have to use document.getElementsByName instead. This returns an array of matching elements (since multiple elements can share the same name), but if in your code you know that the element in question is the only one with that name, you can do this:
document.getElementsByName(lineid)[0].disabled = true;
You can see a working version (I think this is how you wanted it anyway) here. And here is a version using getElementsByName.
You are missing a closing brace on the function:
function disablefield(lineid){
if (document.getElementById(lineid).checked == true){
document.dupedit.lineid='enabled';
}else{
document.dupedit.lineid='disabled';
}
} //<-- here
Also, can I suggest you pass this to the function. Then you don't have to call getElementById
<input onclick='disablefield(this)' type.....
function disablefield(obj){
if (obj.checked == true){
document.dupedit.lineid='enabled';
}else{
document.dupedit.lineid='disabled';
}
}
I think what you need is to re-think the code.
Don't use ID on the checkbox. Better move that ID to the text field you want to disable/enable and check whether that field is disabled/enabled, not the checkbox itself
use cleaner JS.
Please, take a look at the jsFiddle, I have compiled for you. Does it do what you expect, Dan?
I have a script which dynamically adds rows to a form with default values:
$(document).ready(function() {
var defaults = {
'name[]': 'Name',
'email[]': 'Email',
'organisation[]': 'Organisation',
'position[]': 'Position'
};
var setDefaults = function(inputElements, removeDefault)
{
$(inputElements).each(function() {
if (removeDefault)
{
if ($(this).data('isDefault'))
{
$(this).val('')
.removeData('isDefault')
.removeClass('default_value');
}
}
else
{
var d = defaults[this.name];
if (d && d.length)
{
this.value = d;
$(this).data('isDefault', true)
.addClass('default_value');
}
}
});
};
setDefaults(jQuery('form[name=booking] input'));
$(".add").click(function() {
var x = $("form > p:first-child").clone(true).insertBefore("form > p:last-child");
setDefaults(x.find('input'));
return false;
});
$(".remove").click(function() {
$(this).parent().remove();
});
// Toggles
$('form[name=booking]').delegate('input', {
'focus': function() {
setDefaults(this, true);
},
'blur': function() {
if (!this.value.length) setDefaults(this);
}
});
});
For the following form:
<form method="post" name="booking" action="bookingengine.php">
<p><input type="text" name="name[]">
<input type="text" name="email[]">
<input type="text" name="organisation[]">
<input type="text" name="position[]">
<span class="remove">Remove</span></p>
<p><span class="add">Add person</span><br /><br /><input type="submit" name="submit" id="submit" value="Submit" class="submit-button" /></p>
</form>
I would now like to split the form into 2 sections, each of which can have rows added dynamically to it. The second section would only have spaces for name and email, so the form as a whole, before any additional rows are added, would look something like this:
But I'm not sure how to achieve this. Either I would create a separate form with a seperate script, and then would need to know how to submit the information from both forms together, or I would just have one form but would then need to work out how to add rows dynamically to each section.
Could someone help with this?
Thanks,
Nick
I've implemented this in a fully functional example here.
I cleaned up your code a little bit, but it's basically the same. The main addition is that I wrapped the inputs in a fieldset element (you could use a div just as well, but fieldset is the semantically correct element for grouping related input fields). Your 4-input section lives in one fieldset, and your 2-input section lives in another; the "Add Person" handler looks for the parent fieldset, clones the first child, and adds it into that fieldset. Conveniently, in your use case the defaults for the first fieldset are the same as those for the second fieldset, but it would be easy enough to set up multiple sets of defaults and pass them into the setDefaults function.
A few other changes to the code:
I split your setDefaults function into two different functions, setDefaults and removeDefaults - you weren't gaining anything by making them a single function, and splitting them makes the code more legible.
I used .delegate to assign the "Remove" handler - otherwise the "Remove" button wouldn't work for new input sets. I also created the "Remove" button with jQuery, rather than cloning it, because I assumed that it wouldn't make sense to include it for the first input set.
I used jQuery in a couple of places where you were using raw Javascript (e.g. getting and setting input values). I generally assume that jQuery is more reliable for cross-browser DOM access and manipulation, so if you're loading the library already there's rarely any point not using it for all but the simplest DOM functions.
I removed your .data calls, since you can get the same information by inspecting the class, and it's generally better to reduce complexity. It's possible that .hasClass('test') is slightly slower than .data('test'), but I don't think it should make any difference here.
Create one form. Put two divs inside of it. Have your script add/remove form elements to the appropriate div.
When you submit the form it should automatically submit all of the form elements in both divs since the divs are contained in the form.
I am having some problems with Javascript :(
This is an HTML form for a mobile webpage. To save space I put the names of the text fields inside the boxes. The name disappears when you focus on the box, but I am not able to make it reappear if the user didn't write anything.
Here is the Script (in head tag):
<script type="text/javascript"> resetDefault();{if (this.value.length==0); this.value="default";} </script>
Here is the HTML code:
<input onfocus="this.value=''" onblur="resetDefault()" name="nom" type="text" value="Nom complet" default="Nom complet"/><br><input onfocus="this.value=''" onblur="resetDefault()"name="courriel" type="text" value="Courriel" default="Courriel"/><br>
I keep getting a "resetDefault is not defined" error. I don't know if default is an accepted attribute for input, but I can't set it to "value" because value becomes 0 once someone has focused on the text field, right?
There are several problems with your javascript code. First, it is not syntactically correct. You should first change this code
resetDefault();
{if (this.value.length==0);
this.value="default";}
so that it has valid syntax, like this:
function resetDefault(){
if(this.value.length == 0){
this.value = "default";
}
}
The second problem is that this refers to the global object, instead of the DOM node you want. You need to pass in a value so it knows which input to change.
Change the onblur javascript so that it passes in a parameter to the function:
onblur="resetDefault(this);"
and change the function so it accepts a parameter:
function resetDefault(that){
if (that.value.length == 0){
that.value="default";
}
}
The third problem is that "default" will just change the value of the input box to the string, "default". I doubt that is what you want. Make the value match the default attribute you gave the input:
that.value = that.getAttribute("default");
Try it out on JSFiddle
The semicolon after resetDefault() in the script in the head needs to be removed - now it's a function call of a function that's not defined.
<script type="text/javascript">function resetDefault() { if (this.value.length==0) this.value="default";} </script>
You need to define the resetDefault() function like so:
function resetDefault() {
// Function stuff here
}