使用jquery keyup获取不同输入字段的值

时间:2015-04-12 02:17:09

标签: jquery

我有一个包含4个输入字段的表单

<div id="st5_one">
Top <input class="tb2" style="width:100px;" type="text" maxlength="3"   name="margin_top" placeholder="Margin top" value="5"> % 
Right <input class="tb2" style="width:100px;" type="text" maxlength="3" name="margin_right" placeholder="Margin right" value="5"> % 
Bottom <input class="tb2" style="width:100px;" type="text" maxlength="3" name="margin_bottom" placeholder="Margin bottom" value="5"> % 
Left <input class="tb2" style="width:100px;" type="text" maxlength="3" name="margin_left" placeholder="Margin left" value="5"> %
</div>

在我的代码中,我试图在任何字段中更改值时从所有字段中获取值

jQuery('input[name=margin_right]') .keyup(function(){
   //get the value in the input box
   var vl = jQuery(this).val();
   var image_right = (parseInt(vl))
   var image_top = $('#margin_top').val(); 
   alert("top is " + image_top)
   var image_top = jQuery('input[name=margin_top]').val();
   alert("top is " + image_top)
});

但我始终未定义image_top值。我得到了margin_right字段中输入的值。

1 个答案:

答案 0 :(得分:0)

这是关于jsfiddle的工作。您指定了错误的目标元素。您使用ID作为目标元素,但您的输入没有ID

https://jsfiddle.net/c8ms2ugo/

示例代码

HTML

<div id="st5_one">
Top 
<input id="top-input" class="tb2" style="width:100px;" type="text" maxlength="3" name="margin_top" placeholder="margin top">%

Right 
<input id="right-input" class="tb2" style="width:100px;" type="text" maxlength="3" name="margin_right" placeholder="margin right" value="5">%

Bottom <input id="bottom-input" class="tb2" style="width:100px;" type="text" maxlength="3" name="margin_bottom" placeholder="margin bottom" value="5">%

Left <input id="left-input" class="tb2" style="width:100px;" type="text" maxlength="3" name="margin_left" placeholder="margin left" value="5">%
</div>

的Javascript

jQuery('input[name=margin_right]') .keyup(function(){
   //get the value in the input box
   var vl = jQuery(this).val();
   var image_right = (parseInt(vl))

   var image_top = $('#top-input').val(); 
   alert('Top is ' + image_top)

   var image_bottom = $('#bottom-input').val(); 
    alert('Bottom is ' + image_bottom)

       var image_left = $('#left-input').val(); 
    alert('Left is ' + image_left)
});