使用jQuery基于文本框值更改div值

时间:2011-08-19 15:13:29

标签: javascript jquery

我创建了这个小提琴,div值根据你的下拉列表选择而改变。 http://jsfiddle.net/qSkZW/20/

我想更进一步,这是创建一个文本框字段,如果你添加例如数字2,它会将div值更改为240(实际上你在脚本中找到的120)它将是一个PHP var)。如果它将3写入360。

此外,必须有两个限制。

  1. 防止他们使用非数字字符。
  2. 最大数量是预先配置的(来自php变量)。就像最大值设置为10一样,如果用户写30,它将返回10。
  3. 感谢您的帮助。

3 个答案:

答案 0 :(得分:0)

好的,首先,创建一个文本字段(例如id =“textfield”),然后将你的监听器操作修改为

$("#quantity").change(function () {
    var price = parseInt($(this).val(), 10)*120
    $("#textfield").attr('value="'+price+'"');
    # sets the default value of #textfield to the selection from #quantity
    })
.change()

$("#textfield").blur(function () {
# when the element looses focus (they click/tab somewhere else)
        var valid = /^\d{2}$/;
        # this means any 2 numbers. change {2} to {3} or however many digits.
        # you can also also use d[0-10] to identify a range of numbers.

    if ( $(this).text() != valid ) {
        $("#message").text("Only numbers please!");
        $("#message").fadeIn();
        # add <span id="message" style="display:none;"></span> next to #textfield
        # enclose #textfield & #message in the same element (like <li> or <div>)
    }
    else {
        $("#message").fadeOut();
    }
});

请你提供更多关于#2的信息(我对这应该发生的事情没有清楚的了解)

快速提问:为什么要在可编辑元素中加价?

答案 1 :(得分:0)

var max = 30;
$('input').keyup(function() {
    var v = $(this).val();
    v = isNaN(v)?'':v;
    v = v > max ? max : v;
    $(this).val(v);
    $('div').html(v * 120);
});

http://jsfiddle.net/vWf2x/2/

答案 2 :(得分:0)

这样做:http://jsfiddle.net/ebiewener/pBeM8/

将keydown事件绑定到输入框以防止输入不需要的字符,并绑定keyup事件以检查值&amp;修改div的高度。

$('input').keydown(function(e){
   if(!(e.which >= 48 && e.which <=58) && e.which !== 8 && e.which !== 46 && e.which !== 37 && e.which !== 39){ //prevent anything other than numeric characters, backspace, delete, and left & right arrows
       return false;
   }
})
.keyup(function(){
   val = $(this).val();
   if(val > 10){
       val = 10;
       $(this).val(10);
   }
   $('div').height(val * 10);
});
相关问题