shorten code when use matchmedia - javascript

I want to use matchmedia.addlistener to check windows size, my button event looks like this
$('button').click(function(){
if(this.attr('aria-expanded') === 'false'){
$this.attr('aria-expanded', true).next().fadeOut();
}else{
$this.attr('aria-expanded', false).next().fadeIn();
}
});
if I use matchmedia, I will need to do it this way
minWidth768 = window.matchMedia('(min-width: 768px)');
if(minWidth768.matches){
$('button').click(function(){
if(this.attr('aria-expanded') === 'false'){
$this.attr('aria-expanded', true).next().slideUp();
}else{
$this.attr('aria-expanded', false).next().slideDown();
}
});
}else{
$('button').click(function(){
if(this.attr('aria-expanded') === 'false'){
$this.attr('aria-expanded', true).next().fadeOut();
}else{
$this.attr('aria-expanded', false).next().fadeIn();
}
});
}
If i want to add an addListener, so I need to repeat my code again.
minWidth768.addListener(function(media) {
if(media.matches){
//repeat;
}else{
//repeat;
}
});
Is there a way I could make my code shorter, and make code looks nice and easy to maintain?

You can make a function and then call that function wherever you need.
Eg.
function matchMedia(){
//do stuff here
}
//now call where you want
if(true){
matchMedia();
}
But note: if you want to call the function inside the function parameter then you no need to use parenthesis like below is an example:
setTimeout(matchMedia, 400);// don't do matchMedia()

Related

How to return a value from a jQuery event function to the parent function?

I have a jQuery event inside a JavaScript function. I've already read that you cannot access the inner function. However, I would like to know how to adjust my code so that the parent function returns true or false depending on the jQuery function.
function validate() {
$("#button").on('click', function(){
var input = document.forms["formular"]["text"].value;
if (input == "") {
return false;
}
});
if(onclickfunction() == true){
return true;
}
else{
return false
}
}
validate();
Or can you recommend a different approach?
Not sure what this code is supposed to do, because calling validate only creates the event listener without actually executing it. But what you can do is to prevent the default action when you need, which is how validation is usually implemented:
$("#button").on('click', function(){
var input = document.forms["formular"]["text"].value;
yourSecondFunction(input !== "");
});
function yourSecondFunction(inputIsValid) {
// Do your magic here
}

jQuery AddClass method not working

I am trying to add a new class to a "submit" input after checking that other form elements are filled up. I´m using .keyup() to trigger the function. This function changes the property "disabled" to "false", but after that it does not add the class " animate pulse ". Thanks!
<script> //checks that all fields are completed before enabling submit button
$(document).ready(function() {
$('input[type="submit"]').prop('disabled', true);
$('input[type="text"],input[type="email"],input[type="password"]').keyup(function() {
if($('#log_password').val() != '' && $('#log_email').val() != '') {
$('input[type="submit"]').prop('disabled', false).addClass("animated pulse");
}
else{
$('input[type="submit"]').prop('disabled',true);
}
});
});
</script>
Your problem is how are you using the prop() function since this function does not return anything, and the addClass() function needs to be called from a jQuery object.
As you can see on the prop defintion it says:
Returns: Anything
This practice is called Chaining and in order to do Chaining functions those functions should return a jQuery Object.
More info
You can rewrite your line of code by something like this:
$('input[type="submit"]')
.addClass('animated pulse')
.prop('disabled', false);
Add seperately the addclass()
$(document).ready(function() {
$('input[type="submit"]').prop('disabled', true);
$('input[type="text"],input[type="email"],input[type="password"]').keyup(function() {
if($('#log_password').val() != '' && $('#log_email').val() != '')
{
$('input[type="submit"]').prop('disabled', false);
//add in next line
$('input[type="submit"]').addClass('animated pulse');
}
else{
$('input[type="submit"]').prop('disabled',true);
}
});
});

jQuery - Enable/Disable a button following checkboxes state

I'm using ASP.NET MVC 4 to develop a web app. I have a page which contains a submit button which should be enabled only if one of my two checkboxes (or both of them) is (are) enabled. The thing is, I'm trying to add an "or" operator in the following script but it does not give me what I want. So, here's my script :
The jQuery sample
And this is the part I'd like to improve :
$(document).ready(function() {
the_terms = $("#the-terms");
the_terms2 = $("#the-terms2");
the_terms.click(function() {
if ($(this).is(":checked")){
$("#submitBtn").removeAttr("disabled");
} else {
$("#submitBtn").attr("disabled", "disabled");
}
});
});
And I can't find a way to tell my document "Okay, if one of these 2 checkboxes (or both of them) is (are) checked, we can press on the button. If not, don't allow it".
Any idea guys?
It can be done with:
Fiddle
$('.checkbox').change(function(){
$('#submitBtn').prop('disabled', !$('.checkbox:checked').length > 0)
});
Note:
This find the checkboxes by class name checkbox so it will work with two checkboxes, whereas your original code is looking at a single checkbox via its ID.
Use the change event not click.
Simply use
$(".checkbox").click(function() {
$("#submitBtn").prop("disabled", !$('.checkbox:checked').length);
});
DEMO
$(document).ready(function() {
the_terms = $("#the-terms");
the_terms2 = $("#the-terms2");
$('.checkbox').change(function(){
$("#submitBtn").prop("disabled", !(the_terms.is(":checked") || the_terms2.is(":checked")));
});
});
// Make a function to be called on onload or on click
function checkTerm() {
jQuery('input[type="submit"]').attr('disabled',!jQuery('input.term:checked').length > 0 ) ;
}
// Call the function on load
$(document).ready(checkTerm) ;
// And call it on check change
jQuery(document).on('change','input.term',checkTerm) ;
Try below modified script , please check if it works as you want.
$(document).ready(function() {
the_terms = $("#the-terms");
the_terms2 = $("#the-terms2");
if(the_terms.is(":checked") || the_terms2.is(":checked"))
{
$("#submitBtn").removeAttr("disabled");
}
else
{
$("#submitBtn").attr("disabled", "disabled");
}
the_terms.click(function() {
if ($(this).is(":checked") || the_terms2.is(":checked")){
$("#submitBtn").removeAttr("disabled");
} else {
$("#submitBtn").attr("disabled", "disabled");
}
});
the_terms2.click(function() {
if ($(this).is(":checked") || the_terms.is(":checked") ){
$("#submitBtn").removeAttr("disabled");
} else {
$("#submitBtn").attr("disabled", "disabled");
}
});
});

How to check button is clicked inside a function

My Scenerio:
I have a function:
The function Addprocedure() is called on onclick of Addprocedure button.
In this function i want to check if btnAddSelectedProcedures is clicked then do Something else do nothing
function Addprocedure(){
if()// Check if Button is clicked, button id = `btnAddSelectedProcedures`
{
//Do Something
}
else{
//Do nothing
}
}
Save the state of the button in a variable.
Define btnClicked globally as false. When btnAddSelectedProcedures is clicked, change btnClicked to true. When you call Addprocedure check if btnClicked variable is true and if so, that button has been clicked.
Example:
var btnClicked = false;
function Addprocedure() {
if (btnClicked) {
//Do something...
} else {
//Do something else...
}
}
$('BUTTON[name="btnAddSelectedProcedures"]').click(function() {
btnClicked = true;
});
$('BUTTON[name="Addprocedure"]').click(function() {
Addprocedure();
});
Try
$('#btnAddSelectedProcedures').click(function(){
$(this).data('clicked', true)
})
then
function Addprocedure(){
if($('#btnAddSelectedProcedures').data('clicked')){
//clicked
} else {
//not clicked
}
}
It is simple, check id
function Addprocedure(){
if(this.id === 'btnAddSelectedProcedures')// Check if Button is clicked, button id = `btnAddSelectedProcedures`
{
//Do Something
}
else{
//Do nothing
}
}
One possiblity,
You can declare a global variable and mark it as true when yourbtnAddSelectedProcedures clicked and use that to check in your Addprocedure() function.
var isButton1Clicked =false;
onButton1Click{
isButton1Clicked ==true
}
onButton2Click{
if(isButton1Clicked){
//procedd
}
}
I suggest to avoid using global var. Use a class instead ( or You can set data-* attribute as well )
$('#btnAddSelectedProcedures').on('click', function(){
//$(this).toggleClass('clicked');
if(! $(this).hasClass('clicked') ){ //allows you to set only once the class
$(this).addClass('clicked');
}
Addprocedure();
});
then
function Addprocedure(){
if( $("#btnAddSelectedProcedures").hasClass('clicked') ) //I guess you can call $(this) too
{
//Do Something
}
else{
//Do nothing
}
}
I used toggleClass because I think you want to check every time if the user clicked .
Use addClass in the other way.
<button id="1" onClick="Addprocedure(this.id)">B1</button>
and then
function Addprocedure(clicked_id)
{
alert(clicked_id);
}

javascript run function if everything is checked, filled, selected

I have a problem with javscript. I was wonder is it possible to create something like this in javascript:
<script>
function all_is_filled(){
if($('input[type=checkbox]').checked && document.getElementById('text_field').value!="" )
{
//do something...
}
}
</script>
So when someone check checkbox and fill text_field then this do something...Is there a way to do it?
This will work:
function all_is_filled() {
if ($('input[type=checkbox]').prop('checked') == true && $('#text_field').value != "") {
//do something...
}
};
$('#myform').on('change', function () {
all_is_filled()
});
I added a listen function to call all_is_filled() on change, but you can also put it onsubmit.
Simple demo HERE

Categories