attribute change if the select box not empty - javascript

i am trying to check a value of a select box which filled according to user choice , this select will be populated once the user select options from other select boxes , now in the document.ready() the select is empty , i need to check if this select still empty , then disable a button , else , enable it again .
here is what i tried , it senses that the drop box is empty , but not when its populated !
if ($('#course-selection').html(null)) {
$('#show-wall-button').attr('disbaled','disabled');
}
else {
$('#show-wall-button').removeAttr('disabled');
}
this already fired on document.ready event when the page loads !.
I also tried this , but did not work
if ($('#course-selection').val(null)) {
$('#show-wall-button').attr('disbaled','disabled');
}
else {
$('#show-wall-button').removeAttr('disabled');
}

you can try this:
$('#show-wall-button').prop('disabled', $('#course-selection').is(':empty'))

try like:
if ($('#course-selection').val() === '') {
$('#show-wall-button').prop('disbaled', true);
}
else {
$('#show-wall-button').prop('disabled', false);
}
From the API: http://api.jquery.com/prop/

if ($('#course-selection').val(null))
should be
if ($('#course-selection').val() == '')

What about $('#course-selection option').length instead of the condition you are currently using?
In any case, I sense there may be a better way to do what you want, without having to check whether there are option tags inside the select box.

Checking the contents of the <select> is a bit messy. How about you do something like add an attribute data-populated="false" and set it to true when you populate it. Then you can just check the status of the attribute on the element in your conditions.

go with the suggestion of #Raminson
But in the example disabled is spelt wrong (disbaled) hence it will never removeAttr disabled when populated, coz the attribute which you have assigned is the wrong spelt disbaled

<select id="course-selection">
<option value="">null</option>
<option value="1">option1</option>
</select>
if you want to get selected value:
if($("#course-selection option:selected").val()=="")
$('#show-wall-button').attr('disbaled', true);
else
$('#show-wall-button').removeAttr('disabled');
if you want to get selected text:
if($("#course-selection option:selected").text()=="null")
$('#show-wall-button').attr('disbaled', true);
else
$('#show-wall-button').removeAttr('disabled');

Related

How To Select A Certain Option Field

Jquery is not my main language PHP is.
Anyway,
What I am trying to do is detect if a field has been selected my code almost works but the issue is that when it selects the certain option I get a alert which is good but then when I select the dropdown again [since its being selected] I get another alert which I don't want. What I do want is once the user select the dropdown then clicks the option again I want another alert
$('#_privacy_selection').click(function() {
if($("#_privacy_selection option:selected").text() == 'Certain Users'){
alert(9);
return false;
}
});
Thanks
Instead of click function use change function on <option>
It will be fired only when you change selected option.
$('#_privacy_selection').change(function() {
if($("#_privacy_selection option:selected").text() == 'Certain Users'){
alert(9);
return false;
}
});

set some specific options in multiselect as disabled and selected

I have a multiselect box having some options which i am able to select or disable via jquery, but i am not able to make them do both at the same time. How can i do that via jquery ??
Here's what i was doing - JSFiddle
In this example i am selecting an option on load and after that disabling it, but the option is still de selectable. I want to keep it selected and disabled all the time.
For now i am using click method to keep it selected by adding this line:
$('#multiSelect').click(function()
{$('#multiSelectoption[value="three"]').attr('selected',true);});
EDIT:
People are posting the solution where we select the option again on click, which i already have posted in my question. What i wanted to know is that if there exist some better solution as this one does not look good.
js fiddle:
http://jsfiddle.net/Tf5ZZ/5/
jquery:
//disabling on load:
$('#multiSelect option[value="three"]').prop('disabled', true);
$("#multiSelect option").on('click',function() {
$('#multiSelect option[value="three"]').prop('selected',true);
});
If the point is to prevent the value of the select box from being changed after it's set then you should disable the select box instead of just the option item.
$('#multiSelect option[value="three"]').prop('selected',true);
$('#multiSelect').prop('disabled',true);
See this fiddle for demonstration: http://jsfiddle.net/zKbVm/1/.
Also, the difference between prop() and attr() is that attr() gets/sets the element's attributes (which reflect the inital state of the element) and prop() gets/sets its properties (which represent the current state of the DOM node). See https://stackoverflow.com/questions/5874652/prop-vs-attr for more information.
Here is a small piece of jQuery to solve your problem.
$("#multiSelect option").click(function()
{
$("#multiSelect option[value='three']").prop("selected", true);
});
<select multiple="multiple" size="3">
<option value="1" selected>One</option>
<option value="2" disabled>Two</option>
<option value="3" disabled>Three</option>
</select>
I guess you could handle that in the create event of multiselect which is called after the widget gets created.
Below is the code snippet which I am using in the current application I am working on;
create: function (event, ui) {
$(this).multiselect("widget").find(":checkbox").each(function () {
var checkBoxValue = $(this).val();
// Using linq.js to query the fields and determine whether
// the field is required in my case.
// Replace this if statement with your own logic here
if (Enumerable.From(CHAMP.cache.fields).Count(function (x) {
return x.Id.toString() == checkBoxValue && x.IsRequired == true;
}) > 0) {
$(this).attr("checked", "checked");
$(this).attr("disabled", "disabled");
}
});
}

Resetting Select2 value in dropdown with reset button

What would be the best way to reset the selected item to default? I'm using Select2 library and when using a normal button type="reset", the value in the dropdown doesn't reset.
So when I press my button I want "All" to be shown again.
jQuery
$("#d").select2();
html
<select id="d" name="d">
<option selected disabled>All</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
I'd try something like this:
$(function(){
$("#searchclear").click(function(){
$("#d").select2('val', 'All');
});
});
You can also reset select2 value using
$(function() {
$('#d').select2('data', null)
})
alternately you can pass 'allowClear': true when calling select2 and it will have an X button to reset its value.
version 4.0
$('#d').val('').trigger('change');
This is the correct solution from now on according to deprecated message thrown in debug mode:
"The select2("val") method has been deprecated and will be removed in later Select2 versions. Use $element.val() instead"
According to the latest version (select2 3.4.5) documented here, it would be as simple as:
$("#my_select").select2("val", "");
you can used:
$("#d").val(null).trigger("change");
It's very simple and work right!
If use with reset button:
$('#btnReset').click(function() {
$("#d").val(null).trigger("change");
});
The best way of doing it is:
$('#e1.select2-offscreen').empty(); //#e1 : select 2 ID
$('#e1').append(new Option()); // to add the placeholder and the allow clear
I see three issues:
The display of the Select2 control is not refreshed when its value is changed due to a form reset.
The "All" option does not have a value attribute.
The "All" option is disabled.
First, I recommend that you use the setTimeout function to ensure that code is executed after the form reset is complete.
You could execute code when the button is clicked:
$('#searchclear').click(function() {
setTimeout(function() {
// Code goes here.
}, 0);
});
Or when the form is reset:
$('form').on('reset', function() {
setTimeout(function() {
// Code goes here.
}, 0);
});
As for what code to use:
Since the "All" option is disabled, the form reset does not make it the selected value. Therefore, you must explicitly set it to be the selected value. The way to do that is with the Select2 "val" function. And since the "All" option does not have a value attribute, its value is the same as its text, which is "All". Therefore, you should use the code given by thtsigma in the selected answer:
$("#d").select2('val', 'All');
If the attribute value="" were to be added to the "All" option, then you could use the code given by Daniel Dener:
$("#d").select2('val', '');
If the "All" option was not disabled, then you would just have to force the Select2 to refresh, in which case you could use:
$('#d').change();
Note: The following code by Lenart is a way to clear the selection, but it does not cause the "All" option to be selected:
$('#d').select2('data', null)
If you have a populated select widget, for example:
<select>
<option value="1">one</option>
<option value="2" selected="selected">two</option>
<option value="3">three</option>
...
you will want to convince select2 to restore the originally selected value on reset, similar to how a native form works. To achieve this, first reset the native form and then update select2:
$('button[type="reset"]').click(function(event) {
// Make sure we reset the native form first
event.preventDefault();
$(this).closest('form').get(0).reset();
// And then update select2 to match
$('#d').select2('val', $('#d').find(':selected').val());
}
Just to that :)
$('#form-edit').trigger("reset");
$('#form-edit').find('select').each(function(){
$(this).change();
});
What I found works well is as follows:
if you have a placeholder option like 'All' or '-Select-' and its the first option and that's that you want to set the value to when you 'reset' you can use
$('#id').select2('val',0);
0 is essentially the option that you want to set it to on reset. If you want to set it to the last option then get the length of options and set it that length - 1. Basically use the index of whatever option you want to set the select2 value to on reset.
If you don't have a placeholder and just want no text to appear in the field use:
$('#id').select2('val','');
To achieve a generic solution, why not do this:
$(':reset').live('click', function(){
var $r = $(this);
setTimeout(function(){
$r.closest('form').find('.select2-offscreen').trigger('change');
}, 10);
});
This way:
You'll not have to make a new logic for each select2 on your application.
And, you don't have to know the default value (which, by the way, does not have to be "" or even the first option)
Finally, setting the value to :selected would not always achieve a true reset, since the current selected might well have been set programmatically on the client, whereas the default action of the form select is to return input element values to the server-sent ones.
EDIT:
Alternatively, considering the deprecated status of live, we could replace the first line with this:
$('form:has(:reset)').on('click', ':reset', function(){
or better still:
$('form:has(:reset)').on('reset', function(){
PS: I personally feel that resetting on reset, as well as triggering blur and focus events attached to the original select, are some of the most conspicuous "missing" features in select2!
Select2 uses a specific CSS class, so an easy way to reset it is:
$('.select2-container').select2('val', '');
And you have the advantage of if you have multiple Select2 at the same form, all them will be reseted with this single command.
Sometimes I want to reset Select2 but I can't without change() method. So my solution is :
function resetSelect2Wrapper(el, value){
$(el).val(value);
$(el).select2({
minimumResultsForSearch: -1,
language: "fr"
});
}
Using :
resetSelect2Wrapper("#mySelectId", "myValue");
For me it works only with any of these solutions
$(this).select2('val', null);
or
$(this).select2('val', '');
// Store default values
$('#filter_form [data-plugin="select2"]').each(function(i, el){
$(el).data("seldefault", $(el).find(":selected").val());
});
// Reset button action
$('#formresetbtn').on('click', function() {
$('#filter_form [data-plugin="select2"]').each(function(i, el){
$(el).val($(el).data("seldefault")).trigger('change');
});
});
If you want to reset forms in edit pages, you can add this button to forms
<button type="reset" class="btn btn-default" onclick="resetForm()">Reset</button>
and write your JS code like this:
function resetForm() {
setTimeout(function() {
$('.js-select2').each(function () {
$(this).change();
/* or use two lines below instead */
// var oldVal = $(this).val();
// $(this).select2({'val': oldVal});
});
}, 100);
}
Lots of great answers, but with the newest version none worked for me. If you want a generic solution for all select2 this is working perfectly.
Version 4.0.13 tested
$(document).ready(function() {
$('form').on('reset', function(){
console.log('triggered reset');
const $r = $(this);
setTimeout(function(){
$r.closest('form').find('.select2-hidden-accessible').trigger('change');
}, 10);
});
});
$(function(){
$("#btnReset").click(function(){
$("#d").select2({
val: "",
});
});
});
to remove all option value
$("#id").empty();

jQuery serialize remove empty Select

I have a big form, that will be serialized by a jQuery function.
The problem is that I need to remove from this form before being serialized all the empty values.
I found a way to successfully remove all the empty input text fields, but not the selections.
It does not work properly with select dropdowns.
Ceck below:
echo "<script type=\"text/javascript\">
$(document).ready(function() {
$('#submForm').validate({
submitHandler: function(form) {
// Do cleanup first
$('input:text[value=\"\"]', '#submForm').remove();
$('select option:empty', '#submForm').remove();
var serialized = $('#submForm').serialize();
$.get('".$moduleURL."classes/DO_submission.php', serialized);
window.setTimeout('location.reload()', 8000);
return false;
form.submit();
}
})
});
It should completely remove the dropdown selections where the values are empty. Not only the options but the entire select box should not be included in the serialize function.
How do I achieve this?
$('select option:empty', '#submForm').remove();
This code is not working as it should..
First, a select can not have an empty value. It will default to the first option if the selected attribute is not set.
Second, $('select option:empty') selects the empty options. To do something, an option should have a value, so afaik the selector will never work.
What you need to do is check all selects to see if they have a different value than their default, and if it is not the case, remove them.
If with 'empty select' you mean that the user has not chosen a 'valid' option (for example the fist option of a select is <option value=''>Select your value</option> )why don't you iterate on the select and check their value?
$('select').each(function(){
if ($(this).val() === ''){//this assumes that your empty value is ''
$(this).remove();
}
});
EDIT - sorry for the error, i missed the last parenthesis, i tried it and it works for me
I would just instead of serlizing the the whole form I would use jquery Form and then all you have to do is call
$('#submForm').ajaxSubmit({/.../});
Try
$('select option:selected:empty').parent().remove();
Edited after reading Nicola's comment.

Select the same option multiple times / onchange without changing

I have a select, and I need to fire some js each time an option is selected, even if it is already selected.
Example:
<select id="select_one">
<option value="">Choose One...</option
<option value="one">One</option>
<option value="two">Two</option>
</select>
If someone selects "one" I want to fire functionOne(). But, while "one" is selected, if the user selects "one" again I want to fire functionOne() again. So, that means onChange won't work, since the selection isn't changing.
Anyone have any thoughts?
Contrary to some of the current answers, you don't actually get a click event on <option> in IE.
The only reliable way to detect the case of an option being clicked that was already selected is to put the onclick handler on the <select>. Naturally this will also detect any other clicks on the select element, so depending on what functionOne() is doing this may not be safe either.
You might be better off with something that looks like a select but isn't, such as a pop-up div with buttons on it. What is it you are trying to do? If you're trying to do a “jump menu” where selecting an option navigates to a new page: don't, it's an old and discredited mechanism with serious usability problems.
add onClick to the <option> tag
after firing the onSelect, change the select value to "Add Another"?
eg. forst option has an id of #selectBox, value of '' and a html of "Select One".
onChange, retrieve the value $('#selectBox').val(); and turn around after your actions and go $('#selectBox').val('').html('Select Another');
Add an onclick even to each option tag. Inside the function do:
function() {
var timesClicked = $(this).attr('times-clicked') || 0;
$(this).attr('times-clicked', ++timesClicked);
if (timesClicked == 1) {
functionONe();
}
else if (timesClicked == 2) {
functionTwo(); // and so on
}
}

Categories

Resources