简体   繁体   中英

Disable select option if input is certain day

How can I disable a select option field if day is a Saturday?

I have one input and one select .

<input type="text" name="date">11/15/2016

<select>
    <option value="car">Car</option>
    <option value="boat">Boat</option>
</select>

Here is my javascript:

if(???) {
   $("option[value='boat']").attr("disabled", "disabled");
}

What should i put in the if statement if the input date is a Saturday?

var today = new Date('2016-11-15');
if(today.getDay() == 6) {//6 is saturday
    ...// disable the option value
}

Convert it to a date object using selected value.

var selectedDate = new Date("11/15/2016");

// Use the get day method that will give you the day of the week.

if(selecteddate.getDay() === 6) {
     // your code
}

You can use:

  • Date.prototype.getUTCDay()

    The getUTCDay() method returns the day of the week in the specified date according to universal time, where 0 represents Sunday.

  • Date Instance new Date(dateString)

    Creates a JavaScript Date instance that represents a single moment in time. Date objects are based on a time value that is the number of milliseconds since 1 January, 1970 UTC.

  • prop() instead of attr() when dealing with boolean properties.

 var $dateInput = $("#dateInput"), $option = $("option[value='boat']"); $dateInput.on("change", function() { var date = new Date($dateInput.val()); if (date.getUTCDay() === 6) { $option.prop("disabled", true); } else { $option.prop("disabled", false); } console.log(date); console.log(date.getUTCDay()); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script> <input type="date" name="date" id="dateInput"> <select> <option value="car">Car</option> <option value="boat">Boat</option> </select> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM