Javascript: How to check if a DropDownList is disabled - javascript

This function check if the the DropDownList is disabled.
function CheckRowBeforeSaving() {
for (i = 0; i < document.forms[0].length; i++) {
if (e.id.indexOf("_ddlTask") != -1) {
var disabled = e.disabled;
alert(disabled);
}
}
}
I've noticed that when the DropDownList is enabled, the alert box appears with the message "False". When the DropDownList is disabled, the alert message does not even appear. How to solve that problem?
EDIT
I've removed the condition but the result is still the same.
Thanks for helping

I've noticed that when the DropDownList is enabled, the alert box appears with the message "False". When the DropDownList is disabled, the alert message does not even appear. How to solve that problem?
Remove the condition that only checks for disabled==false since is already disabled (disabled=true)
if (disabled == false) { // <-----REMOVE THIS LINE
alert(disabled);
}

Replace
if (disabled == false) {
alert(disabled);
}
with just alert(disabled);
That is remove the check for disabled

Take a look at this SO question -- ASP.NET assigns its own client IDs
You may need
function CheckRowBeforeSaving() {
for (i = 0; i < document.forms[0].length; i++) {
if (e.id.indexOf('<%= myDDL.ClientID %>') != -1) {
var disabled = e.disabled;
alert(disabled);
}
}
}

Related

Checkbox manipulation with javascript/jquery

Hello I have a problem with checkboxes in my app.
I want to set value of layer visibility to false when other layer visibility is true and also set checkbox value to checked when visibility of layer is true. I have problem with .click function - console throws me typeError checkbox[i].click is not a function.
var changeLayer = function() {
if (layers[0].M.visible == true) {
layers[1].M.visible == false
} else if (layers[0].M.visible == false) {
layers[1].M.visible == true
}
if (layers[1].M.visible == true) {
layers[0].M.visible == false
} else if (layers[1].M.visible == false) {
layers[0].M.visible == true
}
}
var checkbox = $('.layer');
for (i = 0; i < checkbox.length; i++) {
checkbox[i].click(changeLayer);
//$(checkbox[i]).on('click', changeLayer)
}
Here is image of layer switcher where after click on first layer, second one should hide and uncheck the box.
I know that is maybe silly question, but I couldn't find solution. I hope you can help me.
Your code looks fine, but you could simplify it quite a bit. The following will bind the same event to all elements with the class 'layer'.
$('.layer').click(changeLayer);
We'll probably need some more context to provide better solutions. As an FYI .click(someHandler) is just a shortcut for .on('click', someHandler), they are the same.

Highlight empty select box after alert

I have a site using input:text, select and select multiple elements that generate a text output on button click.
Having searched SO, I found examples of validation code that will alert the user when a select field returns an empty value-
// alert if a select box selection is not made
var selectEls = document.querySelectorAll('select'),
numSelects = selectEls.length;
for(var x=0;x<numSelects;x++) {
if (selectEls[x].value === '') {
alert('One or more required fields does not have a choice selected... please check your form');
return false;
$(this).addClass("highlight");
}
At the end, I tried to add a condition after the alert is dismissed, such that the offending select box will be highlighted by adding the 'highlight' class - but this doesn't do anything. My .highlight css is {border: 1px red solid;}
Any help here?
UPDATED WITH ANSWER - Thanks #Adam Rackis
This code works perfectly. I added a line to remove any added '.highlight' class for selects that did not cause an error after fixing
// alert if a select box selection is not made
var selectEls = document.querySelectorAll('select'),
numSelects = selectEls.length;
$('select').removeClass("highlight");//added this to clear formatting when fixed after alert
var anyInvalid = false;
for(var x=0;x<numSelects;x++) {
if (selectEls[x].value === '') {
$(selectEls[x]).addClass("highlight");
anyInvalid = true;
}}
if (anyInvalid) {
alert('One or more required fields does not have a choice selected... please check your form');
return false;
}
You were close. In your loop, this does not refer to each select that you're checking.
Also, you're returning false prior to the highlight class being added. You'll probably want to keep track of whether any select's are invalid, and return false at the very end after you're done with all validation.
Finally, consider moving your alert to the very bottom, so your user won't see multiple alerts.
var anyInvalid = false;
for(var x=0;x<numSelects;x++) {
if (selectEls[x].value === '') {
$(selectEls[x]).addClass("highlight");
anyInvalid = true;
}
}
if (anyInvalid) {
alert('One or more required fields does not have a choice selected... please check your form');
return false;
}
Also, since you're already using jQuery, why not take advantage of its features a bit more:
$('select').each(function(i, sel){
if (sel.value === '') {
$(el).addClass("highlight");
anyInvalid = true;
}
});
if (anyInvalid) {
alert('One or more required fields does not have a choice selected... please check your form');
return false;
}

How to test if users has made any changes to a form if they haven't saved it

Basically the same functionality as stackoverflow when posting a question, if you start writing a post then try to reload the page. You get a javascript alert box warning message.
I understand how to check if the form has been changed, although how do I do the next step.
I.E: How to I check this when leaving the page, on here you get "This page is asking you to confirm that you want to leave - data you have entered may not be saved."?
EDIT: found correct answer here to another question https://stackoverflow.com/a/2366024/560287
I'm very sure that if you search, 'jQuery detect form change plugin', you will find something much more usable than this semi-pseudo code i'm about to write:
formChanged = function(form) {
form.find('input[type="text"], textarea').each(function(elem) {
if (elem.defaultValue != elem.value) {
return true;
}
});
// repeat for checkbox/radio: .defaultChecked
// repeat for ddl/listbox: .defaultSelected
return false;
}
usage:
if (formChanged($('form')) { // do something }
Note that this is to detect changes against the original rendered value. For instance, if a textbox has a value = "x", and the user changes it to "y", then changes it back to "x"; this will detect it as NO change.
If you do not care about this scenario, you can just do this:
window.formChanged = false;
$(':input').change(function() {
window.formChanged = true;
});
Then you can just check that value.
Yes, it is JavaScript as HTML is just a markup language.
Yes, jQuery can be used for this. It's preferable over vanilla JavaScript as it makes things easier, although it does add some overhead.
There are a number of ways to check if any of a form's controls have changed.
To check for changes from the default, most can be checked against the defaultValue property. For radio buttons, you should always have one checked by default, so check if it's still selected or not. Similarly for selects, set the selected attribute for the default option and see if it's still selected, and so on.
Alternatively, if all your form controls have an ID or unique name, you can collect all their values onload and then check their values when the form is submitted.
Another method is to listen for change events on each form control, but that is a bit over the top.
Here's a POJS version that takes the same approach as rkw's answer:
/*
Check if any control in a form has changed from its default value.
Checks against the default value for inputs and textareas,
defaultChecked for radio buttons and checkboxes, and
default selected for select (option) elements.
*/
function formChanged(form) {
var control, controls = form.elements;
var tagName, type;
for (var i=0, iLen=controls.length; i<iLen; i++) {
control = controls[i];
tagName = control.tagName.toLowerCase();
type = control.type;
// textarea
if (tagName == 'textarea') {
if (control.value != control.defaultValue) {
return true;
}
// input
} else if (tagName == 'input') {
// text
if (type == 'text') {
if (control.value != control.defaultValue) {
return true;
}
// radio and checkbox
} else if (type == 'radio' || type == 'checkbox') {
if (control.checked != control.defaultChecked) {
return true;
}
}
// select multiple and single
} else if (tagName == 'select') {
var option, options = control.options;
for (var j=0, jLen=options.length; j<jLen; j++) {
option = options[j];
if (option.selected != option.defaultSelected) {
return true;
}
}
}
}
// Not really needed, but some like the return value to
// be a consistent Type
return false;
}
Note that you need to be careful with select elements. For a single select, you should always set one option to selected, as if there is no default selected, some browsers will make the first option selected and others wont.

How to check if radio button in radio button list was selected

Good morning
I am having some difficuly in looping through a radiobutton list in order to check if it was selected or not using Javascript.
With C# Asp.net the procedure is relatively easy but with the Javascript I am struggling a little.
This is the code I use with C# to check if the radion button was selected.
protected void Button1_Click(object sender, EventArgs e)
{
string radValue = RadioButtonList1.SelectedValue.ToString();
if (radValue == "")
{
lblError.Text = "Please select neigbourhood";
}
else
{
lblError.Text = "You come from " + radValue;
}
}
The code I use with javascript is a little faulty and I was hoping it could be corrected.
var radNeighbourhood;
for(var loop=0; loop < document.subscribeForm.myRadio.length; loop++)
{
if(document.subscribeForm.myRadio[loop].checked == true)
{
radNeighbourhood = document.subscribeForm.myRadio[loop].value;
break;
}
else
{
alert("Please select a neigbourhood");
return false;
}
}
return true;
Kind regards
Arian
I made a small sample of what you 're asking here. http://jsfiddle.net/mZhQ9/2/
EDIT: analysis
var radioButtons = document.subscribeForm.myRadio; //it is crucial to store the DOM information in a variable instead of grabbing it, each single time. (DOM operations are EXTREMELY slow)
var len = radioButtons.length; //same as before
var found = false; //our flag - whether something was found or not
while( len-- > 0 ) { //decreasing the counter (length of radio buttons)
if( radioButtons[len].checked === true ) { //if we find one that is checked
found = true; //set the flag to true
break; //escape the loop
}
}
if( found ) { //if our flag is set to true
alert( radioButtons[len].value );
return radioButtons[len].value; //return the value of the checked radiobutton (remember, when we broke from the While-loop, the len value remained at the 'checked' radio button position)
}
else {
alert( "Please select a neigbourhood" );
return false; //else return false
}
EDIT 2: As a sidenote please be careful of using
"for(var loop=0; loop < document.subscribeForm.myRadio.length; loop++)"
DOM operations within a loop. the
loop < document.subscribeForm.myRadio.length condition checks the document and grabs the radio buttons every single time, resulting in lots of unecessary overhead.
You might be looking for something more like:
var radNeighbourhood;
for (var loop=0; loop < document.subscribeForm.myRadio.length; loop++)
{
if (document.subscribeForm.myRadio[loop].checked == true)
{
radNeighbourhood = document.subscribeForm.myRadio[loop].value;
break;
}
}
if (!radNeighbourhood)
{
alert("Please select a neighbourhood");
return false;
}
alert("You come from " + radNeighbourhood);
return true;

select all checkboxes... with javascript and rails

I'm running into some type of error here. Nothing is happening. Does anyone have idea idea why?
Thank you beforehand!
-form_tag :action => 'form', :name =>'admin_form' do
#images_actions_bar
.select_all
=check_box_tag('check_all', 'check_all', false, :onClick => "$$('admin_form input.check').each(function(box){box.checked=true});return false;")
==============
thanks. what ultimately worked for me was a check box like this:
=check_box_tag('check_all', 'check_all', false, :onClick => "checkAll(document.admin_form.check_all, document.admin_form.checkbox);")
and a js function like this:
function checkAll(field_main, fields){
if(field_main.checked == true){
for (i = 0; i < fields.length; i++)
fields[i].checked = true ;
}else{
for (i = 0; i < fields.length; i++)
fields[i].checked = false;
}
It's not clear what javascript framework you're using. I've really only used jQuery and (minimally) Prototype. So, I'd check that admin_form is selecting the form element properly. In jQuery, it would have to be form[name="admin_form"]
I've modified a check/uncheck all jquery piece that I previously wrote. Hopefully it may help. First, clicking "check_all" will check all checkboxes. Clicking a checkbox will then uncheck the "check_all" checkbox.
$('#check_all').click(function() {
var checkboxes = $('form[name="admin_form"] > input:checkbox');
$(checkboxes).each(
function(){
this.checked = $('#check_all').attr('checked');
}
);
});
$('form[name="admin_form"] > input:checkbox').click(function() {
var checkAll = $('#check_all');
if ($(checkAll).is(':checked') && !($(this).is(':checked')))
{ $(checkAll).removeAttr('checked'); }
});
The answer posted in the original question got me started but I ran into problems because my checkboxes are named message_id[]. The brackets were causing JS syntax errors.
Following a pattern in this thread, I got around this by looping through all the input fields on the form and then operating explicitly on the ones with type="checkbox".
This code in my view creates the Check All checkbox (intentionally without a label):
<%= check_box_tag('check_all', 'check_all', false, :onClick => "checkAll(this);") %>
which uses this JavaScript:
function checkAll(check_all){
// Pass in a named "Check All" checkbox that appears on the same form where all
// checkboxes should be checked.
// Loop through an array containing ALL inputs on same form as check_all
var inputs = check_all.form.getElementsByTagName("input");
for (var i = 0; i < inputs.length; i++) {
// Only work on checkboxes, and NOT on the "Check All" checkbox
if (inputs[i].type == "checkbox" && inputs[i].name != check_all.name) {
if(check_all.checked == true){
inputs[i].checked = true ;
}else{
inputs[i].checked = false ;
}
}
}
}
function checkAll(check_all){
// Pass in a named "Check All" checkbox that appears on the same form where all
// checkboxes should be checked.
// Loop through an array containing ALL inputs on same form as check_all
var inputs = check_all.form.getElementsByTagName("input");
for (var i = 0; i < inputs.length; i++) {
// Only work on checkboxes, and NOT on the "Check All" checkbox
if (inputs[i].type == "checkbox" && inputs[i].name != check_all.name) {
inputs[i].checked = check_all.checked ;
}
}
}

Categories