2016-12-02 2 views
0

У меня есть страница, как на изображении ниже enter image description hereДля MM/DD/YYYY текста, отображать только тот текст, который не был введен пользователем

По моему требованию, пользователь может вводить цифры с клавиатуры, которая только на странице. Таким образом, поле ввода только для чтения.

Теперь я пытаюсь получить, когда пользователь начинает вводить месяц, тогда другой текст должен оставаться в текстовом поле до тех пор, пока пользователь не наберет его. например 05/DD/YYYY. И соответственно, текст будет скрыт.

Если я разместил местозаполнитель, тогда, когда пользователь начнет вводить цифры, весь текст ушел. Я не хочу этого. Поэтому я принял текст «MM/DD/YYYY» в отдельном span tag.

var Memory = "0", // initialise memory variable 
 
    Current = "",  // and value of Display ("current" value) 
 
    Operation = 0, // Records code for eg */etc. 
 
    MAXLENGTH = 8; // maximum number of digits before decimal! 
 

 
function format(input, format, sep) { 
 
    var output = ""; 
 
    var idx = 0; 
 
    for (var i = 0; i < format.length && idx < input.length; i++) { 
 
    output += input.substr(idx, format[i]); 
 
    if (idx + format[i] < input.length) output += sep; 
 
    idx += format[i]; 
 
    } 
 
    output += input.substr(idx); 
 
    return output; 
 
} 
 

 
function AddDigit(dig) {  //ADD A DIGIT TO DISPLAY (keep as 'Current') 
 
    if (Current.indexOf("!") == -1) { //if not already an error 
 
    if ((eval(Current) == undefined) && 
 
     (Current.indexOf(".") == -1)) { 
 
     Current = dig; 
 
     document.calc.display.focus(); 
 
    } else { 
 
     Current = Current + dig; 
 
     document.calc.display.focus(); 
 
    } 
 
    Current = Current.toLowerCase(); //FORCE LOWER CASE 
 
    } else { 
 
    Current = "Hint! Press 'Clear'"; //Help out, if error present. 
 
    } 
 

 
    if (Current.length > 0) { 
 
    Current = Current.replace(/\D/g, ""); 
 
    Current = format(Current, [2, 2, 4], "/"); 
 
    } 
 
    document.calc.display.value = Current.substring(0, 10); 
 
    document.getElementById("cursor").style.visibility = "hidden"; 
 
} 
 

 
function Clear() {    //CLEAR ENTRY 
 
    Current = ""; 
 
    document.calc.display.value = Current; 
 
    document.calc.display.focus(); 
 
    document.getElementById("cursor").style.visibility = "visible"; 
 
    //setInterval ("cursorAnimation()", 5000); 
 
} 
 

 
function backspace() { 
 
    Current = document.calc.display.value; 
 
    var num = Current; 
 
    Current = num.slice(0,num.length - 1); 
 
    document.calc.display.value = Current; 
 
    document.calc.display.focus(); 
 
    document.getElementById("cursor").style.visibility = "hidden"; 
 
} 
 

 
function cursorAnimation() { 
 
    $("#cursor").animate({ 
 
    opacity: 0 
 
    }, "fast", "swing").animate({ 
 
    opacity: 1 
 
    }, "fast", "swing"); 
 
} 
 
//---------------------------------------------------------------> 
 
$(document).ready(function() { 
 
    document.getElementById("cursor").style.visibility = "visible"; 
 
    //setInterval ("cursorAnimation()", 1000); 
 
});
.intxt1 { 
 
    padding: 16px; 
 
    border-radius: 3px; 
 
    /* border: 0; */ 
 
    width: 1017px; 
 
    border: 1px solid #000; 
 
    font-family: Droid Sans Mono; 
 
    background: #fff; 
 
} 
 
.txtplaceholder { 
 
    font-family: "Droid Sans Mono"; 
 
    color: #D7D7D7; 
 
    position: relative; 
 
    float: left; 
 
    left: 219px; 
 
    top: 17px; 
 
    z-index: 10 !important; 
 
    overflow: hidden; 
 
    white-space: nowrap; 
 
    text-overflow: ellipsis; 
 
    display: inline-block; 
 
} 
 
#cursor { 
 
    position: relative; 
 
    z-index: 1; 
 
    left: 32px; 
 
    top: 2px; 
 
    visibility: hidden; 
 
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.0/jquery.min.js"></script> 
 

 
<form Name="calc" method="post"> 
 
    <div style="position:relative"> 
 
    <span id="cursor">_</span> 
 
    <span class="txtplaceholder">MM/DD/YYYY</span> 
 
    <span style="z-index:100"> 
 
     <input class="intxt1" autocomplete="off" id="pt_dob" name="display" value="" type="text" readonly> 
 
    </span> 
 
    <button class="cancel-icon" type="reset" onClick="Clear()"></button> 
 
    </div> 
 
    <div class="num_keypad1" style=" margin-top:19px;"> 
 
    <!-- Screen and clear key --> 
 
    <div class="num_keys"> 
 
     <!-- operators and other keys --> 
 
     <span id="key1" onClick="AddDigit('1')">1</span> 
 
     <span id="key2" onClick="AddDigit('2')">2</span> 
 
     <span id="key3" onClick="AddDigit('3')">3</span> 
 
     <span id="key4" onClick="AddDigit('4')">4</span> 
 
     <span id="key5" onClick="AddDigit('5')">5</span> 
 
     <span id="key6" onClick="AddDigit('6')">6</span> 
 
     <span id="key7" onClick="AddDigit('7')">7</span> 
 
     <span id="key8" onClick="AddDigit('8')">8</span> 
 
     <span id="key9" onClick="AddDigit('9')">9</span> 
 
     <span id="key0" onClick="AddDigit('0')" style="width: 200px;">0</span> 
 
     <span id="keyback" class="clear" onClick="backspace()"> <div class="num_xBox">X</div></span> 
 
    </div> 
 
    </div> 
 
</form>

С выше Html кода я получаю ниже результат: enter image description here

Проблемы наступающем ниже:

  1. Мои цифры собираются под текстом " MM/DD/YYYY». Я не получаю, как мне получить мои цифры над этим текстом

  2. Как скрыть текст, который вводится пользователем, и отображать другие соответственно, например. «MM» должен скрываться, если пользователь вводит 05 и отображает другой текст, подобный этому «05/DD/YYYY».

Может ли кто-нибудь помочь мне в этом?

ПРИМЕЧАНИЕ: С типом ввода = даты или любыми другими плагинами я могу достичь выше функциональности, но мое требование отличается. Я должен достичь этого только с помощью HTML, CSS, JS.

+2

Эффект, который вы ищете, - это «маскирование ввода». Если вы google, есть сотни плагинов, которые сделают это для вас уже –

+0

Да, я знаю, что плагины, но мое требование отличается. Я не могу использовать плагины по умолчанию, так как мое поле ввода только для чтения, и пользователь должен вводить цифры с клавиатуры, которые указаны на странице. Я также упоминаю об этом и в моем вопросе. Поскольку я должен использовать предоставленную клавиатуру только для того, чтобы управлять всеми функциями Javascript (упоминается в вопросе). – anonymous

+0

Я прочитал ваш вопрос. Ни один из этих ограничений не влияет на использование маскирующего плагина. –

ответ

2

Я хотел бы использовать готовый встроенный сборщик данных для такого рода вещей, как это будет иметь всю проверку ошибок в построенной, чтобы обеспечить ввод даты в правильном формате.

Как вы это делаете, вы не можете проверить, действительно ли день действителен до тех пор, пока вы не введете месяц, и к этому времени пользователю придется отступить, и это будет очень медленный и неуклюжий процесс, который не очень удобный.

В любом случае, если вы сохраняете номерную площадку, вот как бы я это сделал.

  1. поставить дату в глобальном массиве
  2. имеют глобальный индекс счетчик
  3. добавлять и удалять значения на основе индекса счетчика

Ниже приводится очень быстрый пример выше

var dateBits = ["D", "D", "M", "M", "Y", "Y", "Y", "Y"], 
 
    letters = ["D", "D", "M", "M", "Y", "Y", "Y", "Y"], 
 
    input = document.getElementById('pt_dob'), 
 
    currentIndex = 0; 
 
    
 
function makeDate() { 
 
    return dateBits[0] + dateBits[1] + "/" + dateBits[2] + dateBits[3] + "/" + dateBits[4] + dateBits[5] + dateBits[6] + dateBits[7]; 
 
} 
 

 
function AddDigit(number) { 
 
    dateBits[currentIndex] = number; 
 
    if (currentIndex < 8) { 
 
    \t currentIndex++; 
 
    } 
 

 
    input.value = makeDate(); 
 
} 
 

 
function RemoveDigit() { 
 
    if (currentIndex > 0) { 
 
    \t currentIndex--; 
 
    } 
 
    
 
    dateBits[currentIndex] = letters[currentIndex]; 
 
    input.value = makeDate(); 
 
} 
 

 
function Clear() { 
 
    for (i = 0; i < letters.length; i++) { 
 
    dateBits[i] = letters[i]; 
 
    } 
 
    
 
    currentIndex = 0; 
 
    input.value = makeDate(); 
 
} 
 

 
input.value = makeDate(); // run this line onload or include this whole script at the bottom of the page to get your input to start with your text
.intxt1 { 
 
    padding: 16px; 
 
    border-radius: 3px; 
 
    /* border: 0; */ 
 
    width: 1017px; 
 
    border: 1px solid #000; 
 
    font-family: Droid Sans Mono; 
 
    background: #fff; 
 
} 
 

 
#cursor { 
 
    position: relative; 
 
    z-index: 1; 
 
    left: 32px; 
 
    top: 2px; 
 
    visibility: hidden; 
 
} 
 

 
.num_keys > span { 
 
    display: inline-flex; 
 
    width: 2em; 
 
    height: 2em; 
 
    align-items: center; 
 
    justify-content: center; 
 
    cursor: pointer; 
 
    border: 1px solid black; 
 
}
<form Name="calc" method="post"> 
 
    <div style="position:relative"><span id="cursor">_</span> 
 
    <span class="txtplaceholder">MM/DD/YYYY</span><span style="z-index:100"><input class="intxt1" autocomplete="off" id="pt_dob" name="display" value="" type="text" autocomplete="off" readonly></span> 
 
    <button class="cancel-icon" type="reset" onClick="Clear(); return false;">clear</button> 
 
    </div> 
 

 
    <div class="num_keypad1" style=" margin-top:19px;"> 
 
    <!-- Screen and clear key --> 
 

 
    <div class="num_keys"> 
 
     <!-- operators and other keys --> 
 
     <span id="key1" onClick="AddDigit('1')">1</span> 
 
     <span id="key2" onClick="AddDigit('2')">2</span> 
 
     <span id="key3" onClick="AddDigit('3')">3</span> 
 

 
     <span id="key4" onClick="AddDigit('4')">4</span> 
 
     <span id="key5" onClick="AddDigit('5')">5</span> 
 
     <span id="key6" onClick="AddDigit('6')">6</span> 
 

 
     <span id="key7" onClick="AddDigit('7')">7</span> 
 
     <span id="key8" onClick="AddDigit('8')">8</span> 
 
     <span id="key9" onClick="AddDigit('9')">9</span> 
 

 
     <span id="key0" onClick="AddDigit('0')" style="width: 200px;">0</span> 
 
     <span id="keyback" class="clear" onClick="RemoveDigit()"> <div class="num_xBox">X</div></span> 
 

 
    </div> 
 
    </div> 
 
</form>

+0

Спасибо за решение. Я применил ваш код на своей странице. При появлении проблем текст «DD/MM/YYYY» не появляется в моем текстовом поле при загрузке моей страницы. В вашем случае текст отображается, когда мы запускаем код. Как это происходит? И еще одна проблема заключается в функции «Очистить». Я сделал четкую функцию (Clear()) нажатием кнопки cross, которая находится в текстовом поле. Вы не упомянули эту функцию. Из-за «type = reset» его текст очистки, но когда я начинаю вводить новый номер, сохраняется предыдущая введенная дата. пожалуйста, помогите мне в функции «Очистить()», которая не должна храниться в предыдущей дате. – anonymous

+0

. Я отредактировал выше с комментариями о том, что начинается с вашего текста с текстом, четкой функцией (обратите внимание на изменение кнопки onclick) и прекратить ввод с автозаполнения (добавленный атрибут ввода) – Pete

-1

Если я понял все хорошо. Я думаю, что одним из решений является сохранение пользовательского ввода в скрытом поле. Затем получить этот вход для расщепленных цифр и возврат к видимой величине входного сигнала, который состоит из расщепленных значений и т.д.

0
var text = "DD/MM/YYYY"; 

$(".textbox").on("focus blur", function(){ 
    $(".wrapper").toggleClass("focused"); 
}); 

$(".wrapper").click(function (e) { 
    if (e.target == this) { 
     var b = $(".textbox", this).focus(); 
    } 
}).trigger("click"); 

$(".wrapper > .textbox").on("input", function(){ 
    var ipt = $(this).text().replace(/\u00A0/g, " "); 
    $(".gray").text(text.substr(ipt.length, text.length)); 
}).trigger("input"); 

проверки этой скрипка http://jsfiddle.net/7sD2r/22/

Смежные вопросы