Question

I'm using $.trim to check if the inputs are empty, if so, nothing should happen. If they're not empty then the form should be submitted.

This is the variable where the condition is located:

var save = $("<input type='button' value='Save' />").on('click',function() {
        if(!$.trim(name)==''||!$.trim(degree)==''||!$.trim(dateFrom)==''||!$.trim(dateTo)=='') {
            $("#list").append("<li>Name: "+$('#elem1').val()+
                             "<br>Degree: "+$('#elem2').val()+
                             "<br>Date From: "+$('#elem3').val()+
                             "<br>Date To: "+$('#elem4').val()+
                             "</li>");
            cancel.click();
        } else {}
    });

Please take a look to the code on jsFiddle here: http://jsfiddle.net/vrpWu/

  • Click on "Add another"

Note that it works without the if condition, why is this happening? I've readed everywhere but looks like my code is not wrong.

Was it helpful?

Solution

First, you have to get the values when you actually click the save button, not before, as then the values will always be empty strings

var save = $("<input type='submit' value='Save' />").on('click', function () {
    var name     = $("#elem1").val();
    var degree   = $("#elem2").val();
    var dateFrom = $("#elem3").val();
    var dateTo   = $("#elem4").val();

    if (!($.trim(name) == '' || $.trim(degree) == '' || $.trim(dateFrom) == '' || $.trim(dateTo) == '')) {
        console.log('test')
        $("#list").append("<li>Name1: " + $('#elem1').val() +
            "<br>Name2: " + $('#elem2').val() +
            "<br>Name3: " + $('#elem3').val() +
            "<br>Name4: " + $('#elem4').val() +
            "</li>");
        cancel.click();
    } else {
        console.log('no')
    }
});

then you should note that things work a little differently when you negate the variables and use OR

You can either negate the whole thing at once

if (! ($.trim(name)==''||$.trim(degree)==''||$.trim(dateFrom)==''||$.trim(dateTo)=='')) {

or use AND instead

if (!$.trim(name)=='' && !$.trim(degree)=='' && !$.trim(dateFrom)=='' ... etc

FIDDLE

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top