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
}
Related
I added this inside Demo.prototype._handleSortChange to reverse the sort order if the radio is checked...
var order = true;
function reverseOrder() {
if (document.getElementById('order').checked) {
order = true;
} else {
order = false;
}
console.log('reverseOrder: '+order);
}
reverseOrder();
What I can't figure out is to call the sorting function when you check or uncheck the radio input without having to re-select the sort order dropdown.
Demo.prototype.reverseSorting = function () {
// this call resets the sort order to default, rather than just reversing the selected order...
document.getElementById('order').addEventListener('click', this._handleSortChange.bind(this));
};
Codepen https://codepen.io/midaspider/pen/ZEBwBqw
Solved it. I was looking at the wrong section as being the problem, the solution was very simple really.
Demo.prototype._handleSortChange = function (event) {
//var value = event.target.value;
var value = document.querySelector('.sort-options').value;
I realised the value of the select input wasn't being passed if I clicked the checkbox, so I changed var value to explicitly get the value from the select input rather than get the value passed from event. Now it works, I've updated the Codepen for reference in case anyone else needs this.
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.
I'm building a preference list where the user selects a number of items from a list and they're then presented back to them in order of preference.
I've a prototype built, but I need some help with a feature I'd like to add. I want the user to see what preference the next item they select will be.
The behaviour would be:
First the user is presented with "Choose your 1st preference"
When they select their 1st preference this then changes to "Choose your 2nd preference, and so on.
It'd also need to know if they'd deselected a preference and on doing so it'd need to say "Choose your 1st preference (or whatever preference)" again.
I've created a JSfiddle here
I'm imagining to be able to use grep in some way to do this?
var nextPreference = $.grep(preferencesAsText, function(v) {
// return v !== First preference that isn't one of the preferences that are already selected
});
Any help would be great, thanks!
Edit: I've managed to get an array of the items that are in the list of chosen preferences by doing this:
var chosenPreferences = $('[data-schemeorder]').map(function() {
return $( this ).text();
})
.get();
var arrayOfChosen = $.makeArray(chosenPreferences);
console.log(arrayOfChosen);
So basically I just need a way of finding the first preference that isn't in this list, if that makes sense... updated fiddle
Why don't you use schemePrefArray.length to get the number of elements selected and display the text you need?
the text displayed would be preferencesAsText[schemePrefArray.length]
no?
OK, so I think I've figured this one out. If you create an array of the chosen preferences and then use grep to create an array of the items that aren't in the preferences text, you can then use this to find the first item that is not selected.
var chosenPreferences = $('[data-schemeorder]').map(function() {
return $( this ).text();
})
.get();
var arrayOfChosen = $.makeArray(chosenPreferences);
var differenceArray = [],
initialVal = 0;
$.grep(preferencesAsText, function(el) {
if($.inArray(el, arrayOfChosen) == -1) differenceArray.push(el);
initialVal++;
})
if(differenceArray[0] === undefined) {
$('#chosenLimit').show();
$('#chooseYourPrefs').hide();
} else {
$('#chosenLimit').hide();
$('#chooseYourPrefs').show();
$('#chooseNextPreference').text(differenceArray[0]);
}
And an updated fiddle here
I have two dropdowns. When selecting a value from the first (bron) I want to select an entry from the second.
This is fired from the onChange of the first dropdown.
function DepId() {
var bron = document.getElementById("IDUserDepartment");
var doel = document.getElementById("IDDepartment");
var bronwaarde = bron.options[bron.selectedIndex].value;
for ( var i = 0; i < doel.options.length; i++ ) {
var doelwaarde = doel.options[i].value;
if ( doelwaarde == bronwaarde ) {
doel.options[i].selected = true;
return;
}
}
}
But this does not work.
EDIT: for whatever reason, I never get a match. When I hardcode any of the values, and then do: doel.options[hardcodedvalue].selected=true, the option is selected. When I test for window.alert(doelwaarde) inside the loop, this always returns zero.
Any suggestions?
Your code should work, I see nothing wrong with it. If I may make three suggestions:
You might want to use jQuery: simpler code, better multi-browser support.
Use console.log instead of a window alert for debugging purposes: less intrusive, won't interrupt your testing (have a look at the developer console of your browser).
You might want to use English names for your variables, controls, etc. More developers will be able to read it, besides English is often shorter than Dutch ;)
I need to get the values of all checkboxes that are currently checked using jquery, I suppose I would put it all in an array, but I am having trouble doing that. Would anyone be able to point me in the write direction.
This is what I am using so far. I am trying to send all of the values that are currently checked to a div I have.
function cityPopulate() {
var arr44 = new Array();
var cityNames22 = $("input[name=city_select[]]:checked").each(function(){arr44.push(this.value);});
$("#city_pop").append(cityNames22.val());
}
When I try the code above, it just gives me the value of the first checkbox I check only. Not all of the rest.
Without seeing the code you have I'm guessing at your exact schema, but using map() on your checkboxes with the class you specify to create an array should work, try this:
var checkboxValues = $('.myCheckbox:checked').map(function() {
return $(this).val();
}).get();
checkboxValues would then contain an array with all the values of the checked checkboxes.
Depending on the class you have assigned to your checkboxes, it will look something like this:
var values = [];
$('.checkboxclass').each(function(){
var $this = $(this);
if ($this.is(':checked')) {
values.push($this.val());
}
});