jQuery not function dependency on the value of another control - javascript

I have the following code:
$(serialNumbersDDL).children("option:gt(0)").remove();
It will delete all the options except the first one. Now I need to delete all the options except the first one and also not delete the option whose value is equal to the label text. How can I say that with writing limited amount of code?

try
$("option:not(':first')",serialNumbersDDL).filter(function(){
return $(this).val()!=$(this).text();
}).remove();

I'd try
$(serialNumbersDDL).children("option:gt(0)").not(function(){
return $(this.labels).text() == this.value;
}).remove();

Related

Adding "values" to a texfield in jquery/js

When writing a new email, I've got a modal(pop-up window in boostrap) that shows a list of contacts. When I select (through checkboxes) a couple of contacts, the selected ones are written into a checkbox. Problem is I'm just writing the lastone I select instead of all of the selected ones.
If you need further explanation please ask. (Sorry for my english)
$("#tblContacto").on("click", ".ck", function(event){
if($(".ck").is(':checked')) {
selected_index = parseInt($(this).attr("alt").replace("Check", ""));
var contacto = JSON.parse(tbContactos[selected_index]);
$("#txtDestinatarios").val(contacto.Email);
} else {
$("#txtDestinatarios").val("");
}
});
Assuming that you want to add all E-Mails into a textfield with id txtDestinatariosthe cause of your Problem is the usage of the $("#txtDestinatarios").val(); function.
Calling val() with an argument sets (and thus overwrites) the value within the textfield. (See demo at http://api.jquery.com/val/#val2)
You would have to first retrieve the value of the textfield using code like var currentValue = $("#txtDestinatarios").val() and then add/remove the E-Mail from/to the string before setting the resulting string back as the value.
If you want to set all selected items in the checkboxes into Textfiled you can use the following line of code :-
$("#txtDestinatarios").val( $("#txtDestinatarios").val()+ ","+contacto.Email);

Remove all "-" inside select options

I have in wordpress a list of options, but it generates with sub level menu's automatic a - before it. Now I wanna loop them out but can't get it seems to work.
I targeted my menu items and try to loop out the "-" to remove them.
var $menuitem = $(".hasCustomSelect .menu-item");
$menuitem.filter(function(){
return $.trim($(this).text()) == '-'
}).remove();
small codepen
http://codepen.io/denniswegereef/pen/NGGrgR
If I understand correctly. The problem is you are trying to match the wrong kind of dash - vs —. Try this instead return $.trim($(this).text()) == '—';
http://codepen.io/anon/pen/vNLZyv
I can see a - vs a —, Try copy paste from the codepen or from below code
Also I guess you want to use
var $menuitem = $(".hasCustomSelect .menu-item");
$menuitem.filter(function(){
return $.trim($(this).text()).indexOf('—')>-1;//all values containing `—`
}).remove();
Or if you really want to delete only the single - than
return $.trim($(this).text())=='—'; //the value that is `—`
Updated Code Pen http://codepen.io/anon/pen/wKMeJv
If removing the separator options, is what you wanted, then imtheman has a solution for you.
If you wanted to remove the leading dashes from the menu captions (my first guess on what you need), then you can go with the snippet below:
var $menuitem = $(".hasCustomSelect .menu-item");
$.each($menuitem, function(key, val){
$(val).text($(val).text().replace(/—+ /,''));
});

How to select empty inputs (value="") using jQuery

How can I check for empty values of (required) input fields within a section, and then add a class to them on an event, using jQuery? So far, I have tried:
jQuery("#sender_container input.required").val("").addClass("error");
But that seems to SET the value, rather than checking it. Any ideas?
jQuery("#sender_container input.required").filter(function() {
return !this.value;
}).addClass("error");​
Why you have to use filter and not [value=""] you can see in this DEMO
The reason is: attribute selectors check the initial state of the element, not the current state. (note that you can change the "initial" state with the attr function, but it's bad practice, you should always use prop)
So if you change the input value, the current value won't effect the attribute selector. not wise... :)
Notes:
.val() returns the value of the form element, and breaks the jQuery chain,
$('selector').val().addClass('foo') Error, the return value is a string\ number
.val(valueToSet) sets the value of the form element and doesn't break the jQuery chain.
$('selector').val("some value").addClass('foo') - Valid, the returned value is a jQuery
$('input:text[value=]','#sender_container').addClass('error');
DEMO
$('#sender_container input.required[value=""]').addClass('error')
jQuery('#sender_container input.required[value=""]').addClass("error");
You can try this:
$('input:not([value!=""])').addClass('error');
DEMO
Note: This answer should not be used, and the only reason it wasn't deleted is so it can be learned from.
$field = $("#sender_container input.required");
if( ! $field.val())
{
$field.addClass("error");
}
this simple way may work.
If you only need to select based on the initial attribute value of the input then the following will do:
var elements = $('#sender_container input.required[value=""]')
But be aware that this won't work if the value attribute isn't present. It also won't work for the current input value if it has been changed by user or script.
If you'd like to get the current input value you can use jquery's filter function:
var elements = $('#sender_container input.required').filter(function() {
return this.value === '';
// alternatively for "no value":
// return !this.value;
})
After you've selected the jquery elements you can add your class:
elements.addClass('error');
to get all fields inspected this might help.
$('#sender_container [required]').each(function(index)
{
if (!($(this).val())) $(this).addClass('error');
}
});

Access element of Mootools array

I'm using a bit of Mootools to access the values of an HTML select element but the thing is that the way to do it with Mootools [.getSelected()] returns an array and I don't know how to handle it.
my code :
<script type="text/javascript">
window.addEvent('domready', function(){
$('votconj').addEvent('click', function() {
// This works great
$('jj_conjoint').addClass("validate['required']");
$('mm_conjoint').addClass("validate['required']");
$('aaaa_conjoint').addClass("validate['required']");
$('conjoint_regime').addClass("validate['required']");
new FormCheck('form');
});
if ($('nb_children').getSelected() == 1){
// this doesn't work because .getSelected() returns an array and never equals 1
$('jj_enfant1').addClass("validate['required']");
$('mm_enfant1').addClass("validate['required']");
$('aaaa_enfant1').addClass("validate['required']");
new FormCheck('form');
}
if ($('nb_children').getSelected() == 2){
// this doesn't work because .getSelected() returns an array and never equals 2
$('jj_enfant2').addClass("validate['required']");
$('mm_enfant2').addClass("validate['required']");
$('aaaa_enfant2').addClass("validate['required']");
new FormCheck('form');
}
new FormCheck('form');
});
</script>
getSelected() returns an array because some select elements allow multiple selection. If yours doesn't, you could just try $('nb_children').getSelected()[0]. To get the value you can use $('nb_children').getSelected()[0].get("value").
You can use .each to traverse an array in MooTools:
var selected = $('nb_children').getSelected();
selected.each(function(element) {
var val = element.get('value');
$('jj_enfant' + val).addClass("validate['required']");
//etc
}
new FormCheck('form');
For more info: http://mootools.net/docs/core/Types/Array#Array:each
The reason why getSelected() returns an array at all times, is that code like this can always be reused when you decide to add multiple selectable items instead of just one.
Edit
Note that the above code is directly written. Might need some tweaking to get it working for your case.
Edit 2
Updated code to a more comprehensive example.
You want to check the value of the selected item, right?
Try with:
if ($('nb_children').getSelected().get('value') == 1){//...

Selecting from a list of previously selected elements via jQuery

I'm having a bit of a brain fart here, and hoping someone can help me find a 1-line solution to this problem, without having to call .each().
So I get a list of all checkboxes within a container like this:
var checkboxes = $(':checkbox', '#surveyModal');
At some point later, I need to find out if any (or none) of the checkboxes are checked within that list.
I expected something like these to work:
$(':checked', checkboxes)
// or
checkboxes.attr(':checked')
// or
$(checkboxes).attr(':checked')
But it doesn't. The only thing I've had success with is calling each() and then checking each individually. But that means I'll have to keep a separate variable (.e.g. someAreChecked at a higher-level scope, which I don't feel is optimal.
checkboxes.each(function () {
if ($(this).attr('checked')) {
someAreChecked = true;
}
});
I was hoping that I can easily in a single line do such a check:
if (checkboxes.('get checked count') == 0)
{
}
Thanks in advance.
The filter function is what you're looking for :)
checkboxes.filter(':checked').length;
.attr returns the value of an attribute, and you have to pass the attribute's name to it, not a selector.
Just use .is instead.
Description: Check the current matched set of elements against a
selector, element, or jQuery object and return true if at least one of
these elements matches the given arguments.
$(checkboxes).is(':checked')
This should do it:
$("input[type=checkbox][checked]").length

Categories

Resources