javascript sort with data handlers issue - javascript

sorry if this is a stupid question but I'm a bit of a javascript novice and I'm trying to learn better programming instead of "cheating" and writing out each event type individually.
I can't seem to get this to run. The user clicks on a link at the top of the page with a data attribute with an event types ID number in it (data-event-type="1", etc). It should hide any events without that id number. JS and HTML is below.
JS fiddle with it all
http://jsfiddle.net/96r9jqp6/
HTML
<div class="sort">
All
Trainer
Conference
</div>
<div class="events-container">
<div class="eventsys-event-wrapper" data-event-type="1">
event 1 info here
</div>
<div class="eventsys-event-wrapper" data-event-type="2">
event 2 info here
</div>
<div class="eventsys-event-wrapper" data-event-type="1">
event 3 info here
</div>
<div class="eventsys-event-wrapper" data-event-type="2">
event 4 info here
</div>
</div>
Javascript
<script src="text/javascript">
$(document).ready(function(){
$('.eventSort').click(function(){
if (event.preventDefault) event.preventDefault();
else event.returnValue = false;
var thisEventSort = $(this).attr("data-event-sort");
if (thisEventSort = "0"){
$('.eventsys-event-wrapper').show('fast');
return;
} else {
$('.eventsys-event-wrapper').each(function(){
var thisEventType = $(this).attr("data-event-type");
if (thisEventType = thisEventSort) {
$(this).show('fast');
} else {
$(this).hide('fast');
}
});
}
});
});
</script>

if (thisEventSort = "0")
needs to be
if (thisEventSort === "0")
and same for
if (thisEventType = thisEventSort)
needs to be
if (thisEventType === thisEventSort)

Something like this
$('.eventSort').click(function(e){
e.preventDefault();
var thisEventSort = $(this).data("event-sort");
$('.eventsys-event-wrapper').hide().filter(function() {
return thisEventSort === 0 ? true : ($(this).data('event-type') == thisEventSort);
}).show('fast');
});
FIDDLE

You didnt pass event also... so your if there is not needed...
and use .data("event-sort") for this...
$(document).ready(function(){
$('.eventSort').click(function(event){
event.preventDefault();
var thisEventSort = $(this).data("event-sort");
if (thisEventSort == "0"){
$('.eventsys-event-wrapper').show('fast');
return;
} else {
$('.eventsys-event-wrapper').each(function(){
var thisEventType = $(this).attr("data-event-type");
if (thisEventType == thisEventSort) {
$(this).show('fast');
} else {
$(this).hide('fast');
}
});
}
});
});

I've updated your jsfiddle here
http://jsfiddle.net/96r9jqp6/5/
the most import piece is your use of the "=" operator
you need to use triple equal to test for equality instead of just one.
also when using data-* attributes, you should use the jquery .data() function to retrieve its values
$(document).ready(function(){
$('.eventSort').click(function(){
if (event.preventDefault) event.preventDefault();
else event.returnValue = false;
var thisEventSort = $(this).data("event-sort");
console.log(thisEventSort);
if (thisEventSort === 0){
$('.eventsys-event-wrapper').show('fast');
return;
} else {
$('.eventsys-event-wrapper').each(function(){
var thisEventType = $(this).data("event-type");
if (thisEventType === thisEventSort) {
$(this).show('fast');
} else {
$(this).hide('fast');
}
});
}
});
});

Related

How come multiple classes not targeting in textarea?

I want to use validate_empty_field function for both classes .log and .log2. For some reason only .log is targeted but .log2 textarea is not. When you click on text area, if empty, both should show validation error if the other one is empty or if both empty.
$(document).ready(function() {
$('#field-warning-message').hide();
$('#dob-warning-message').hide();
var empty_field_error = false;
var dob_error = false;
// $('input[type=text], textarea')
$('.log, .log2').focusout(function () {
validate_empty_field();
});
function validate_empty_field() {
var field = $('.log, .log2, textarea').val();
// var first_name_regex = /^[a-zA-Z ]{3,15}$/;
if (field.length == '') {
$('#field-warning-message').show();
$('#field-warning-message').html("Please fill out form!");
empty_field_error = true;
} else if (field.length < 1) {
$('#field-warning-message').show();
$('#field-warning-message').html("Please fill out form!");
empty_field_error = true;
} else {
$('#field-warning-message').hide();
}
}
$('.verify-form').submit(function () {
empty_field_error = false;
dob_error = false;
validate_empty_field();
if ((empty_field_error == false) && (dob_error == false)) {
return true;
} else {
return false;
}
})
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<textarea class="log"></textarea>
<textarea class="log2"></textarea>
<div id="field-warning-message"></div>
You should pass the event to the handler so you have access to the target
Change your event listener line to this:
$('.log1, .log2').focusout(validate_empty_field);
and then accept an argument in validate_empty_field
function validate_empty_field(ev){
var field = $(ev.target).val();
if(!field.length){
//textarea is empty!
}else{
//textarea is not empty!
}
}
in fact, you could do all of this in an anonymous function you have already created, and use the on method to stick with JQuery best practices:
$('.log1, .log2').on('focusout', function(){
if(!$(this).val().length){
//this textarea is empty
}else{
//this textarea is not empty!
}
});
And yes, adding one class to all textareas and swapping out .log1, .log2 for that class would be a better option.
EDIT: Final option should cover all requirements.
$('.log').on('focusout', function(){
$('.log').each(function(){
if(!$(this).val().length){
//this textarea is empty
}else{
//this textarea is not empty!
}
}
});

Creating a callback function containing if else statement

the problem I have is that I would like to use an if else statement in a callback function like this:
alertNotify("alert","Do you want to delete this",function(delete) {
if(delete) {
//do code
}else {
//do nothing
}
});
current function code:
function alertNotify(text,type) {
$("body").append("<div id = 'alert' class='common'>\
<div id ='content'class='common'>\
</div>\
</div>");
var alert = $("<div id = 'ok' class='common'>\
Ok\
</div>\
<div id = 'cancle''class='common'>\
Cancle\
</div>");
var rename = $("<div class='common rename_it'>\
Ok\
</div>");
var type_file = $("<input type='text' id ='rename'><div id='hover'></div>");
if(type == "alert") {
$("#content").append(text);
$("#content").append(alert);
}
if(type == "rename") {
$("#content").append(rename);
$("#content").append(type_file);
}
$("#ok").click(function() {
$("div").remove("#alert");
});
$(".rename_it").click(function() {
$("div").remove("#alert");
});
$("#cancle").click(function() {
$("div").remove("#alert");
});
}
I would like the if statement to differentiate between whether the #ok div was clicked or the #cancel div was clicked but I have no idea where to start. Any ideas?
You can use confirm instead:
document.getElementById("prompt").onclick=function(){
if(confirm("Do you want to delete item?")){
// Delete
document.getElementById("status").innerHTML = "deleted";
}else{
// Don't delete
document.getElementById("status").innerHTML = "spared";
}
}
<button id="prompt">delete item</button>
<div id="status"></div>
It is possible that you are trying to do something like this
if( confirm("Do you want to delete this")){
//delete
}else{
// do not delete
}
In raw JavaScript your code might look something like:
//<![CDATA[
var pre = onload;
onload = function(){
if(pre)pre(); // if previous onload run here using this type of Event handler
var doc = document, bod = doc.body;
function E(id){
return doc.getElementById(id);
}
var ok = E('ok');
ok.onclick = function(){
console.log('ok was clicked');
}
// another way to use E
E('cancel').onclick = function(){
console.log('cancel was clicked');
}
}
//]]>
First you need event listeners on each element. So you can use something like
var element0 = document.getElementById(divID);
element0.addEventListener('click', funcDivClicked(element0));
To put a click event listener on all of them with a loop, see here:
Simple way to get element by id within a div tag?
I suggest using window.confirm instead of alert:
http://www.w3schools.com/js/js_popup.asp
function funcDivClicked(el){
var cBox = confirm("Delete "+el.getAttribute("id")+"?");
var strAction;
if (cBox == true) {
strAction = "You pressed OK";
//deletes the element
el.parentNode.removeChild(el);
} else {
strAction = "You pressed Cancel!";
}
console.log(strAction);
}
You could check the target within the event handler:
document.querySelector('body').addEventListener('click', function(e){
if(e.target.id === 'ok'){
alert('ok');
} else if(e.target.id === 'cancel'){
alert('cancel');
}
});
document.querySelector('body').addEventListener('click', function(e){
if(e.target.id === 'ok'){
alert('ok');
} else if(e.target.id === 'cancel'){
alert('cancel');
}
});
div {
color: white;
display: inline-block;
text-align: center;
height: 20px;
width: 100px;
}
div#ok {
background: green;
}
div#cancel {
background: red;
}
<div id="ok">Ok!</div>
<div id="cancel">Cancel!</div>
Sorry about that little bit of confusion. If I had of explained myself properly someone else might have answered but instead i got it. Add paremeter called callback and simply return callback(true); when the ok button is clicked and then my USB stopped working....

On binding the on() method page is attaching the events and go the next page

My problem is that when I try to bind the click event using JQuery on(). It doesn't go the next page.
What is your favorite color?This input is required.
$('#continue-bank-login-security-question-submit').off('click');
$('#continue-bank-login-security-question-submit').on('click',function(e){
e.preventDefault();
e.stopPropagation();
if ($('.tranfer--bank-security-question-inputs').val().length===0){
$('.transfer--form-row-error').show();
return false;
} else {
$('.transfer--form-row-error').hide();
return true;
}
});
Because you call
e.preventDefault();
e.stopPropagation();
of course it does not do anything after returning.
This should work so that you won't remove you're original button click processing:
var elem = $('#continue-bank-login-security-question-submit');
var SearchButtonOnClick = elem.get(0).onclick;
elem.get(0).onclick = function() {
var isValid = false;
var sessionKey = '';
if ($('.tranfer--bank-security-question-inputs').val().length===0){
$('.transfer--form-row-error').show();
return false;
} else {
$('.transfer--form-row-error').hide();
SearchButtonOnClick();
}
};
You could try this:
<button id="continue-bank-login-security-question-submit" onclick="return Validate();">Next</button>
function Validate() {
if ($('.tranfer--bank-security-question-inputs').val().length === 0) {
$('.transfer--form-row-error').show();
return false;
} else {
$('.transfer--form-row-error').hide();
nextPage();
}
}

Changing the value of a boolean (Jquery/Javascript)

I'm trying to make a boolean change in this value by using a function. I tried it this way:
var itemInStock = false;
$("#button").click(function(){
itemInStock = true
}
if( itemInStock === false){
document.write("item is out of stock");
} else{
document.write("item is in stock");
}
I understand why it's not working but I can't find a way to solve this!
I just can guess what you're trying to achieve. It seems like you wanna check at some point, if item is currently in stock. Since you can't know when the click will occur, one solution could be periodically checking the value.
(function () {
var itemInStock = false;
$("#button").click(function () {
itemInStock = true
});
window.setInterval(function () {
if (itemInStock === false) {
console.log("item is out of stock");
} else {
console.log("item is in stock");
}
}, 500);
})()
http://jsfiddle.net/Ttu5N/
Tell me, if I'm wrong with my guessing.
Update: way easier approach
$(function () {
var $state = $('#state');
$state.text('item is out of stock');
$("#button").click(function () {
$state.text('item is in stock');
});
})
<button id="button">click me</button>
<div id="state"></div>
http://jsfiddle.net/Wb3ET/
Just do it directly on click.
because itemInStock doesn't get changed until the button is clicked...
You cannot use document.write after load and is also not necessary also the Boolean changes when the button is clicked and not before
Create a span with id="status" and have
var itemInStock = false;
$(function() {
$("#button").click(function(){
itemInStock = true;
$("#status").html("item is in stock":
}
$("#status").html(itemInStock?"item is in stock":"item is out ofstock");
});
// HTML
<div id="status">item is out of stock by default</div>
// JS
var itemInStock = false;
$("#button").click(function(){
itemInStock = true;
}, changeStatus());
function changeStatus(){
if( itemInStock === false){
$('#status').html("item is out of stock");
} else{
$('#status').html("item is in stock");
}
}

Detect user selection within html element

How can I detect if a user selection (highlighting with mouse) is within/a child of a certain element?
Example:
<div id="parent">
sdfsdf
<div id="container">
some
<span>content</span>
</div>
sdfsd
</div>
pseudo code:
if window.getSelection().getRangeAt(0) is a child of #container
return true;
else
return false;
Using jQuery on() event handler
$(function() {
$("#container > * ").on("click",
function(event){
return true;
});
});​
Edit: http://jsfiddle.net/9DMaG/1/
<div id="parent">outside
<div id="container">
outside
<span>first_span_clickMe</span>
<span>second_span_clickMe</span>
</div>
outside</div>
$(function() {
$("#container > span").on("click", function(){
$('body').append("<br/>child clicked");
});
});​
​
Ok I managed to solve this in a "dirty" way. The code could use improvement but it did the job for me and I am lazy to change it now. Basically I loop through the object of the selection checking if at some point it reaches an element with the specified class.
var inArticle = false;
// The class you want to check:
var parentClass = "g-body";
function checkParent(e){
if(e.parentElement && e.parentElement != $('body')){
if ($(e).hasClass(parentClass)) {
inArticle = true;
return true;
}else{
checkParent(e.parentElement);
}
}else{
return false;
}
}
$(document).on('mouseup', function(){
// Check if there is a selection
if(window.getSelection().type != "None"){
// Check if the selection is collapsed
if (!window.getSelection().getRangeAt(0).collapsed) {
inArticle = false;
// Check if selection has parent
if (window.getSelection().getRangeAt(0).commonAncestorContainer.parentElement) {
// Pass the parent for checking
checkParent(window.getSelection().getRangeAt(0).commonAncestorContainer.parentElement);
};
if (inArticle === true) {
// If in element do something
alert("You have selected something in the target element");
}
};
}
});
JSFiddle

Categories

Resources