jQuery serialize remove empty Select - javascript

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.

Related

Selection from dropdownlist javascript event

I have this html part code :
<p><label>Taxe </label>
<select id="id_taxe" name="id_taxe" style="width: 100px;" onchange="taxselection(this);"></select>
<input id="taxe" name="taxe" class="fiche" width="150px" readonly="readonly" />%
</p>
Javascript method :
function taxselection(cat)
{
var tax = cat.value;
alert(tax);
$("#taxe").val(tax);
}
I'd like to set the value of taxe input to the selected value from the dropdownlist.It works fine only where the dropdownlist contains more than one element.
I try onselect instead of onchange but I get the same problem.
So How can I fix this issue when the list contains only one element?
This works:
$('#id_taxe').change(function(){
var thisVal = $(this).val();
var curVal = $('#taxe').val();
if(thisVal != curVal)
$('#taxe').val(thisVal);
$('#select option:selected').removeAttr('selected');
$(this).attr('selected','selected');
});
Use the change method which is very efficient for select boxes. Simply check the item selected isn't currently selected then if not, set the value of the input to the selected value. Lastly you want to remove any option's attr's that are "selected=selected" and set the current one to selected.
Just include this inside a $(document).ready() wrapper at the end of your HTML and the change event will be anchored to the select field.
Hope this helps.
http://jsbin.com/populo
Either always give an empty option, or in your code that outputs the select, check the amount of options, and set the input value straight away if there's only 1 option.
A select with just 1 option has no events, since the option will be selected by default, so there's no changes, and no events.
As DrunkWolf mentioned add an empty option always or you can try onblur or onclick event instead, depending on what you are actually trying to do.
Ok, just to stay close to your code, do it like this: http://jsfiddle.net/z2uao1un/1/
function taxselection(cat) {
var tax = cat.value;
alert(tax);
$("#taxe").val(tax);
}
taxselection(document.getElementById('id_taxe'));
This will call the function onload and get value of the element. You can additionally add an onchange eventhandler to the element. I highly recommend not doing that in the HTML! Good luck.

Use jQuery to set select box value to first option

I am dynamically populating a select box with options. When I do this, I want the value of the select box to be the value of the first option (a 'default option', if you like). Sounds really simple, but I just can't get it to work.
var myElement = $('select[name="myName"]');
.... tried the following three variations
// myElement.find('option').first().prop('selected', 'selected');
// myElement.val(myElement.find('options').first().val());
myElement.prop('selectedIndex', 0);
...but the following line gives a blank alert
alert(myElement.val());
Where am I going wrong?
options should be option
myElement.find('option:eq(0)').prop('selected', true);
You can use the eq selector on the option to select the first option.
If you know the value of the first option. Then you could simply do
myElemeent.val('first value') // Which selects the option by default
The 2nd case you tried should work, unless you are not calling at the right point . i.e; waiting for the ajax response to be completed.
Try calling that inside the done or the success (deprecated) handler
You almost got it, drop the 's' in 'options':
myElement.val(myElement.find('option').first().val());
Working jsFiddle
You could also use next code:
myElement[0].selectedIndex = 0;
This get's the Dom element (not jQuery object), works with vanilla Javascript and uses it to set the first option as the selected one based on it's index.
If you want to be sure that your option has a value and is not a placeholder you can do:
$('select option').filter( function (index, option) {
return option.attributes.value
}).val()
That way you'll check if the HTML node has attribute value and is not empty.

unexpected behaviour in option tag in HTML

I have the following code
<select id="part">
<option>noun</option>
<option>verb</option>
<option>adjective</option>
</select>
In the above code, I don't have any value attribute each option tag.
there is only text node.
when I access the option tag
$("#part").val(); I get what is selected in dropdown box. ie, "noun"
but when I access $("#part").text(), there is empty string.
but when I create, option tags dynamically in jquery for
<select id="part"></select>
using
var names=["noun","adjective","verb"];
for (var i =0;i<names.length;i++) {
var option=$("<option>",{
value:names[i],
text:names[i]});
$("#part").append(option);
}
Here the value is attribute is needed to get the option selected.
without value attribute, $("#part") is undefined.
can somebody explain the discrepancy here? of if my understanding is not correct. Thanks
Check here DEMO http://jsfiddle.net/yeyene/yH4Fb/
You need to get only the selected option text coz there are three options,
when you get $("#part").val(); you directly get the selected value (only one selected value). But when you get $("#part").text().. you are getting the text of the whole select text where you have three options and three types of text.
JQUERY
$(document).ready(function(){
var names=["noun","adjective","verb"];
for (var i =0;i<names.length;i++) {
var option=$("<option>",{
value:names[i],
text:names[i]});
$("#part").append(option);
}
$("#part").on('change', function() {
alert('Value is '+$(this).val());
var text = $("#part option:selected").text();
alert('Text is '+text);
});
});
$("#part").text() doesn't return nothing but it won't return what you expect (see this fiddle).
Explanation: text returns the text of the object strips out the html (see jQuery docs examples), so what you will be getting is the inner contents of the select after the html was stripped out.
If you want the text of the selected value, include the selected option in your jquery selector: i.e. $('#part option:selected').text() which uses the jQuery psuedo-selector (also in my fiddle).

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();

attribute change if the select box not empty

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');

Categories

Resources