При вводе числового значения показывать «∞», если значение больше 50 - PullRequest
2 голосов
/ 21 ноября 2011

Как сделать так, чтобы при вводе чисел, пересекающих 50, поле заменялось текстом типа ввода со значением ∞ и заканчивалось, когда минус 51 снова обращал процесс к числам отображения. Можно добиться? Когда значение бесконечности мне нужно, например, скрытое поле со значением 51, чтобы понять данные после отправки на стороне сервера. Мои мертвые тесты ниже.

JQuery:

$("#order_quantity").live("change",function() {
    var tempField;
    if($(this).val() > 50) {
        $('<input type="text"/>').val("∞").appendTo("#order_quantity");
        tempField = $('<input type="hidden" name="order[quantity]" type="number" />').val(this).appendTo("#order_quantity");
    }else{
        tempField.remove();
        $('<input name="order[quantity]" type="number" />').val(this).appendTo("#order_quantity");
        $("body").append("<br>50<br>");
    }
});

HTML:

<input id="order_quantity" type="number" value="1" size="30" name="order[quantity]" min="0" max="51">

Ответы [ 2 ]

2 голосов
/ 22 ноября 2011

Один из способов обойти ограничения числового поля состоит в том, чтобы условно показать или скрыть метку, содержащую индикатор максимального значения и текст в поле ввода.

Вот пример jsfiddle: http://jsfiddle.net/CWq8D/

HTML:

Input has a max limit of 250, but displays '∞' after 50:
<input id="order_quantity" type="number" value="1" size="30" name="order[quantity]" min="0" max="250">
<br/>
Input has no max, but displays a '10+' after 10:
<input id="other_quantity" type="number" value="1" size="30" name="other[quantity]" min="0">

jquery.maxDisplay.js:

$.fn.maxDisplay = function( max, max_display ) {
  return this.each( function() {
    var $input = $( this );

    // Create a label that will position itself ontop of the input field.  The
    // label's text display will default to 'max+'.
    var $label = $('<label>');
    $label.html( max_display ? max_display : '' + max + '+')
          .css({ position : "absolute",
                 left     : "6px",
                 top      : "3px" });

    // Wrap the input in a div with relative position so that the label can be
    // positioned via absolute.
    $input.wrapAll( '<div style="position: relative;">' );

    // Insert label before the input.
    $input.before( $label );

    // Store off the input's text color.
    var color = $input.css( 'color' ); 

    function hide_label() {
      // If the label is already hidden, just return early.
      if ( !$label.is(':visible') ) return;
      $label.hide();

      // Reset the text color so that it is visible.
      $input.css({ color: color });
    };

    function show_label() {
      // If the label is already visible, just return early.
      if ( $label.is(':visible') ) return;

      $label.show();

      // The color property does not support transparent, so mimic this by
      // matching the background color.
      $input.css({ color: $input.css( 'background-color' ) });
    };

    // Control when the label is displayed.
    function display_label() {
      if ( max >=  $input.val()) {    
        hide_label()
      }
      else {
        show_label();
      }
    };

    // Invoke to set initial display.
    display_label();

    // Bind to events.
    $input.change( display_label ) // Display label based on value.
          .focus( hide_label )     // Hide label if input is focused.
          .blur( display_label );  // Hide/show label when input loses focus.

    // The label is sitting over the input field, so have its click behavior
    // mimic that of the input.
    $label.click( function() {
      hide_label();
      $input.focus();
    });
  });
};

И использование:

// Apply max display to the input divs.
$("#order_quantity").maxDisplay( 50, "∞" );
$("#other_quantity").maxDisplay( 10 );
0 голосов
/ 21 ноября 2011

Изменение типа ввода на text может помочь вам ^ _ ^

Попробуйте это: http://jsfiddle.net/maniator/dpsMa/

Код:

$("#order_quantity").live("change", function() {
    if (this.value > 50) {
        $(this).val("∞");
    } else if (this.value < -50) {
        $(this).val("-∞");
    } 
});
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...