So this question is asked a lot on the net and I see the answer is to check if the .length is > 0.
So in my case a select box may or may not exist. If it exists, it may have no options.
I have to code for the following:
If selectbox exists ...
if there are no select box options ...
disable a text area
I have therefore written the following:
$(document).ready(function () {
"use strict";
alert('running globals');
// Only process this block if the contactEmailAddress select box exists
if ($('contactEmailAddress').length > 0) {
alert('on the comm page');
// If there are no contacts ...
if ($('#contactEmailAddress option').size() === 0) {
alert('disabling the message box');
$('#message').attr("disabled", "disabled");
}
}
});
The problem is, because the select box has no options, it's decided the selectbox.length is 0. So this block never fires.
I need another way.
You're missing the "ID selector" from the first $, instead searching for elements named contactEmailAddress, rather than elements with an ID of contactEmailAddress.
if ($('#contactEmailAddress').length > 0) {
Note you can just do $('#contactEmailAddress option').size() directly without worrying if the select exists or not; no exception or error will be thrown.
You can determine an element exist with using pure javascript.
if( document.getElementById("contactEmailAdress") )
or
if( document.getElementsByClassName("option")[0] )
Related
I am working on a module, which should select the only possible value of a Multi- or Single selection field, if there is only one valid value and a empty one available.
So far its working fine, until I use ACLs to disable selection values.
For example, I got a single selection field with 3 possible values. Then I disable 2 of them (ACL - if there is a special Queue selected) so theres only one value (+ an empty one) left.
My module wont pick the last value at first, but when I change anything else on the same page (second onchange call) it will pick the last possible value.
The first if condition checks if the Field has only one possible value in it. When I log the 'Change' array it always got the disbaled values still in there even when the 'change' that called the whole function was the ACL disabling those values.
Im still kinda new to javascript and havent found a solution yet.
I would realy appreciate any help.
$('.TableLike').on("change", function () {
var Change = [];
$('.Row').each( function() {
$(this).children().next().children().next().children().each( function(index) {
Change[index] = $(this).text()
} )
if ( (!Change[2] || /.*Field needed.*/i.test(Change[2])) && Change[0] === "-") {
SoleOption = Change[1];
$(this).children().next().children().next().children().each(function() {
if ($(this).text() === "-") {
$(this).removeAttr("selected");
}
if ($(this).text() === SoleOption) {
$(this).attr("selected", "selected");
}
} )
$(this).children().next().children().children().children().val(SoleOption)
}
SoleOption = "";
Change = [];
} )
} )
I managed to fix the issue with the setTimeout() Method.
So the DOM updated before the ACL did the changes.
I opened up the setTimeout Method after the onChange method and inserted all the code thats supposed to run after the change into the setTimeout method.
I hope this will be helpfull for others in the future.
So, I'm trying to make sure a button is disabled to prevent a user from saving data from form field entries whenever two conditions are met:
The checkbox is checked
There's nothing inside the form field in question ( #read_return_response_rate_ids )
This is what I have to that end:
$('body').on("change","#tab3 #read_return_response_rate_ids", function(){
if ($(this).is('')) && ($('input:checkbox').is(':checked')) {
$('.create_read_btn').attr('disabled', 'disabled');
} else {
$('.create_read_btn').removeAttr('disabled');
}
});
The error it's giving me in the console is totally useless towards debugging purposes.
Uncaught SyntaxError: Unexpected token /
It's my thought that this is where the problem exists:
if ($(this).is('')) && ($('input:checkbox').is(':checked'))
Basically, I don't think I can have multiple selectors as I have them structured, but I don't know. Does anyone have any thoughts on why this is returning an error? I confirmed that this code block is where the error originates by selectively commenting out other blocks of code and whittling it down to this one.
There are syntax errors (parenthesis chars note required):
Change:
if ($(this).is('')) && ($('input:checkbox').is(':checked')) {
by
if ($(this).is('') && $('input:checkbox').is(':checked')) {
The argument to .is() must be a selector or jQuery collection; it tests whether the specified element matches the selector or is the same set of objects. If you want to test whether an input field is empty, you need to use .val() to get the value.
if ($(this).val() == '' && $('input:checkbox').is(':checked')) {
When I check inputFieldDomNode.selectionStart it always returns some number, even if it does not have a text selection and there's no caret in it. So how can I tell if it doesn't have a text selection?
At least window-globally, you can use Selection.isCollapsed
window.getSelection().isCollapsed
Despite the compatibility table, I have found it to be working in Chrome, and apparently it's been supported since IE 9 as well.
You can check if a element is selected with something like:
document.getElementById("color-red").checked
which will return a boolean.
If that's what you want, check out an example at http://jsfiddle.net/o5t0ow9g/1/
I think (but am not 100% sure) that if the element is not the active element for the document, it can't have a text selection. You can test it using document.activeElement:
if (inputFieldDomNode == document.activeElement) {
// Do stuff with the selection
}
Example: http://jsfiddle.net/hpseuLj3/1/
Ok I figured it out:
exports.getSelectionRange = function (element) {
if(element.nodeName === 'INPUT' || element.nodeName === 'TEXTAREA') {
var selection = window.getSelection()
for(var n=0; n<selection.rangeCount; n++) {
var range = selection.getRangeAt(0)
if(range.startOffset === range.endOffset && range.startContainer.children[range.startOffset] === element /*|| range.startContainer === element || */) { // I don't think the input or textarea itself will ever be the startContainer
return [element.selectionStart, element.selectionEnd]
}
}
// else return undefined - the element doesn't have an active caret or active selection (it still may have an inactive selection)
} else {
// .. do something else unrelated to this question
}
}
Basically, when you have an active text input, its parent is the range.startContainer and so you have to not only check that it is a child of range.startContaine but make sure that its the right child (the child that's selected) which is determined by the range.startOffset. Also, you have to make sure that input is the only thing that's selected, because its possible for the input to be included in a larger selection.
Note: I think this might still fail in cases where the actual input node is the only thing selected and not its contents. This is an incredibly rare edge case and i'm not sure if its even possible via user input (tho probably possible via the dom API).
I have a form where the user can 1.) check one option and be done. or 2.) check the other option and fill out a text field.
Whole thing is, after all is said and done I'd like for my alert to show, but it doesn't.
$('.know-your-role').show('fast', function() {
var $checkboxes = $('input:checkbox.checkchoice');
if($checkboxes.is(':checked')){
// show this after checked and the input has been filled.
alert('cool');
}else if($checkboxes.is(':checked') & $(".year").va() != "" ){
alert('cool');
}
});
How do I get the alert to show after all requirements (checkboxes and input) have been met?
I've made a fiddle here to show what I'm working with.
Thank you for your help in advance.
As well as the previous correct answers (missing & and misspelled val) there is a more fundamental logical issue here. You seem to have this structure:
if (conditionA) {
// behaviorA
} else if (conditionA && conditionB) {
// behaviorB
}
You will never reach behaviorB with such logic. If conditionA fails then conditionA && conditionB will certainly also fail.
Do you need to reverse the order of your if and else-if blocks?
Missing '&'
$checkboxes.is(':checked') && $(".year").val() != ""
You should use && instead of & for boolean comparisons, and also you appear to have mis-typed val as va.
I would suggest having two events, one on the 'Teacher' check box being checked and one on the year field being completed. Both events can trigger a single function that shows your alert and whatever other logic you want. So there is little duplication.
This helps to separate the events from the logic that shows/hides the year field and more easily allows you to perform different actions for the two events if that's a requirement.
I have a select box that is being populated dynamically from a database. As of right now the population of this check box is working flawlessly.
I have added functionality that consists of a button which on click calls isSelextBoxEmpty. The job of this function is to know whether this particular check box has been populated or not; if it has not then it will simply do nothing.
My problem is in determining whether this select box is empty or not.
Here is a very simplified example of what I am dealing with:
<li>
<label for="fruit_name">Fruit</label>
<select name="some_fruit" id="fruit_name" onclick="populate_box('fruit', this);">
</select>
</li>
My function, which is called from a separate button, looks like this:
function isSelextBoxEmpty(selectBoxId) {
var selected_value = $('#fruit_name');
/* More options... still testing the proper way:
var selected_value = $('#fruit_name').text;
var selected_value = $('#fruit_name').value;
var selected_value = $('#fruit_name').length;
var selected_value = $('#fruit_name option:selected', this);
var selected_value = document.getElementById('fruit_name');
var selected_value = document.getElementById('fruit_name').length;
var selected_value = document.getElementById('fruit_name').value;
var selected_value = document.getElementById('fruit_name').innerHTML;
*/
if (selected_value) {
alert("NOT null, value: " + selected_value);
// do something
}
}
Don't worry about what this does and how it does it. Right now what matters to me is that I can't check whether or not the checkbox is empty, I am just not sure how to go about it. I have read a lot through forums and documentation but there are many implications in doing this since it depends on the implementation itself.
For instance using document.getElementById(...)... will not necessarily return false and it depends on how you use it. Also using $("#someID")... in jQuery may or may not produce the desired results. I have already tried many different times as you can see in the commented lines, all of which can be evaluated in the if(...) statement.
How can this be done?
To check whether select box has any values:
if( $('#fruit_name').has('option').length > 0 ) {
To check whether selected value is empty:
if( !$('#fruit_name').val() ) {
One correct way to get selected value would be
var selected_value = $('#fruit_name').val()
And then you should do
if(selected_value) { ... }
Another correct way to get selected value would be using this selector:
$("option[value="0"]:selected")
Best for you!
Check this answer its tested and working well
if( !$('#id').val() ) {
// stuff here
}