Validate multiple selectors on click and unclick - javascript

jQuery(function($){
var nickname = $('#nickname');
var email = $('#email');
var email_match = $('#email_match');
var password = $('#password');
var birthday_day = $('#birthday_day');
var birthday_month = $('#birthday_month');
var birthday_year = $('#birthday_year');
var gender_femal = $('#gender_female');
var gender_femal = $('#gender_male');
var error = $('.error');
nickname.blur( function(){
if (nickname.val() < 1) error.html('error')
});
nickname.click( function(){
if (nickname.val() > 0) error.html('')
});
});
Now this only works for nickname selector what is the easiest way to check all selectors without copy paste the same function.
for example
blur/focus(function(){if (nickname || email || password < 0) error.html('error'); });
while i'm typing this question i'm getting the idea that the best way is to duplicate the function this because i want to show error if the value is empty.
But i like to hear from the pro's i believe there will be a good way to do this.

You can target them all in one selector, like so:
var fields = $('#nickname, #email, #password, ...');
But it might be easier if you can identify them with something common like:
var fields = $('#some-container :input');
...or:
var fields = $('.form-fields');
Once you have by some means identified a set of all the elements of interest, you may bind the event handlers to all of them at once:
fields.blur(function() {
// 'this' will refer to the DOM node blurred, even though fields refers to all of them
var field = $(this);
if(field.val().length == 0)
error.html('error');
});

Related

Troubleshooting Conditional Form

I'm new to Javascript and trying to build a conditional form using bootstrap and JQuery. I would really appreciate the help as I've been working most of the day on this to no avail.
I'm trying to show the div with id physician (and subsequent field) when the select field with the name AppointmentType has a value of Orthopedic or Rheumatology. Here is the link to the live form.
Here is my javascript:
$( document ).ready(function() { //wait until body loads
//Inputs that determine what fields to show
var appttype = $('#secureform input:select[name=AppointmentType]');
var physician = document.getElementById("physician");
appttype.change(function(){ //when the Appointment Type changes
var value=this.value;
physician.addClass('hidden'); //hide everything and reveal as needed
if (value === 'Orthopedic' || value === 'Rheumatology'){
physician.removeClass('hidden'); //show doctors
}
else {}
});
});
These lines are going to cause errors (which you should see in your devtools console):
var appttype = $('#secureform input:select[name=AppointmentType]'); // `input:select` is not a valid selector and causes the rest of the script to fail
physician.addClass('hidden'); // `addClass` is a jQuery method, so this should be `$(physician).addClass('hidden')`
physician.removeClass('hidden');// `removeClass` is a jQuery method, so this should be `$(physician).removeClass('hidden')`
Correct those lines and it should work.
If it helps, I would write it like this:
$( document ).ready(function () {
//Inputs that determine what fields to show
var apptType = $('#secureform select[name="AppointmentType"]'); // dropped the `input:` part
var physician = document.getElementById('physician');
physician.classList.add('hidden'); //hide this initially, outside the change handler
apptType.change(function () { // when the Appointment Type changes
var value = $(this).val().toLowerCase(); // leave case-sensitivity out of it.
var showables = [ // using an array as I prefer using a simple `indexOf` for multiple comparisons
'orthopedic',
'rheumatology',
];
var isShowable = showables.indexOf(value) > -1;
physician.classList.toggle('hidden', !isShowable);
// or, the jQuery equivalent:
// $(physician).toggleClass('hidden', !isShowable);
});
});
Your selector is incorrect:
var appttype = $('#secureform input:select[name=AppointmentType]');
// this should be
var appttype = $('#secureform select[name=AppointmentType]');
Furthermore you are mixing jquery with vanilla JS. Your are using vanilla js here
var physician = document.getElementById("physician");
Physician is now a dom object and not a jquery object. You should use this instead:
var physician = $("#physician");
Additionally you should replace
var value=this.value;
with this
var value= $(this).val();

With jQuery, how to find an data attribute on or within an element? (tree traversal)

I have several unknown elements (Could be span, input, select, div, whatever):
<div id="SomeControl" > <-- Data Attribute could be here
<span> <-- or Data Attribute could be here or even lower in the DOM
... somewhere here is a data attribute: data-is-dirty="True"
</span>
</div>
...
var $myControl = $('#SomeControl');
Using $myControl is there a way to find the existence and/or value of a given data attribute?
I've tried:
var isDirty = $myControl.find(':has([data-is-dirty]').data('is-dirty');
Any suggestions would be appreciated.
Ways I could think about doing it without wrapping it in another element. Not a fan of any of them, maybe it will inspire others.
var horrible1 = $("#test").find("*").andSelf().filter("[data-is-dirty]").length;
var horrible2 = $("#test").find("[data-is-dirty]").andSelf().filter("[data-is-dirty]").length;
var elem = $("#test");
var horrible3 = elem.parent().find("#" + elem.attr("id") + "[data-is-dirty], #" + elem.attr("id") + " [data-is-dirty]").length;
var elem = $("#test");
var horrible4 = elem.find("[data-is-dirty]").add(elem.filter("[data-is-dirty]")).length;
var horrible5 = $("[data-is-dirty]").filter( "#test, #test *" ).length;
JSFiddle
var isDirty = $myControl.find('[data-is-dirty]');
Fiddle : http://jsfiddle.net/UpGQX/1/ Courtesy: gibberish
To select $myControl itself (if dirty):
var isDirty = $myControl.find('[data-is-dirty]');
var myControlIsDirty = $myControl.attr('data-is-dirty');
if (typeof myControlIsDirty !== 'undefined' && myControlIsDirty !== false) {
isDirty.push($myControl);
}
or maybe even better:
var isDirty = $myControl.parent().find('[data-is-dirty]');
$( "[data='data-is-dirty']" ) , and if you want to exclude your parent div just use .not("#SomeControl")
try this http://fiddle.jshell.net/HHaT9/
var isDirty=$("#SomeControl[data-is-dirty],#SomeControl [data-is-dirty]").data('is-dirty');
[Edit] Same idea, if you don't know the element id:
var isDirty=$someControl.data("is-dirty")||$("[data-is-dirty]",$someControl).data("is-dirty");

id of a link that a function is called from

I hope it's not a problem to post much specific code here, but I figure it will be better explained if everyone can just see it, so I will give you my code and then I will explain my problem.
My code:
function addBeGoneLinks () {
var beGoneClassElems;
var beGoneSpan;
var beGoneLink;
var beGonePrintSafe;
var spacesSpan;
//var middotSpan = document.createElement ('span');
var interactionContainer = document.getElementsByClassName('feedItemInteractionContainer');
for (var i=0; i<children.length; i++)
{
beGonePrintSafe = false;
beGoneClassElems = children[i].getElementsByClassName('beGone')
beGonePrintSafe = true;
if (beGoneClassElems.length == 0)
{
beGoneLink = document.createElement('a');
beGoneLink.href = 'javascript:void(0);';
beGoneLink.appendChild(document.createTextNode('Be Gone'));
beGoneLink.className = 'beGone';
beGoneLink.id = 'beGoneLink' + i.toString();
beGoneLink.addEventListener ("click", function() {beGone();}, false);//This line!
beGoneLink.align = 'right';
spacesSpan = document.createElement('span');
spacesSpan.innerHTML = ' - ';
if (interactionContainer[i] != undefined)
{
interactionContainer[i].appendChild(spacesSpan);
interactionContainer[i].appendChild(beGoneLink);
}
}
}
}
Here I have a function from a Greasemonkey script that I am working on. When one of the links is clicked, my aim is to have it call the function beGone() which will, among other things, remove the whole element a few parents up, thereby removing their sibling's, their parents and their parents' siblings, and one or two levels after that.
My idea was just to get the id of the link that was pressed and pass it to beGone() so that I could then get the parents using its id, but I do not know how to do that. Am I able to have the id of a link passed by the function that it calls? If not, is there any other way to do this?
I am not sure whether I am missing some really simple solution, but I haven't been able to find one rooting around the web, especially because I was unsure how I would search for this specific problem.
Try this:
beGoneLink.addEventListener("click", beGone, false);
beGone = function (evt) {
evt.target; // evt.target refers to the clicked element.
...
}
You can then use evt.target.id, evt.target.parentNode, etc.

Update div with jQuery upon entry of data

I have a form with four text input elements. Every time one of them is updated, I want the sum of the four text input boxes to be displayed in a div below without the user pushing a button. Here's what I have so far (I got the idea from here [does this only work with select?]):
var getSum = function() {
var email = $('#emailDown').val();
var internet = $('#internetDown').val();
var server = $('#serverDown').val();
var desktop = $('#pcDown').val();
//TODO:Check for integers (not needed with sliders)
var sum = email + internet + server + desktop;
$('totalHoursDown').html(sum);
}
$('#emailDown').change(getSum(event));
$('#internetDown').change(getSum(event));
$('#serverDown').change(getSum(event));
$('#pcDown').change(getSum(event));
Currently, it's not updating. (Don't worry about validating). I'm new to PHP, so I'm not sure if I should be using it in this instance.
You are missing a # or . in your selector, depending on if totalHoursDown is a class or an ID:
$('totalHoursDown').html(sum);
// Should be this if ID
$('#totalHoursDown').html(sum);
// or this if class
$('.totalHoursDown').html(sum);
Update:
I modified the code by jmar777 a bit to make it work. Try this instead:
$(function(){
var $fields = $('#emailDown, #internetDown, #serverDown, #pcDown'),
$totalHoursDown = $('#totalHoursDown');
$fields.change(function() {
var sum = 0;
$fields.each(function()
{
var val = parseInt($(this).val(), 10);
sum += (isNaN(val)) ? 0 : val;
});
$totalHoursDown.html(sum);
});
});
​Here is a working fiddle as well: http://jsfiddle.net/mSqtD/
Try this:
var $fields = $('#emailDown, #internetDown, #serverDown, #pcDown'),
$totalHoursDown = $('#totalHoursDown');
$fields.change(function() {
var sum = 0;
$fields.each(function() { sum += $(this).val(); });
$totalHoursDown.html(sum);
});
Also, in your example, you had $('totalHoursDown').html(sum);, which I'm assuming was intended to be an ID selector (i.e., $('#totalHoursDown').html(sum);.

Jquery script freezing browser but working

i'm trying to make a live search for my mobile website, I don't want to query the database every time a user type a letter so I created a ordered list with all the names that can be searched for and i'm looping through it with jquery, problem is that I have 3300 names and it's freezing the browser when it searches through them, can anyone give me a tip about better ways to do it? here is my code:
$(document).ready(function(){
$("input#search").keyup(function(){
var filter = $(this).val(), count = 0;
var html = "";
$("ol.pacientes li").each(function(){
var nome_paciente = $(this).text();
if(nome_paciente.indexOf(filter.toUpperCase()) != -1){
html = html + " " + nome_paciente;
}
$('#pacientes_hint').html(html);
});
Use the jQuery autocomplete version. You can load an array with all your names and pass it in to autocomplete, which will work on the fly.
http://bassistance.de/jquery-plugins/jquery-plugin-autocomplete/
You could change your each to:
var text = $("ol.pacientes li:contains(\""+filter.toUpperCase()+"\")").map(function() {
return $(this).text();
}).join(' ');
$('#pacientes_hint').text(text);
Besides being shorter, the only improvement will be setting the contents of $('#pacientes_hint') only at the end, which could help.
Let me know if you need a more creative solution.
First of all, you could move #pacientes_hint outside the each function.
$(document).ready(function(){
$("input#search").keyup(function(){
var filter = $(this).val(), count = 0;
var html = "";
$("ol.pacientes li").each(function(){
var nome_paciente = $(this).text();
if(nome_paciente.indexOf(filter.toUpperCase()) != -1){
html = html + " " + nome_paciente;
} // end if
}); // end each
$('#pacientes_hint').html(html);
Then, you can define ol.pacientes as a variable before the keyup handler, so it doesn't look for it everytime and in the each function, search inside the variable:
$(document).ready(function(){
var pacientes_list = $("ol.pacientes");
var pacientes_hint = $("#pacientes_hint");
$("input#search").keyup(function(){
...
$("li", $(pacientes_list)).each(function(){ // search in the container
...
}); // end each
$(pacientes_hint).html(html);

Categories