2016-01-21 147 views
6

我想知道这是否是可能的,如果期间迹象.从文本删除打的事件。 例如我有一个文本框#Quantity这需要数值作为输入与周期符号如何检查句号(。)是否从jQuery文本框中的单词中删除?

enter image description here

和我有一个下拉控制#unitValue,其具有三个选项

我已经成功击中周期的事件签署.按键如下

$("#Quantity").keypress(function(e) { 
    if(e.which == 46) { 
     //successfully disabled Gram in Unit 
    } 
}); 

现在我想如果周期符号.从文本框中取出,以便能够在下降“革兰氏阴性”选项下。 我有一个想法,但不这样做,如果这是正确的。 思想是: - 上的任意键按下每个字母添加到一个数组,然后在退格键按压,我检查是否在阵列索引字母是周期符号.与否,如果它是,则.标志使能在“革兰氏阴性”

任何帮助将不胜感激

谢谢

+0

嗨需要一些更清晰 – Help

+0

'onfocusout'检查文本框的值有'.'与否。并将属性设置为启用或禁用。 –

回答

5

JS Fiddle - updated - 使用.prop()代替

// attach the functionality on multi events 
 
$('#inpt').on('keypress input change', function() { 
 
    var Gram = $('#slct').children('[value="1"]'); 
 

 
    // if the indexOf "." is > -1, then there's a dot 
 
    if ($(this).val().indexOf('.') > -1) { 
 

 
    // disable the Gram option 
 
    Gram.prop('disabled', true); 
 

 
    // ====================== this part was added by @SarathChandra 
 
    // reset the drop down if Gram option was selected 
 
    if ($('#slct').val() === "1" || $('#slct').val() === null) { 
 
     $('#slct').val("0"); 
 
    } 
 
     // ====================== @SarathChandra Thank you for the improvement 
 

 
    } else { 
 

 
    // if it the dot was removed, we set the disabled prop to false 
 
    Gram.prop('disabled', false); 
 
    } 
 
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script> 
 
<input id="inpt" type="text"> 
 
<select id="slct"> 
 
    <option value="0">- select -</option> 
 
    <option value="1">Gram</option> 
 
    <option value="2">Kilo</option> 
 
    <option value="3">Quntal</option> 
 
</select>


编辑:由于@SarathChandra添加了这几行:

if($('#slct').val() == "1" || $('#slct').val() == null){ 
     $('#slct').val("0"); 
} 

要解决它,当输入的数值没有包含.,和革兰氏选择THEN期为增加,它重置下拉。

+0

@SarathChandra,谢谢你的改进! –

0

我建议存储先前输入的文本,并将其与在输入的实际文本:

... 
var prevText = ""; 

$("#Quantity").keypress(function(e) { 
    var actualText = $(e.target).text(); 
    if (this.prevText.indexOf(".") !== -1 && actualText.indexOf(".") === -1) { 
     // deleted 
    } 

    this.prevText = actualText; 
}); 
... 
1

JsFiddle Demo

您可以使用此。

$(document).on('keyup paste', '#Quantity', function() {   
 
    if ($(this).val().indexOf('.') > -1) { 
 
    // disable the Gram option 
 
    $('#Unit').children('[value="1"]').prop('disabled', true); 
 
    } else{ 
 
    $('#Unit').children('[value="1"]').prop('disabled', false); 
 
\t } 
 
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script> 
 
<input id="Quantity" type="text"> 
 
    <select id="Unit"> 
 
     <option value="0">- select -</option> 
 
     <option value="1">Gram</option> 
 
     <option value="2">Kilo</option> 
 
     <option value="3">Quntal</option> 
 
    </select>

相关问题