IT

사용자 입력을 허용하지 않는 텍스트 입력이있는 jQuery Datepicker

lottoking 2020. 6. 22. 07:33
반응형

사용자 입력을 허용하지 않는 텍스트 입력이있는 jQuery Datepicker


텍스트 상자 입력과 함께 jQuery Datepicker를 어떻게 사용합니까?

$("#my_txtbox").datepicker({
  // options
});

사용자가 텍스트 상자에 임의의 텍스트를 입력 할 수 없습니다. 텍스트 상자에 포커스가 있거나 사용자가 클릭 할 때 Datepicker가 팝업되기를 원하지만 텍스트 상자가 키보드 (복사 및 붙여 넣기 또는 기타)를 사용하는 사용자 입력을 무시하고 싶습니다. Datepicker 달력에서 독점적으로 텍스트 상자를 채우고 싶습니다.

이게 가능해?

jQuery 1.2.6
날짜 선택기 1.5.2


텍스트 입력 에서 readonly 속성 을 사용할 수 있어야하며 jQuery는 여전히 내용을 편집 할 수 있습니다.

<input type='text' id='foo' readonly='true'>

내 경험을 바탕으로 Adhip Gupta가 제안한 솔루션을 추천합니다.

$("#my_txtbox").attr( 'readOnly' , 'true' );

다음 코드는 사용자가 새 문자를 입력 없지만 문자를 삭제할 수 있도록합니다.

$("#my_txtbox").keypress(function(event) {event.preventDefault();});

또한 JavaScript를 사용하지 않는 사람들에게는 양식을 쓸모 없게 만듭니다.

<input type="text" readonly="true" />

시험

$("#my_txtbox").keypress(function(event) {event.preventDefault();});

여러 곳에서 날짜 선택기를 재사용하는 경우 다음과 같은 방법으로 JavaScript를 통해 텍스트 상자를 수정하는 것이 좋습니다.

$("#my_txtbox").attr( 'readOnly' , 'true' );

날짜 선택기를 초기화 한 장소 바로 앞 / 뒤


<input type="text" readonly="true" />

포스트 백 후 텍스트 상자의 값이 손실됩니다.

오히려 완벽하게 작동하는 Brad8118의 제안을 사용해야합니다.

$("#my_txtbox").keypress(function(event) {event.preventDefault();});

편집 : IE에서 작동하게하려면 'keypress'대신 'keydown'을 사용하십시오.


$("#txtfromdate").datepicker({         
    numberOfMonths: 2,
    maxDate: 0,               
    dateFormat: 'dd-M-yy'       
}).attr('readonly', 'readonly');

jquery에 readonly 속성을 추가하십시오.


날짜 선택기를 초기화 한 후 :

        $(".project-date").datepicker({
            dateFormat: 'd M yy'
        });

        $(".project-date").keydown(false);

게인 포커스에서 datepicker가 팝업되도록하려면 :

$(".selector").datepicker({ showOn: 'both' })

사용자 입력을 원하지 않으면 입력 필드에 추가하십시오

<input type="text" name="date" readonly="readonly" />

이 작업을 수행 할 수있는 두 가지 옵션이 있습니다. (내가 아는 한)

  1. 옵션 A : 텍스트 필드를 읽기 전용으로 만드십시오. 다음과 같이 수행 할 수 있습니다.

  2. 옵션 B : 커서 초점을 변경하십시오. 흐림 효과를 설정하십시오. onfocus="this.blur()"날짜 선택기 텍스트 필드에 속성 설정하여 수행 할 수 있습니다 .

전의: <input type="text" name="currentDate" id="currentDate" onfocus="this.blur()" readonly/>


방금 이것을 만났으므로 여기에서 공유하고 있습니다. 옵션은 다음과 같습니다

https://eonasdan.github.io/bootstrap-datetimepicker/Options/#ignorereadonly

코드는 다음과 같습니다.

HTML

<br/>
<!-- padding for jsfiddle -->
<div class="input-group date" id="arrival_date_div">
  <input type="text" class="form-control" id="arrival_date" name="arrival_date" required readonly="readonly" />
  <span class="input-group-addon">
    <span class="glyphicon-calendar glyphicon"></span>
  </span>
</div>

JS

$('#arrival_date_div').datetimepicker({
  format: "YYYY-MM-DD",
  ignoreReadonly: true
});

바이올린은 다음과 같습니다.

http://jsfiddle.net/matbaric/wh1cb6cy/

bootstrap-datetimepicker.js의 내 버전은 4.17.45입니다.


데모 는 달력을 텍스트 필드 위에 놓아 입력 할 수 없도록합니다. HTML에서 입력 필드를 읽기 전용으로 설정하여 확실하게 설정할 수도 있습니다.

<input type="text" readonly="true" />

HTML

<input class="date-input" type="text" readonly="readonly" />

CSS

.date-input {
      background-color: white;
      cursor: pointer;
}

I know this thread is old, but for others who encounter the same problem, that implement @Brad8118 solution (which i prefer, because if you choose to make the input readonly then the user will not be able to delete the date value inserted from datepicker if he chooses) and also need to prevent the user from pasting a value (as @ErikPhilips suggested to be needed), I let this addition here, which worked for me: $("#my_txtbox").bind('paste',function(e) { e.preventDefault(); //disable paste }); from here https://www.dotnettricks.com/learn/jquery/disable-cut-copy-and-paste-in-textbox-using-jquery-javascript and the whole specific script used by me (using fengyuanchen/datepicker plugin instead):

$('[data-toggle="datepicker"]').datepicker({
    autoHide: true,
    pick: function (e) {
        e.preventDefault();
        $(this).val($(this).datepicker('getDate', true));
    }
}).keypress(function(event) {
    event.preventDefault(); // prevent keyboard writing but allowing value deletion
}).bind('paste',function(e) {
    e.preventDefault()
}); //disable paste;

I've found that the jQuery Calendar plugin, for me at least, in general just works better for selecting dates.


$('.date').each(function (e) {
    if ($(this).attr('disabled') != 'disabled') {
        $(this).attr('readOnly', 'true');
        $(this).css('cursor', 'pointer');
        $(this).css('color', '#5f5f5f');
    }
});

Here is your answer which is way to solve.You do not want to use jquery when you restricted the user input in textbox control.

<input type="text" id="my_txtbox" readonly />  <!--HTML5-->

<input type="text" id="my_txtbox" readonly="true"/>

$("#my_txtbox").prop('readonly', true)

worked like a charm..


Instead of using textbox you can use button also. Works best for me, where I don't want users to write date manually.

enter image description here


I know this question is already answered, and most suggested to use readonly attribure.
I just want to share my scenario and answer.

After adding readonly attribute to my HTML Element, I faced issue that I am not able to make this attribute as required dynamically.
Even tried setting as both readonly and required at HTML creation time.

So I will suggest do not use readonly if you want to set it as required also.

Instead use

$("#my_txtbox").datepicker({
    // options
});

$("#my_txtbox").keypress(function(event) {
    return ( ( event.keyCode || event.which ) === 9 ? true : false );
});

This allow to press tab key only.
You can add more keycodes which you want to bypass.

I below code since I have added both readonly and required it still submits the form.
After removing readonly it works properly.

https://jsfiddle.net/shantaram/hd9o7eor/

$(function() {
  $('#id-checkbox').change( function(){
  	$('#id-input3').prop('required', $(this).is(':checked'));
  });
  $('#id-input3').datepicker();
  $("#id-input3").keypress(function(event) {
    return ( ( event.keyCode || event.which ) === 9 ? true : false );
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>

<link href="https://code.jquery.com/ui/jquery-ui-git.css" rel="stylesheet"/>

<form action='https://jsfiddle.net/'>
Name:  <input type="text" name='xyz' id='id-input3' readonly='true' required='true'> 
    <input type='checkbox' id='id-checkbox'> Required <br>
    <br>
    <input type='submit' value='Submit'>
</form>


replace the ID of time picker: IDofDatetimePicker to your id.

This will prevent the user from entering any further keyboard inputs but still, the user will be able to access the time popup.

$("#my_txtbox").keypress(function(event) {event.preventDefault();});

Try this source: https://github.com/jonthornton/jquery-timepicker/issues/109


This question has a lot of older answers and readonly seems to be the generally accepted solution. I believe the better approach in modern browsers is to use the inputmode="none" in the HTML input tag:

<input type="text" ... inputmode="none" />

or, if you prefer to do it in script:

$(selector).attr('inputmode', 'none');

I haven't tested it extensively, but it is working well on the Android setups I have used it with.


Instead of adding readonly you can also use onkeypress="return false;"


Or you could, for example, use a hidden field to store the value...

        <asp:HiddenField ID="hfDay" runat="server" />

and in the $("#my_txtbox").datepicker({ options:

        onSelect: function (dateText, inst) {
            $("#<% =hfDay.ClientID %>").val(dateText);
        }

If you want the user to select a date from the datepicker but you dont want the user to type inside the textbox then use the following code :

<script type="text/javascript">
$(function () {
    $("#datepicker").datepicker({ maxDate: "-1D" }).attr('readonly', 'readonly');
    $("#datepicker").readonlyDatepicker(true);

});

참고URL : https://stackoverflow.com/questions/153759/jquery-datepicker-with-text-input-that-doesnt-allow-user-input

반응형