Checkbox doesn't checked using JQuery - html

I'm working on my web application using NodeJS, EJS and JQuery. Using JQuery I'am able to detect click event on checkbox but checkbox doesn't appeare checked.
<input type="checkbox" id="myCheck2" class="myClass">
JQuery
function checkboxDefault(){
$("#myCHeck1").attr("checked", false);
$("#myCHeck2").attr("checked", true);
}
$(function() {
$(document).on('click', ".myClass", function (e) {
e.preventDefault();
var event = $(this).attr("id");
if(event == "myCheck1")
$("#myCheck1").attr("checked", true);
else
$("#myCheck2").attr("checked", false);
});
});
I tried using $("#myCheck*").prop, instead .attr() but it doesn't work. Click event and right checkbox ID are rightly detected. Can you help me please? Thanks

prop('checked', true) // to check the box
prop('checked', false) // to uncheck the box
Also #myCHeck1 isn't it a typo?
H is big

Related

Dragging from Outlook to Chrome moves email to Deleted folder

Recently, I noticed that the drag and drop function was added back so that you could successfully drag an email from your Microsoft Outlook inbox to a web app's file upload. The issue is that once the file has been dragged to the web app, the email is moved to the Deleted folder in Outlook. Any ideas on how to resolve?
This issue can be solved by the web developper.
You can go to the following web page to see exemples with the different behaviors (copy, move, link) when we do a drag and drop in a browser:
https://codepen.io/SitePoint/pen/epQPNP
Put the following line into 'dragenter', 'dragover' and 'drop' event handler :
e.originalEvent.dataTransfer.dropEffect = "copy";
My code to solve the issue:
$('#myDropArea').on({
'dragenter': function (e) {
e.originalEvent.dataTransfer.dropEffect = "copy";
e.stopPropagation();
e.preventDefault();
$(this).addClass('draginprogress');
$(this).find('.DragText').css({ 'z-index': '1000' }).show()
},
'dragover': function (e) {
e.originalEvent.dataTransfer.dropEffect = "copy";
e.preventDefault();
e.stopPropagation();
},
'dragleave': function (e) {
e.stopPropagation();
e.preventDefault();
$(this).removeClass('draginprogress');
$(this).find('.DragText').hide();
},
'drop': function (e) {
var dataTransfer = e.originalEvent.dataTransfer;
$(this).removeClass('draginprogress');
$(this).find('.DragText').hide()
if (dataTransfer && dataTransfer.files.length) {
e.originalEvent.dataTransfer.dropEffect = "copy";
e.preventDefault();
e.stopPropagation();
//DO DROP action
}
}
});
I hope this helps
Most likely you are doing move instead of copy.

AngularJs ui-bootstrap Typeahead with scroll

I have created an typeahead on my input using angularjs ui-bootstrap. Code as below:
<div id="scrollable-dropdown-menu">
<input type="text" name="uName" ng-model="uName" autocomplete="off"
required class="form-control input-medium" placeholder="Enter user
name..." typeahead="uName.uName for uName in getUserNames($viewValue)"
typeahead-on-select='onSelect($item, $model, $label)'/>
</div>
I wanted to add a scroll to this so I have wrapped it around a div and added css to achieve scrolling.
The issue is if I start tying something and use my keyboards down arrow on the scroll I cant see the selected item ie the scroll does not move with the arrow key. I have to use my mouse to scrill. I believe its because I am setting a height of the div.
I have created a demo to show the issue as: https://codepen.io/kaka1981/pen/YOvYRY
Any solution for making this work ?
I was able to resolve this using below directive:
.directive('typeahead', function () {
return {
restrict: 'A',
priority: 1000, // Let's ensure AngularUI Typeahead directive gets initialized first!
link: function (scope, element, attrs) {
// Bind keyboard events: arrows up(38) / down(40)
element.bind('keydown', function (evt) {
if (evt.which === 38 || evt.which === 40) {
// Broadcast a possible change of the currently active option:
// (Note that we could pass the activeIdx value as event data but AngularUI Typeahead directive
// has its own local scope which makes it hard to retrieve, see:
// https://github.com/angular-ui/bootstrap/blob/7b7039b4d94074987fa405ee1174cfe7f561320e/src/typeahead/typeahead.js#L104)
scope.$broadcast('TypeaheadActiveChanged');
}
});
}
};
}).directive('typeaheadPopup', function () {
return {
restrict: 'EA',
link: function (scope, element, attrs) {
var unregisterFn = scope.$on('TypeaheadActiveChanged', function (event, data) {
if(scope.activeIdx !== -1) {
// Retrieve active Typeahead option:
var option = element.find('#' + attrs.id + '-option-' + scope.activeIdx);
if(option.length) {
// Make sure option is visible:
option[0].scrollIntoView(false);
}
}
});
// Ensure listener is unregistered when $destroy event is fired:
scope.$on('$destroy', unregisterFn);
}
};
});
Thanks to the post at: up/down arrow key issue with typeahead control (angular bootstrap UI)

Form hidden field and required validation use

I have an HTML5/Bootstrap form with hidden fields:
style="display: none"
which i show/hide via jQuery:
show() | hide()
For field validation i use the attribute required.
I want to have all my hidden fields as required but when some of them don't appear then the form can't proceed to submission.
Any thoughts about how can i have validation enabled only to fields displayed by user selections?
You can use this trick:
inside HTML form:
<input type="text" name="username" required="required" class="input-hidden">
CSS class:
.input-hidden{
height:0;
width:0;
visibility: hidden;
padding:0;
margin:0;
float:right;
}
You can add a class name for all the required attributes in the html:
<input type="text" name="first_name" class="card-payment-info" required>
<input type="text" name="last_name" class="card-payment-info" required>
and, from js event like a click, you can enable or disable the required attributes:
// disable require:
$(".card-payment-info").attr('required', false);
// enable require
$(".card-payment-info").attr('required', true);
Add a class .hideable to your hideable required inputs.
Then use these functions instead of your show() and hide():
function show1() {
//Your show() code here
$('.hideable').attr('required', 'required');
}
function hide1() {
//Your hide() code here
$('.hideable').removeAttr('required');
}
1 - Change the form to "novalidate"
2 - Catch the submit event
3 - Force the browser to check individually each visible input with input.reportValidity()
$('form')
.attr('novalidate', true)
.on('submit', function(){
var isValid = true;
$('input:visible,select:visible,textarea:visible', this).each(function() {
// report validity returns validity of input and display error tooltip if needed
isValid = isValid && this.reportValidity();
// break each loop if not valid
return isValid;
});
// do not submit if not valid
return isValid;
})
I've made a JQuery tool for this that also uses a mutation observer to automatically apply on dynamically created forms.
https://github.com/severinmoussel/VisibilityFormValidator/blob/master/VisibilityFormValidator.js
I wrote a drop-in replacement for the built-in show() and hide() that removes required on hide and restores them back on show (for all child elements).
(function ($) {
var oldShow = $.fn.show;
$.fn.show = function () {
oldShow.apply(this, arguments); //run the original "show" method
this.find("[notrequired]").prop("required", true).removeAttr("notrequired");
return this;
};
var oldHide = $.fn.hide;
$.fn.hide = function () {
oldHide.apply(this, arguments); //run the original "hide" method
this.find("[required]").prop("required", false).attr("notrequired", "1");
return this;
};
})(jQuery);
UPD: published as a gist here in case anyone wants to add anything https://github.com/alex-jitbit/jquery-required-visibility/blob/main/showhide.js
You can add pointer-events: none;, so the user can't click on the hidden element and also the cursor doesn't change when you hover it. As #DeadApe answered in this question
https://stackoverflow.com/a/65356856/6938902
One solution is to write your own validation-function:
This function checks all textareas and inputs in the default way, but first check if the input is displayed.
function validateFormOnlyVisableInputs(elForm) {
var inputs = elForm.querySelectorAll("input, textarea");
for (var i = 0; i < inputs.length; i++) {
console.log(i);
// display:none inputs ignorieren
if (inputs[i].offsetParent === null) continue;
if (!inputs[i].checkValidity()){
inputs[i].reportValidity();
return false;
}
}
return true;
}
You have to add an eventlistener to the submit-button and call the valdation function:
// this is out of a class, so you have to remove this...
// if you have problems you can write me ;)
this.elSendButton = this.elForm.querySelector("Button");
this.elSendButton.addEventListener("click", async (e) => {
e.preventDefault();
if (validateFormOnlyVisableInputs(this.elForm)) {
this.elForm.submit();
...

Redirect a user when box is closed

I have a javascript popup context menu with a button below it with close. That button when pressed close will continue to the next page. If a user dont click the close button and decides to click outside the popup box it will not redirect the user. What function for javascript can i add if a user click outside the box it will redirect them without clicking the close button inside the box. using a osx-modal-content plugin
How its triggered*
<input type='button' name='osx' value='Click Here To Enter The Website!' class='osx demo'/></a>
plugin page (link)
OSX STYLE DIALOG ** OSX STYLE DIALOG ** OSX STYLE DIALOG **
http://www.ericmmartin.com/projects/simplemodal-demos/
This is something that i have for the close function**
close: function (d) {
var self = this; // this = SimpleModal object
d.container.animate(
{top:"-" + (d.container.height() + 20)},
500,
function () {
self.close(); // or $.modal.close();
}
This is how you can do stuff on close:
$("#element-id").modal({
onClose: function () {
window.location.href = "http://stackoverflow.com";
}
});
If you had an element added like:
// Load dialog on click
$('#basic-modal .basic').click(function (e) {
$('#basic-modal-content').modal();
return false;
});
Change that to
// Load dialog on click
$('#basic-modal .basic').click(function (e) {
$('#basic-modal-content').modal({
onClose: function () {
window.location.href = "http://stackoverflow.com";
}
});
return false;
});

Jquery Click Event Not Firing On First Click, but does on second click, why?

I've got a jQuery code, which
$("a.reply").click(function() {
//code
});
When I click the link with .reply class the first time, nothing happens. The second time I click, the code inside the click function works.
The link is being inserted on the page using PHP from a mysql database. so it's not being inserted dynamically.
Why is this happening? Any solution?
The BadASS Code:
$(function(){
//TextArea Max Width
var textmaxwidth = $('#wrapper').css('width');
//Initialize Focus ids To Different Initially
var oldcommentid = -1;
var newcommentid = -2;
//End Of initialization
$("a.reply").click(function() {
newcommentid = $(this).attr('id');
if (newcommentid == oldcommentid)
{
oldcommentid=newcommentid;
$("#comment_body").focus();
}
else
{
$('#comment_form').fadeOut(0, function(){$(this).remove()});
var commetformcode = $('<form id="comment_form" action="post_comment.php" method="post"><textarea name="comment_body" id="comment_body" class="added_comment_body" rows="2"></textarea> <input type="hidden" name="parent_id" id="parent_id" value="0"/> <div id="submit_button"> <input type="submit" value="Share"/><input type="button" id="cancelbutton" value="Cancel"/></div></form>');
commetformcode.hide().insertAfter($(this)).fadeIn(300);
//
var id = $(this).attr("id");
$("#parent_id").attr("value", id);
oldcommentid=newcommentid;
//dynamicformcreation function
dynarun();
//
}
return false;
});
dynarun();
function dynarun()
{
//Form Re-Run Functions
$('#comment_body').elastic();
texthover();
$("#comment_form input, select, button").uniform();
textareasizer();
$("#comment_body").focus();
$("abbr.timestamp").timeago();
return false;
}
//TextArea Resizer Function
function textareasizer(){$("#comment_body").css('max-width', textmaxwidth);return false;}
//Other Miscellaneous Functions
$('.comment-holder').hover(
function(event) {
$(this).addClass('highlight');
},
function(event) {
$('.comment-holder').removeClass('highlight');
}
);
function texthover()
{
$('.added_comment_body').hover(
function(event) {
$(this).parent().parent().addClass('highlight');
},
function(event) {
$('.comment-holder').removeClass('highlight');
}
);
return false;
}
});
This is a longshot, but are you running some sort of tracking script? Like webtrends or coremetrics (or even some of your own script, that's globally looking for all clicks)? I ran into a similar problem a while ago, where the initial-click was being captured by coremetrics. Just a thought.
Does it still happen if you comment out all your code and simply have an alert("hi") inside the click function?
Update
I think Sarfaz has the right idea, but I would use the document ready function like so
$(document).ready(function(){
$("a.reply").click(function() {
//code
});
});
I just ran into same problem and I resolved my problem by removing:
<script src="bootstrap.js"></script>
you can use bootstrap.min.js
Use Inline CSS for hiding div and use JS/jQuery to show . This way Jquery Click Event will Fire On First Click
<div class="about-block">
<div class="title">About us</div>
<div class="" id="content-text" style="display:none;">
<p>Show me.</p>
</div>
</div>
<script>
var x = document.getElementById("content-text");
jQuery( '.about-block' ).click(function() {
if (x.style.display === "none") {
x.style.display = "block";
} else {
x.style.display = "none";
}
});
</script>