How to bind multiple pair of selector:event in jQuery ON method - jquery-selectors

I m using jQuery 1.7+ latest .on method, but failed to implements, please help me.
working Fiddle.
basically here is my
HTML
<ul id="sortByRight" >
<li id="1">List</li>
<li id="2">Photo</li>
<li id="3">Map</li>
</ul>
<select name="sort" id="sort" >
<option value="1">Recommended</option>
<option value="2">Price: low to high</option>
<option value="3">Price: high to low </option>
<option value="4">Newest</option>
</select>
jQuery code
$(document).on('change click', 'ul#sortByRight,select#sort', function() {
selectedOption = $('select#sort').val();
whatToShow = $(this).attr('id');
alert('selectedOption:'+selectedOption+'whatToShow:'+whatToShow);
}
);
now I havebelow problems/queries.
can we bind one event with one selector i.e. above function should be called
EITHER on change of selectbox OR on click of ul.
how to set data argument in .on method. I have tried like below
$(document).on('change click', 'ul#sortByRight,select#sort',
{ selectedOption : $('select#sort').val(), whatToShow : $(this).attr('id') } ,
function(){console.log('selectedOption:'+selectedOption+'whatToShow:'+whatToShow);}
);
but get an error that selectedOption is not defined.
can we write something like this $(this, li); because I need the id of li not the id of selectbox.
if there is any other optimized solution ( using function like live or bind ), then please tell me.
Thanks A Lot.

I'm not 100% clear on what you actually want to do, but one thing doesn't make much sense. You want to send the ID of the LI when the select box is changed. Which LI? The last LI clicked? You need to store the state of the active LI so that you can send it in the ajax request if the select box is changed.
Perhaps something like this:
$('select#sort').change(function() {
processAjax();
});
$('ul#sortByRight > li > a').click(function() {
$(this).closest('ul').find('li').removeClass('active');
$(this).closest('li').addClass('active');
processAjax();
});
function processAjax() {
selectedOption = $('select#sort').val();
whatToShow = $('ul#sortByRight').find('.active').attr('id');
alert('selectedOption:' + selectedOption + 'whatToShow:' + whatToShow);
}
or check out the jsFiddle

Related

Angularjs check if section in the form is valid

I want to check my angular form validity with a little tweak,
I have a form builded dynamically with directives involved, Now the form has more than one page to it, so i play with ng-hide/ng-show when i move from page to page...
All i want to do is to check the validity of the first chunk of form inputs, for example:
I have 3 pages, 3 questions in every 'page', before the user can go to the next page, it should check for validation on the three inputs, and only than! he can move to the next one...
on my form tag i have 'novalidate' so i must do all the validations myself...
What you're after is ng-form
You can't nest HTML <form></form> tags but you can with ng-form to split your form into sections.
i.e.
<form name="myForm">
<ng-form name="subForm1">
<input name="txtField1" type="text" ng-model="Field1" ng-maxlength="50" required>
</ng-form>
<ng-form name="subForm2">
<input name="txtField2" type="text" ng-model="Field2" ng-maxlength="10" required>
</ng-form>
<button type="button1" ng-disabled="subForm1.$invalid" ng-click="doSomething() ">Button 1</button>
<button type="button1" ng-disabled="subForm2.$invalid" ng-click="doSomething()" >Button 2</button>
<button type="button3" ng-disabled="myForm.$invalid" ng-click="doSomething()" >Button 3</button>
</form>
In this instance button1 and button2 are disabled on parts of the form where as button3 is disabled based on the whole forms input
Source: https://docs.angularjs.org/api/ng/directive/ngForm
You can use the Angular's form element property $dirty, or you could check if the element you want to validate has the class ng-dirty.
If you'd like, read more here, it explains how to use and check this.
Angular JS has some pretty features which you can take advantage of especially the class .ng-valid and .ng-invalid. As the user fills your form, angular dose a real time update on the state of form fields by changing the classList to correspond to the current state of the form.
Any for field that is has been altered and does not pass the Angular validation will have a class .ng-invalid well all classes that passed the validation will have .ng-valid. While ng-pristine indicates that the form have not been modified ng-dirty tells you that the form has been modified. Not that ng-pristine and ng-dirty cannot be used to ascertain the validity of the field.
Meanwhile for your case I have created a CodePen
angular.module("paged", [])
.controller("FormCtrl", function($scope) {
$scope.form = {page: 1};
$scope.canShow = function(i) {
return (i === $scope.form.page);
};
$scope.submit = function(form) {
alert("Form Submitted", form);
};
$scope.gotoPage = function(pageTo) {
var show = false;
var els = document.getElementsByTagName("input"); //Just with input only to keep it simple
for (var i = 0; i < els.length; i++) {
if (els[i].hasAttribute("data-page") && els[i].getAttribute("data-page") == pageTo - 1) {
if (els[i].classList.contains("ng-invalid")) {
show = false;
break;
}
}
show = true;
}
if (show) {
$scope.form.page = pageTo;
if (pageTo == 4) {
$scope.submit($scope.form);
}
}
}
});
to show you how this can done. As someone will rightfully say, there may ways to kill a rat. I think this is one of them

complex jquery/css selector

I need a selector for this code:
<div class="panel-heading BWHeadingForSection">
<a style="text-decoration:none" href="#faq-cat-1-sub-2" data-parent="#accordion-cat-2" data-toggle="collapse" tabindex="90">
<i class="fa fa-truck fa-lg"></i>
UPS Deutschland
<span class="pull-right">
<i class="glyphicon glyphicon-plus"></i>
</span>
</a>
</div>
And I tried that:
$('div.BWHeadingForSection a[href~="#faq-cat-1-sub-'+globalcarriernumber+'"]').on("click", function(){
count++;
if(count%2==0){
$("#faq-cat-1-sub-"+globalcarriernumber).slideToggle();
//why doesn't this selector work?
//if ( $(this+">span i").hasClass('plus') ) {
// $(this+">span i").removeClass('plus').addClass('minus');
// }
//this selector work's, at least it enters the if -block
if ( $('div.BWHeadingForSection a[href~="#faq-cat-1-sub-'+globalcarriernumber+'"]>span i').hasClass('plus') ) {
$('div.BWHeadingForSection a[href~="#faq-cat-1-sub-'+globalcarriernumber+'"]>span i').removeClass('glyphicon glyphicon-plus').addClass('glyphicon glyphicon-minus');
}
}else{
$("#faq-cat-1-sub-"+globalcarriernumber).hide();
}
});
The relevant line is "$(this+">span i")" and/or "$('div.BWHeadingForSection a[href~="#faq-cat-1-sub-'+globalcarriernumber+'"]>span i')" , which needs some adjustment. I have to replace that "plus"("") with "minus".
If I use the FireBug debugger I get for "$('div.BWHeadingForSection a[href~="#faq-cat-1-sub-'+globalcarriernumber+'"]>span i')" ,it goes into that if-block, but the symbol is still the same. And if I use "$(this+">span i")" I get(when I hove over it) : "a#faq-cat-1-sub-2",but it's not entering the if-block.
Thanks...
First of all you are mixing types here. The function $(...) accepts either an object (a DOM node or a jQuery object) or a selector string but not a concatenation of both.
So better try $(this).find('span i').
As far as I can see in your code snippet, the element you will find then, has the css classes 'glyphicon' and 'glyphicon-plus', but no class 'plus'. So you probably won't be able to remove that. Maybe you want to remove 'glyphicon-plus' and add 'glyphicon-minus'?

How implementing a directive to validate another field (custom form in angularjs)

I have a validation custom form, I use validate-message-character="{{compose.limitCharacter - compose.message.length}}" in a select and textarea like this
<form class="form-horizontal" role="form" name="composeForm" >
<select ng-change="limitComposeCharacter()" ng-selected="compose.profile"
ng-model="compose.profile" ng-options="userId in profiles" name="profile"
validate-message-character="{{compose.limitCharacter - compose.message.length}}" required>
</select>
number Character: {{compose.limitCharacter - compose.message.length}}
<textarea class="form-control" ng-model="compose.message" name="message"
validate-message-character="{{compose.limitCharacter - compose.message.length}}"
required></textarea>
Form validity: {{composeForm.$valid}}
I have something like this:
1° Select User has compose.limitCharacter = 100
2° Select User has compose.limitCharacter = 200 etc etc.
This is my directive to check number Character is > 0
angular.module('App')
.directive('validateMessageCharacter', function () {
return {
require: 'ngModel',
link: function postLink(scope, element, attrs, c) {
scope.$watch(attrs.ngModel, function() {
console.log(attrs.validateMessageCharacter);
if(attrs.validateMessageCharacter < 0)
{
c.$setValidity('maxCharacter', false);
c.$invalid = true;
}else{
c.$setValidity('maxCharacter', true);
c.$invalid = false;
}
});
}
};
});
It doesn't work proply when change select without change the textarea
some advice?
First, using an advice from the angular google group, I changed the scope.$watch to attr.$observe.
Second, the reason it validated only after typing text is that the text area is a required field.
Your code works here:
http://plnkr.co/edit/YvsuLoHzX9eqb7FhDgXA?p=preview

mootools select box focus

I have a select box
<select>
<option value="0">0 mins</option>
<option value="1">1 mins</option>
<option value="2">2 mins</option>
</select>
and I want to fire an event when the visitor either clicks on a value or clicks anywhere else on the page -i.e loss of focus on the select box
I've fiddled about for four hours now with no joy. I'm now down to this:
var c = 0;
$("selectTime").addEvent('click', function() {
if (c++ % 2 == 1) {
console.log(c);
//$(this).blur();
}
});
$('selectTime').click(function() {
if ($('select').is(':blur')) {
c = 1;
} else {
c = 0;
}
});
any ideas?
thanks
The mootools syntax for adding multiple events to same element is:
$('myElementID').addEvents({
blur: function(){
alert('blur');
},
click: function(){
alert('click');
}
});
Example with you code
You could though use just the change event, which fires when the element is changed. Like:
$('myElement').addEvent('change', function(){
alert('Select changed');
});
Example
Note that part of your code is using jQuery syntax, part is using MooTools syntax.

Javascript to select first option of select list

I need to create a reset button which on click will set all select lists in a form to index 0. I have tried this code for function, but it gives a syntax error on myForm.length;
<script type="text/javascript">function ResetForm(form) {
var myForm = document.forms[form];
for( var i=0; i < myForm.length; i++ ){
myForm.select[i].selectedIndex =0; } }
</script>
There is no such property as someForm.select, try this instead:
selectTags = myForm.getElementsByTagName("select");
for(var i = 0; i < selectTags.length; i++) {
selectTags[i].selectedIndex =0;
}
A quick note to answer from Ron Royston
(I've only tried this on Chrome 74.0)
Setting mySelect.selectedIndex = 0; or $('#mySelect').prop("selectedIndex", 0); won't work if the option if it's disabled.
Hope this saves someone some time and frustration!
You simply need to set the .selectedIndex property, as in mySelect.selectedIndex = 0;. Try out the example below.
var doc = document;
var myCheckbox = doc.getElementById('my-checkbox');
var mySelect = doc.getElementById('my-select');
myCheckbox.addEventListener("click", function(e){
if (this.checked){
mySelect.disabled = false;
} else {
mySelect.selectedIndex = 0;
mySelect.disabled = true;
}
});
<label><input type="checkbox" id="my-checkbox" value=""> Enable Dropdown</label><br>
<select id="my-select" disabled>
<option class="placeholder" selected disabled value="">Select credential</option>
<option value="apples">apples</option>
<option value="oranges">oranges</option>
<option value="bananas">bananas</option>
</select>
This will set every selection directly after changing to the first option:
<select onchange="your_selection_func(); this.selectedIndex=0;">
You may find jquery useful here. This SHOULD do the trick...
$(function()
{
$('.resetButton').click(function()
{
$(this).closest('form').find('select').each(function()
{
$(this)[0].selectedIndex=0;
});
});
});
<input type="reset" class="resetButton" />
I found some hack:
<select onchange="doSomething()">
<option value="a" selected disabled hidden>a</option>
<option value="a">a</option>
<option value="b">b</option>
<option value="…">…</option>
</select>
combination of selected disabled hidden causes that (visualy) first option responds with change event (even with same value!).
Working with IE, Edge, Opera, Chrome, but not working in FF :(
I realize this is kinda old, but wanted to improve on teh1's answer. There's no reason to create a jQuery object from 'this' when you're just going to grab the DOM element back from it:
$(this).closest('form').find('select').each(function() {
this.selectedIndex = 0;
});