根据选择值jQuery附加输入

时间:2012-04-25 14:28:11

标签: jquery input append

我的表单包含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
        });
});

例如,用户从第一个<select>中选择“2”,从第二个<select>中选择“4”,因此它会将{4 + 2:“6”输入字段添加到{{1} }

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

希望我很清楚,谢谢你的帮助!

4 个答案:

答案 0 :(得分: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");

        });
});

答案 1 :(得分: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

答案 2 :(得分: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 />');
        }
        });
    });​

DEMO

答案 3 :(得分: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);
  });
});