1

我有一个表单,其中包含 2<select>个从 0 到 10 的字段。

我正在尝试根据两个字段值的数量.append <input>来字段#myDiv<select>

我已经有了这个:

jQuery(function($){
        $('select[name="nb_adultes"], select[name="nb_enfants"]').change(function() {
            var nb = $(this).val(); //the value of select
        });
});

例如,用户从第一个中选择“2”,<select>从第二个中选择“4”,<select>因此它将附加:4+2:“6”输入字段到"#myDiv"

重要提示:如果可能,附加输入的数量不能高于“10”

希望我清楚,谢谢帮助!

4

4 回答 4

0

一个相当直接的方法:

/* Cache selectors, and set limitation variables */
var adults = $("#adults"),
    infant = $("#infants"),
    msgDiv = $("#mydiv"),
    vLimit = 10;

/* Bind to adults and infants some onChange logic */
$(adults).add(infant).on("change", function(){
  /* Determine values, addition, and results */
  var aValue = parseInt( adults.val(), 10 ),
      iValue = parseInt( infant.val(), 10 ),
      result = aValue + iValue,
      differ = result - vLimit;

  /* If the user selected too many, inform them */
  if ( differ > 0 ) {
    /* Invalid amount: x too many. */
    msgDiv.html("Invalid amount: %d too many.".replace( /%d/, differ ));
    return;
  }

  /* Clear msgDiv, fill it with x input elements */
  var i = 0; msgDiv.empty(); 
  while ( i++ < result ) $("<input/>", { id: 'element'+i }).appendTo(msgDiv);
});

演示:http: //jsbin.com/etawas/8/edit

于 2012-04-25T14:45:10.650 回答
0

假设选择框的 id 是:'nb_adultes' 和 'nb_enfants'

jQuery(function($){
        $('#nb_adultes, #nb_enfants').change(function() {
            var nb = $('#nb_adultes').val() + $('#nb_enfants').val(); //the value of select
            if(nb >10)
              alert("Sum should not be greater then 10");

        });
});
于 2012-04-25T14:34:12.980 回答
0
jQuery(function($) {
    $('select[name="nb_adultes"], select[name="nb_enfants"]').change(function() {
        var total = parseInt($('select[name="nb_adultes"]').val()) + 
                    parseInt($('select[name="nb_enfants"]').val());
        if (total > 10) {
            alert("it cannot be higher than 10");
        } else {
            $("div").empty();
            for(var j=0; j < total; j++) 
              $("div").append('<input type="text" value="'+j+'"/><br />');
        }
        });
    });​

演示

于 2012-04-25T14:47:08.060 回答
0

将这两个值作为数字获取,如果不是数字则重置输入,并且仅在总数小于 10 时更新。

jQuery(function($){
  $('select[name="nb_adultes"], select[name="nb_enfants"]').change(function() {

    // the value of select option
    var nb = parseInt($(this).val());

    // the input
    var totalInput = $('#total');

    // if the input is user editable make sure they didn't put a non-numer in there
    if(isNaN(totalInput.val())) totalInput.val('');

    // get the total of the input
    var total = parseInt($('#total').val());

    // add the selected option if its less than 10
    if(total + nb <= 10) totalInput.val(total + nb);

    // do whatever you like or nothing if there are more than 10
    else { alert('more than 10);
  });
});
于 2012-04-25T14:47:59.203 回答