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?
Related
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(...);
I have a dropdown box and I want to select the option based on value. Somehow I am getting handle to value say 3. Now I want to manually select the option which has got value 3.
I have tried something like this
selectBoxElement.options[selectedValues].selected = true;
where selectedValue = 3, but it is not working.
If using jquery (as per your tag), you can do:
$(document).ready(function() {
$("#yourSelectId option[value='3']").attr("selected", "selected");
});
Something like that should work (assuming $ is not overwritten and is alias for jQuery):
$(selectBoxElement).find('option[value="selectedValue"]').prop('selected', true);
or rather:
$(selectBoxElement).val(selectedValue);
which is simpler and achieves similar result :)
If you're using plain JS (except for the jQuery tag, you didn't explicitly say whether you want plain JS or jQuery), this should do what you want:
for (i=0; i<selectBoxElement.options.length; i++) {
if (selectBoxElement.options[i].value == selectedValues) {
selectBoxElement.options[i].selected=true;
break;
}
}
This is simple please try the following
When using the index position of the option tag within the select box
selectBoxElement.selectedIndex = index; // Where the index starts from 0
When using the value
selectBoxElement.value = value;// Where the value is the attribute defined within option tag
Hope this solves your problem.
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
}
I am trying to change the selected option in a select dropdown box with jQuery. I have it set so that it finds the hash tag at the end of the URL and based on that hash tag it changes the selected option in the select box.
Most of my code is functional, it successfully finds the hash tag and executes the if statement that corresponds with it. However, when it goes to execute the "then" section of the statement when it goes to the selector for the option (which uses an attribute selector based on the value attribute of the option tag) it returns null. If figured this out with firebug, in the console it says that the selector is null.
Here is my code:
$(document).ready(function() {
var $hash = window.location.hash
if($hash == "#htmlcss") {
$('option[value="HTML/CSS Coding"]').attr("selected","selected")
}
if($hash == "#php") {
$('option[value="PHP Coding"]').attr("selected","selected")
}
if($hash == "#jscript") {
$('option[value="Javascript and jQuery Coding"]').attr("selected","selected")
}
if($hash == "#improv") {
$('option[value="General Website Improvements"]').attr("selected","selected")
}
if($hash == "#towp") {
$('option[value="Website Conversion to Wordpress"]').attr("selected","selected")
}
if($hash == "#wptheme") {
$('option[value="Wordpress Theme Design"]').attr("selected","selected")
}
if($hash == "#complete") {
$('option[value="Complete Website Creation"]').attr("selected","selected")
}
if($hash == "#server") {
$('option[value="Web Server Configuration"]').attr("selected","selected")
}
});
So to clarify, when I enter in a url that ends in the #php hash tag, for example, the desired action does not occur which would change the "PHP Coding" option to the selected one by using the "selected" html attribute however the selector for the particular option tag returns null. Is there a problem with my syntax or is my code not functioning in the way that I think it should? Thanks very much.
You can slim it down and resolve your selector issue at the same time, just use .val() like this:
var hashmap = {
htmlcss: "HTML/CSS Coding",
php: "PHP Coding",
jscript: "Javascript and jQuery Coding",
improv: "General Website Improvements",
towp: "Website Conversion to Wordpress",
wptheme: "Wordpress Theme Design",
complete: "Complete Website Creation",
server: "Web Server Configuration"
};
$(function() {
var $hash = window.location.hash.replace('#','');
$("#IDOfSelectElement").val(hashmap[$hash]);
});
This approach sets the value on the <select> (finding it by it's ID) using .val(), which selects the <option> with the value matching what you passed in, this resolves escaping issues as well. However, I'm not certain the values you have are the actual value="" portion, they seem like the text of the <option>...make sure you're using the value="" portion. The other optimization is that this uses an object map to make this much easier to maintain :)
You shouldn't use quotes in the value selector, also I think you might need to escape the slash, i.e.:
$('option[value=HTML\\/CSS Coding]').attr("selected","selected")
For more info, see http://api.jquery.com/category/selectors/
Probably just add this code before your if statements:
$('option').removeAttr('selected');
Though know that if you have more then one select on the page, then that affects all of them.
Why not to assign id for each select option? It would make your code more tidy
$(document).ready(function() {
$(window.location.hash).attr("selected","selected");
});
I'm using mootools to toggle the display (and existence) of two DOM elements in one of my forms. Then, I am using javascript to validate the form to make sure that all of the required fields were filled in. The problem is that the the browser seems to be caching the elements. For example, I have html like this:
<input name="inputbox" id="inputbox" type="text" />
<select name="selection" id="selection">...</select>
And the javascript for validation is something like this:
if (form.inputbox != null && form.inputbox.value == "") {
//don't submit form
{
else if (form.selection != null && form.selection.value == 0) {
//don't submit form
}
Now, this works fine when the page is first loaded and the input element has been removed. However, when I click the button that replaces the input element with the select element, from then on the form.inputbox and form.selection in the javascript code contain the respective element as it was in its last state in the DOM - even if it is no longer in the DOM. So is the javascript caching the DOM and not updating the elements when they are removed from the DOM? What is going on here, and, more importantly, how should I go about fixing it?
Edit: I am using mootools to do the removing and replacing of the elements, the documentation for the respective functions can be found here and here.
Evaluating an element by name (form.elementName) when non-existent returns undefined. Evaluating the property value of an object ($('elementId')) returns null. Undefined and null are treated differently.
Well, I can answer the second part of my question now: how to fix it. If you are using mootools, then use the dollar function (or getElementById might work) instead of using form.selection and form.inputbox:
if ($("inputbox") != null && $("inputbox").value == "") {
//don't submit form
{
else if ($("selection") != null && $("selection").value == 0) {
//don't submit form
}
It works, but I don't have an explanation for why the other didn't...