0

I have 3 <select> elements for Day, Month and Year. And I am trying to get them validated with jQuery.

<li class="pseudo_day">
    <select class="mod_day" name="day">
        <option disabled selected>Day</option>
        <option value="1">1</option>
        <option value="2">2</option>
        <option value="3">3</option>
        <option value="4">4</option>
        <option value="5">5</option>
        <option value="6">6</option>
        <option value="7">7</option>
        <option value="8">8</option>
        <option value="9">9</option>
        <option value="10">10</option>
    </select>
</li>

Like so:

$("select[name=day], select[name=month], select[name=year]").on('change', function(){

    var select_day = $("select[name=day]").val();
    var select_month = $("select[name=month]").val();
    var select_year = $("select[name=year]").val();

        if ( select_day.length !== 0 ) { console.log("Valid - " + select_day); }
        else { console.log("Not valid!"); }
}); 

This is the error I get when I run the jQuery code:

Uncaught TypeError: Cannot read property 'length' of null
    at HTMLSelectElement.<anonymous> (new_user.html:242)
    at HTMLSelectElement.dispatch (jquery-3.2.1.min.js:3)
    at HTMLSelectElement.q.handle (jquery-3.2.1.min.js:3)

What am I doing wrong here?

3
  • Why not just use a datepicker plugin? It has the benefits of avoiding this problem completely, plus it looks a lot better. Commented Oct 8, 2017 at 17:10
  • Yes, don't reinvent the wheel. I once used this and was quite happy with it. Commented Oct 8, 2017 at 17:12
  • I've tried it. But it didn't for me in this case. Commented Oct 8, 2017 at 17:15

2 Answers 2

1

When no option is selected select[name=day] then $("select[name=day]").val() is null and you get the error, as we cannot read property 'length' of null. We can resolve it in many ways, but one way you can do it like:

var select_day = $("select[name=day]").val() || '';
var select_month = $("select[name=month]").val() || '';
var select_year = $("select[name=year]").val() || '';
Sign up to request clarification or add additional context in comments.

1 Comment

Perfect! Thanks!
1

The problem is that on every change event for your selects you are trying to get all the values. And if, for example, you changed only year then month and day are undefined. And then you are trying to manipulate day - select_day.length - by taking its length. You can use what palash suggested or check existence and type like

if (select_day && typeof select_day === 'string' ) ...

This is true only if select_day is a not empty string.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.