0

I am having the following JQuery function that is working properly:

$(function () {
    $('#accmenu').change(function() {
        $(".insightsgraphs div").hide();
        $(".insightsoptions input").removeClass("green");
        $("#newLikes").one('click', function () {
            $.ajax({type:'GET', url: 'newLikes.php', data:$('#ChartsForm').serialize(), success:
                function(response) {
                    var json = response.replace(/"/g,'');
                    json = "[" + json + "]";
                    json = json.replace(/'/g,'"');
                    var myData = JSON.parse(json);
                    var myChart = new JSChart('dailyNewLikes', 'line');
                    myChart.setDataArray(myData);
                    myChart.setAxisNameX('');
                    myChart.setAxisNameY('');
                    myChart.setAxisValuesColorX('#FFFFFF');
                    myChart.setSize(470, 235);
                    myChart.setTitle('Daily New Likes');
                    myChart.draw();
                }});
            return false;
        });
        $("#unlikes").one('click', function () {
            $.ajax({type:'GET', url: 'unlikes.php', data:$('#ChartsForm').serialize(), success:
                function(response) {
                    $("#dailyUnlikes").html(response);
                }});
            return false;
        });
    });
    $("#newLikes").on('click', function(){
        $(this).toggleClass('green');
        $('#dailyNewLikes').toggle();
        return false;
    });
    $("#unlikes").on('click', function(){
        $(this).toggleClass('green');
        $('#dailyUnlikes').toggle();
        return false;
    });
});

but I want to create a condition: if one of the following two date inputs:

var since = $('#dateoptions input[name="since_date"]').val();
var until = $('#dateoptions input[name="until_date"]').val();

is empty I want to receive an alert and the .one() function to be executed only when the conditions are met. For example when I click on one of the button without the date inputs in place I want to receive an alert like alert("One of the date or both missing") for example and after I choose the dates and press the button again to execute the .one() function like in the above example. I hope I make myself clear enough. I know that I can use something like:

if (until == "" || since == "") {
    alert("One of the date or both missing")
} else {}

but my tries so far was no success. Probably I didn't place the condition where it should... Also it is possible also with an alert the inputs to be focused, highlighted or something similar?

EDIT: Here's a fiddle with it: http://jsfiddle.net/DanielaVaduva/ueA7R/6/ I replace the ajax call with something else without to modify the flow.

Daniela costina Vaduva
  • 1,717
  • 4
  • 19
  • 22
  • That should work, can you provide a demo on http://jsfiddle.net? – undefined May 13 '13 at 13:17
  • Did you tried `if (until.trim().length === 0 || since.trim().length === 0)`? – DaGLiMiOuX May 13 '13 at 13:17
  • Not the if statement is the problem but where to put it is the issue because if I put it before the ajax call it will execute the `.one()` without the get request if the inputs are missing and the second time I press the button it not make the request anymore because the `.one()` has been already executed once. I need maybe something like a reset `.one()` counter or so? – Daniela costina Vaduva May 13 '13 at 13:21
  • @DanielacostinaVaduva You have to put it at each `onclick` function before calling ajax. If it's length is 0, then `alert(...)` else `ajax({...})`. Is that what you were asking? – DaGLiMiOuX May 13 '13 at 13:24
  • you could use `.on()` instead of `.one()` and then after the validation and the `data` is successfully sent you use `.off()` to unbind the event. – Spokey May 13 '13 at 13:26
  • If i use `.off()` it will also unbind the toggle that I use to change the button color and to show/hide the div? – Daniela costina Vaduva May 13 '13 at 13:28
  • @Spokey if im not wrong, `.one()` executes atleast one time, but if you attach an event with `.on()` and then unattach the event with `.off()` it will only be executed one time and never more – DaGLiMiOuX May 13 '13 at 13:28
  • @DanielacostinaVaduva with `.off()` you can remove only the function you want to remove, but if you have annonymous functions, they dont have a name, so you cant say to jQuery 'Remove the annonymous function of that element'. You will have to separate your function into a defined function with his name to remove only the function that you defined. Here you have an example http://api.jquery.com/off/ – DaGLiMiOuX May 13 '13 at 13:36
  • @DaGLiMiOuX thank you for the guidance but I don't think this could solve my issue but is very good information to know from now on. – Daniela costina Vaduva May 13 '13 at 13:43
  • @DanielacostinaVaduva You are welcome. Anyway I'm still thinking what you are trying to do and where do you get the 'error'. Did you tried this on your `.one(...)` function? `function() {if (until.trim().length === 0 || since.trim().length === 0) {alert(...)} else {$.ajax({...})}}` – DaGLiMiOuX May 13 '13 at 13:46
  • @DaGLiMiOuX I've tried what you said and I get the following: if I got empty inputs I receive the alert (the button is becoming green because the `.on()` that is outside `.change()` is executed) and after I select the dates the get request is not send anymore (the green/red toggle part is working fine because is outside the `.change()`). I have to use `.change()` in my application... – Daniela costina Vaduva May 13 '13 at 13:58
  • @DanielacostinaVaduva In around 1 hour I will go back home, if you don't have your problem solved when I arrive, I will try your code at my home and try to find why it is not working. Added to favourites. – DaGLiMiOuX May 13 '13 at 14:17
  • I will make a jsfiddle meanwhile :) – Daniela costina Vaduva May 13 '13 at 14:18
  • Here it is: http://jsfiddle.net/DanielaVaduva/ueA7R/6/ – Daniela costina Vaduva May 13 '13 at 14:34
  • @DanielacostinaVaduva I don't know if you already solved your problem. I tried many different ways to try to get what do you want to do with this code that you posted at jsfiddle. Sorry, but I don't know what do you want and your code is a bit strange :S. Also, you are returning false after every function... you dont really need to `return` something when your function ends. If you tell me more specificly what do you want/spect, I can give another try... It's not really clear. One thing that I would like to know: When do you want to trigger if dates are empty, `.change(...)` or `one(...)`? – DaGLiMiOuX May 13 '13 at 16:49
  • @DanielacostinaVaduva see updated part of my answer – DaGLiMiOuX May 14 '13 at 07:22

2 Answers2

1

Try checking your values with:

if (until.trim().length === 0 || since.trim().length === 0) {
    //TODO here
}

I suggest you that check your name attribute in your inputs and check that it's the same that you use when you are retrieving the values of the inputs.

If it still not working, try some 'debugging' like:

console.log(since);

And check if it is getting your value properly.

UPDATE

I don't know if you wanted this (demo). If your dates are empty, it will not work. AJAX call will not work on JsFiddle, because you are using a .serialize() and it sends the information via URL, as a GET type and you need to send it as POST. It doesn't matter. If you already prepared your server to recieve a GET method, it will work.

Also, I must add that if you want to change color ONLY if the AJAX was success, you must add your change color function as I used on the demo and if you want to check your date every time you want to send information to server, change .one() function into .on() function and remove the function after the AJAX success with:

$('#myimage').click(function() { return false; }); // Adds another click event
$('#myimage').off('click');
$('#myimage').on('click.mynamespace', function() { /* Do stuff */ });
$('#myimage').off('click.mynamespace');

(More info about removing a function here);

I hope this will help you atleast on the way you want to do. Leave a comment if it is not what you wanted.

Community
  • 1
  • 1
DaGLiMiOuX
  • 861
  • 9
  • 26
1

I'm not sure if I understood the issue exactly but.. you can check this >>

Fiddle Demo

HTML

Add IDs to the date fields like

 <input id="until" type="date" name="until_date" value="Until date">
 <input id="since" type="date" name="since_date" value="Since date">

And just for highlighting the required dates >>

CSS

.req{
   border:2px red solid;
}
.required{
   color:red;
   font-size: 0.8em;
   font-style:italic;
}

jQuery

$(function () {
     //removing the highlighting class on change
      $('#until').change(function() {
         $(this).removeClass('req').next('.required').remove();
      });
      $('#since').change(function() {
         $(this).removeClass('req').next('.required').remove();
      });

    $('#accmenu').change(function() {
      var dSince= $('#since').val();
      var dUntil= $('#until').val();
      if(dSince=='' || dUntil==''){
         alert('You MUST select Both dates!');
         $(this).val(0); // Set the menu to the default 
         //Adding the Highlight and focus
         if(dSince==''){
             $('#since').addClass('req').after('<span class="required">- required *</span>').focus();}
         if(dUntil==''){
             $('#until').addClass('req').after('<span class="required">- required *</span>').focus();}           
      }else{
         $(".insightsgraphs div").hide();
         $(".insightsoptions input").removeClass("green");
         $("#newLikes").one('click', function () {
             $("#dailyNewLikes").html('</p>Test daily new likes</p>');
             return false;
          });
         $("#unlikes").one('click', function () {
              $("#dailyUnlikes").html('</p>Test daily unlikes</p>');
             return false;
         });
       }  //End of the if statement
   });
   $("#newLikes").on('click', function(){
      $(this).toggleClass('green');
      $('#dailyNewLikes').toggle();
      return false;
   });
   $("#unlikes").on('click', function(){
         $(this).toggleClass('green');
      $('#dailyUnlikes').toggle();
      return false;
   });

});

Thus whenever an option from the accmenu gets selected, it will check for the values of the two DATEs, if both or any is blank, it won't execute the function.

Mi-Creativity
  • 9,101
  • 10
  • 33
  • 44